UNPKG

gnablib

Version:

A lean, zero dependency library to provide a useful base for your project.

2 lines 1.73 kB
/*! Copyright 2024 the gnablib contributors MPL-1.1 */ import{log as e}from"./Log.js";import{callFrom as t}from"./callFrom.js";class s{constructor(e,t,s){this.key=e,this.defaultValue=t,this.guard=s,this.reason="default",this.typ=typeof t,this._v=t}get value(){return this.guard&&e.warn("guarded config access",{key:this.key,caller:t(2)}),this._v}valueIfType(s){if(this.typ===s)return this.guard&&e.warn("guarded config access",{key:this.key,caller:t(2)}),this._v;e.info("incorrect type access",{key:this.key,have:this.typ,seek:s})}setValue(e,t){this._v=e,this.reason=t}}class n{constructor(e){this.el=e}importEnv(e,t){return process?(t(process.env[e],(t=>this.el.setValue(t,"env."+e))),this):this}importAvailEnv(e,t){if(!process)return this;const s=process.env[e];return null==s||t(s,(t=>this.el.setValue(t,"env."+e))),this}}export const config=new class{constructor(){this._defs=new Map}define(e,t,r=!1){if(this._defs.has(e))throw new Error("$key already defined");const o=new s(e,t,r);return this._defs.set(e,o),new n(o)}set(e,t,s){const n=this._defs.get(e);if(!n)throw new Error(`${e} not found`);const r=typeof t;if(r!==n.typ)throw new Error(`${e} is type ${n.typ}, got ${r}`);n.setValue(t,null!=s?s:"direct set")}getBool(t,s=!1){const n=this._defs.get(t);if(!n)return e.debug("unknown config",{key:t}),s;const r=n.valueIfType("boolean");return null==r?s:r}getInvertedBool(t,s=!1){const n=this._defs.get(t);if(!n)return e.debug("unknown config",{key:t}),s;const r=n.valueIfType("boolean");return null==r?s:!r}getString(t,s=""){const n=this._defs.get(t);if(!n)return e.debug("unknown config",{key:t}),s;const r=n.valueIfType("string");return null==r?s:r}getValueReason(e){const t=this._defs.get(e);if(t)return[t.value,t.reason]}};