UNPKG

coffi

Version:

⚡️ A fast, lightweight, easy-to-use, configuration files loader 📄

2 lines (1 loc) 2.03 kB
import{existsSync as P,readdirSync as D}from"node:fs";import{readFile as E}from"node:fs/promises";import{dirname as h,join as y,resolve as j}from"node:path";class l{static instance;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}warn(n){console.warn(`\x1B[33mWARNING: ${n}\x1B[0m`)}debug(n){console.debug(`\x1B[34mDEBUG: ${n}\x1B[0m`)}error(n){console.error(`\x1B[31mERROR: ${n}\x1B[0m`)}}var m=l.getInstance();import k from"strip-json-comments";function C(n){return k(n).replace(/,\s*([}\]])/g,"$1").trim()}var b=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"];function $(n){try{return P(n)}catch{return!1}}async function x(n){try{if(!$(n))return null;if(n.slice(n.lastIndexOf(".")).toLowerCase()===".json"){let i=await E(n,"utf-8"),c=C(i);return JSON.parse(c)}let t=await import(n),e=t.default||t;if(typeof e==="function")e=e();if(e instanceof Promise)return e;return e}catch(r){return m.error(`Failed to parse config file: ${S(r)}`),null}}function S(n){if(n instanceof Error)return n.message;return String(n)}function v(n,r){let t=n,e=0;while(e<r){let i=y(t,"package.json");if($(i))return i;let c=h(t);if(c===t)break;t=c,e++}return null}async function T(n,r,t,e,i,c){if(c){let s=v(t,e);if(s){let o=await x(s);if(o&&typeof o==="object"&&c in o)return{config:o[c],filepath:s}}}if(i){let s=j(t,i),o=await x(s);if(o!==null)return{config:o,filepath:s};m.warn(`Preferred path "${i}" not found or invalid, searching for ${n} files instead.`)}let a=t,f=0;while(f<e){try{let o=D(a),p=new Set(o);for(let d of r){let u=`${n}${d}`;if(p.has(u)){let g=y(a,u),w=await x(g);if(w!==null)return{config:w,filepath:g}}}}catch(o){}let s=h(a);if(s===a)break;a=s,f++}return{config:null,filepath:null}}async function G(n,r=b,t={}){if(typeof n==="string"){let o=n,{cwd:p=process.cwd(),maxDepth:d=10,preferredPath:u,packageJsonProperty:g}=t;return T(o,r,p,d,u,g)}let{name:e,extensions:i=b,cwd:c=process.cwd(),maxDepth:a=10,preferredPath:f,packageJsonProperty:s}=n;return T(e,i,c,a,f,s)}export{G as loadConfig};