@rzl-zone/utils-js
Version:
A modern, lightweight set of JavaScript utility functions for everyday development, crafted to enhance code readability and maintainability.
1 lines • 4.97 kB
JavaScript
function E(r){return Array.isArray(r)}var o=r=>typeof r=="string";var h=(r,e)=>{if(!o(r))return true;s(e)||(e={});let{trim:n=true}=e;return n&&(r=r.trim()),r===""};var d=r=>typeof r=="boolean";var $=r=>r instanceof Error;function T(r){return Array.isArray(r)&&r.length>0}function s(r){return typeof r=="object"&&!v(r)&&!E(r)}var p=(r,e)=>{if(!o(r))return false;s(e)||(e={});let{trim:n=true}=e;return(n?r.trim():r).length>0};var u=r=>typeof r>"u";function v(r){return r==null}var c=(r,e={trimOnly:false})=>{if(!p(r))return "";s(e)||(e={});let{trimOnly:n=false}=e;return n?r.trim():r.replace(/\s+/g,"")};var w=(r,e="/")=>{if(!p(e))throw new TypeError(`Invalid parameter:'defaultPath' must be a string and string is non-empty string. Received:${typeof e}(${e})`);if(!p(r))return e;try{if(r=c(r,{trimOnly:!0}),r=r.replace(/\s+/g,""),r.startsWith("http://")||r.startsWith("https://")){let n=new URL(r);return `${n.pathname}${n.search}${n.hash}`.replace(/^\/+/,"/")}return "/"+r.replace(/^\/+/,"").replace(/\/{2,}/g,"/")}catch(n){let t=$(n)?n:new Error("Unknown error from function `normalizePathname()`");throw new x(`Failed to normalize pathname in function \`normalizePathname()\`:${t.message}`,t)}};var y=(r,e)=>{if(!p(r))return "";if(!u(e)){if(!s(e))throw new TypeError("Options must be an object.");if("prefixColon"in e&&!d(e.prefixColon))throw new TypeError("Option `prefixColon` must be a boolean.")}let n=r.replace(/\D+/g,"");return n?e?.prefixColon??false?`:${n}`:n:""};var x=class r extends Error{constructor(n,t){super(n);this.originalError=t;this.name="NormalizePathnameError",Error.captureStackTrace&&Error.captureStackTrace(this,r);}};function G(r,e){if(!o(r)||h(r))throw new TypeError(`\u{1F6A8}'generateRoute' Failed:- Invalid 'route' value.- Expected a non-empty string,but received ${typeof r}:${JSON.stringify(r)}`);if(!r.includes("["))return r;if(!s(e))throw new Error(`\u{1F6A8}'generateRoute' Failed cause in route "${r}":- Missing or invalid parameters object for route:"${r}",expected an object mapping parameters.`);if(!e)throw new Error(`\u{1F6A8}'generateRoute' Failed cause in route "${r}":- Missing parameters object for route:"${r}"`);let n=["?","&","#","=","/"," ","'",'"',"(",")","+",";","%","@",":"],t=[],i=Array.from(r.matchAll(/\[(\w+)\]/g)).map(a=>a[1]);for(let a of i){let l=e[a];if(u(l)){t.push(`- Missing parameter:"${a}".`);continue}let f=l.trim();if(!f){t.push(`- Parameter "${a}" cannot be empty.`);continue}f.includes("/")&&t.push(`- Parameter "${a}" contains slashes "/" which is not allowed.`);let g=n.filter(m=>m!=="/").filter(m=>f.includes(m));g.length>0&&t.push(`- Parameter "${a}" contains invalid characters(${g.length>1?g.join(","):g}). These characters are not allowed because they could cause issues in URL structure. The following characters are forbidden in route parameters:(${n.join(",")}).`);}if(T(t))throw new Error(`\u{1F6A8}'generateRoute' Failed cause in route "${r}":${t.join(``)}`);return r.replace(/\[(\w+)\]/g,(a,l)=>e[l].trim().replace(/^\/+|\/+$/g,"")).replace(/\/+/g,"/")}var rr=(r="",e)=>{try{let f=function(m,P){return `${m.replace(/\/+$/,"")}/${P.replace(/^\/+/,"")}`};var n=f;if(!o(r))throw new TypeError(`Invalid type for 'pathname'. Expected 'string',received:${typeof r}`);s(e)||(e={});let{prefix:t="/api",withOrigin:i=!0}=e;if(!u(t)&&!o(t))throw new TypeError(`Invalid type for 'prefix'. Expected 'string',received:${typeof t}`);if(!d(i))throw new TypeError(`Invalid type for 'withOrigin'. Expected 'boolean',received:${typeof i}`);r=w(r),t=w(t);let a=t.endsWith("/")?t:t+"/";(r===t||r===t+"/"||r.startsWith(a))&&(r=r.slice(t.length),r=w(r));let l=b({suffix:t});return f(i?l:new URL(l).pathname,r).replace(/\/+$/,"")}catch(t){throw new Error("Failed to generate backend API URL in `createBeApiUrl()`,Error:"+t)}};var b=({suffix:r="/"}={})=>{if(!o(r))throw new TypeError(`Invalid type for 'suffix'. Expected string,received:${typeof r}`);try{let e=process.env.NEXT_PUBLIC_BACKEND_API_URL?.trim();if(e){e=c(e);let i=new URL(e);!!!i.port&&process.env.NEXT_PUBLIC_PORT_BE&&(e=i.origin+y(process.env.NEXT_PUBLIC_PORT_BE,{prefixColon:!0}));}else e="http://localhost"+y(process.env.NEXT_PUBLIC_PORT_BE||"8000",{prefixColon:!0});r=c(r).length?c(r):"/";let n=new URL(e.replace(/\/+$/,"")).origin,t=r==="/"?"/":`${r.startsWith("/")?"":"/"}${r.replace(/\/+$/,"")}`;return `${n}${t}`}catch(e){throw new Error("Invalid `NEXT_PUBLIC_BACKEND_API_URL`,failed to generate from `getBeApiUrl()`,Error:"+e)}};var or=()=>{try{let r=process.env.NEXT_PUBLIC_BASE_URL?.trim(),e=process.env.NEXT_PUBLIC_PORT_FE?.trim(),n=r||"http://localhost";n=c(n).replace(/\/+$/,"");let t=/:\/\/[^/]+:\d+/.test(n);!t&&e?n+=y(e,{prefixColon:!0}):!t&&!r&&(n+=":3000");let i=new URL(n);return `${i.protocol}//${i.hostname}${i.port?`:${i.port}`:""}`}catch(r){throw new Error("Invalid `NEXT_PUBLIC_BASE_URL`,failed to generate from `getBaseUrl()`,Error:"+r)}};export{rr as createBeApiUrl,G as generateRoute,or as getBaseUrl,b as getBeApiUrl};