UNPKG

link-exists

Version:

A super lightweight JavaScript / TypeScript library to check whether a given url is valid and exists or not.

3 lines (2 loc) 2.21 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});const t=/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g,e=/^https?:\/\//i;function o(t){const e=new AbortController;if(void 0===t||t<=0)return{signal:e.signal,clearTimer:()=>{}};const o=setTimeout((()=>{e.abort()}),t);return{signal:e.signal,clearTimer:()=>{clearTimeout(o)}}}async function r(t,e,o){try{return await fetch(t,{method:e,redirect:"follow",signal:o})}catch{return null}}function n(t){return{exists:t.ok,status:t.status,url:t.url}}function i(t){return{exists:!1,status:0,url:t}}exports.linkExists=async function(l,a){if("string"!=typeof l)throw new TypeError("Expected a string, got "+typeof l);!function(t){if(t){if(t.ignoreProtocol&&"boolean"!=typeof t.ignoreProtocol)throw new TypeError("Expected a boolean, got "+typeof t.ignoreProtocol);if(void 0!==t.timeout&&("number"!=typeof t.timeout||!Number.isFinite(t.timeout)||t.timeout<0))throw new TypeError("Expected timeout to be a non-negative finite number");if(void 0!==t.method&&"HEAD"!==t.method&&"GET"!==t.method)throw new TypeError("Expected method to be HEAD or GET");if(void 0!==t.fallbackToGet&&"boolean"!=typeof t.fallbackToGet)throw new TypeError("Expected a boolean, got "+typeof t.fallbackToGet);if(void 0!==t.details&&"boolean"!=typeof t.details)throw new TypeError("Expected a boolean, got "+typeof t.details)}}(a);const c=!0===a?.details;if(null===l.match(t))return!!c&&i(l);const u=function(t,o){try{let r=t;return"boolean"==typeof o&&!0===o&&(r=e.test(r)?r:`http://${r}`),new URL(r.trim())}catch(t){return null}}(l,a?.ignoreProtocol);if(!u)return!!c&&i(l.trim());if("undefined"==typeof AbortController||"function"!=typeof fetch)return!!c&&i(u.href);const{href:f}=u,s=a?.timeout,p=a?.method??"HEAD",y=!1!==a?.fallbackToGet;if("GET"===p){const t=o(s);try{const e=await r(f,"GET",t.signal);return c?e?n(e):i(f):null!==e}finally{t.clearTimer()}}const d=o(s);let m=null;try{m=await r(f,"HEAD",d.signal)}finally{d.clearTimer()}if(null!==m)return!c||n(m);if(!y)return!!c&&i(f);const h=o(s);try{const t=await r(f,"GET",h.signal);return c?t?n(t):i(f):null!==t}finally{h.clearTimer()}}; //# sourceMappingURL=index.js.map