url-normalize
Version:
Normalize URLs to a standardized form. HTTPS by default, flexible configuration, custom protocols, domain extraction, humazing URL, and punycode support. Both CJS & ESM modules available.
2 lines (1 loc) • 2.52 kB
JavaScript
var d=Object.defineProperty;var c=(t,r)=>d(t,"name",{value:r,configurable:!0});var w=require("punycode");const g={auth:!1,customProtocol:!1,defaultProtocol:"https",fragment:!0,index:!0,port:!0,protocol:!0,search:!0,sortSearch:!0,textFragment:!1,unicode:!1,www:!1},l=c(t=>{try{return t()}catch{return null}},"canFail"),n=c((t,r)=>{if(r={...g,...r},t=t.trim(),!/^[a-z0-9.+-]*:\/\//i.test(t)){if(/^[a-z0-9.+-]*:[^0-9]/i.test(t))throw new Error("Unsupported protocol");t=`${r.defaultProtocol}://${t}`}const e=new URL(t);if(!r.customProtocol&&!["http:","https:",`${r.defaultProtocol}:`].includes(e.protocol)&&!r.forceProtocol)throw new Error("Invalid protocol");if(e.hostname=e.hostname.replace(/^\.*/,""),e.hostname=e.hostname.replace(/\.*$/,""),!r.www){const a=e.hostname.split(".");a.length===3&&a[0]==="www"&&(e.hostname=a.slice(1).join("."))}if(e.hostname.split(".").filter(a=>a!=="").length<2)throw new Error("Invalid domain");if(r.auth||(e.username="",e.password=""),r.port||(e.port=""),l(()=>e.pathname=decodeURI(e.pathname)),r.index||(e.pathname=e.pathname.replace(/\/index\.[a-z0-9]+$/i,"/")),e.pathname=e.pathname.replace(/(^|[^:])\/{2,}(?!\/)/g,"$1/"),!r.search)e.search="";else{if(e.search=e.search.replace(/&$/,""),e.search=e.search.replace(/&{2,}/,"&"),e.search=e.search.replace(/%20/g,"+"),r.filterSearch){const a=new URLSearchParams(e.search);for(const[i,p]of a.entries())r.filterSearch(i,p)||a.delete(i);e.search=a.toString()}r.sortSearch&&(e.searchParams.sort(),l(()=>e.search=decodeURIComponent(e.searchParams.toString())))}r.fragment?r.textFragment||(e.hash=e.hash.replace(/#?:~:text.*?$/i,"")):e.hash="";let o=e.toString();o.endsWith("/")&&!o.endsWith("/#/")&&(o=o.slice(0,-1));let h=e.protocol;if(r.forceProtocol){const a=new RegExp(`^${e.protocol}//`,"i");o=o.replace(a,`${r.forceProtocol}://`),h=`${r.forceProtocol}:`}if(!r.protocol){const a=new RegExp(`^${h}//`,"i");o=o.replace(a,"")}if(r.unicode){const a=w.toUnicode(e.hostname);o=o.replace(e.hostname,a)}return o},"urlNormalizeOrFail"),m=c((t,r)=>l(()=>n(t??"",r)),"urlNormalize"),x=c(t=>(r,s)=>m(r,{...t,...s}),"createUrlNormalize"),f=c(t=>{const r=n(t);return new URL(r).hostname},"extractDomainOrFail"),z=c(t=>l(()=>f(t??"")),"extractDomain"),u=c((t,r)=>n(t,{...r,protocol:!1}),"humanizeUrlOrFail"),U=c((t,r)=>l(()=>u(t??"",r)),"humanizeUrl");exports.createUrlNormalize=x,exports.extractDomain=z,exports.extractDomainOrFail=f,exports.humanizeUrl=U,exports.humanizeUrlOrFail=u,exports.urlNormalize=m,exports.urlNormalizeOrFail=n;
;