UNPKG

zod-config

Version:

Load configuration variables from multiple sources with flexible adapters, ensuring type safety with Zod.

2 lines (1 loc) 1.95 kB
function c(e){return!e||typeof e!="object"?!1:Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null}function u(e,...n){if(!n.length)return e;let r=n.shift();return r===void 0?e:(c(e)&&c(r)&&Object.keys(r).forEach(t=>{if(r[t]===void 0)return;if(!c(r[t])){e[t]=r[t];return}let s=e[t];if(!c(s)){e[t]=u({},r[t]);return}u(s,r[t])}),u(e,...n))}import{ZodObject as w}from"zod/v3";import*as d from"zod/v4/core";var j={strict:b(e=>e),lenient:b(T)},O=100;function p(e,n,r,t=0,s=O){if(t>=s||!e||!n||Object.keys(e).length===0||Object.keys(n).length===0)return e;let a=j[r];return Object.fromEntries(Object.entries(e).map(([o,f])=>{let i=Object.keys(n).find(h=>a(h,o))??o;if(!c(f))return[i,f];let m=n[i],l=y(m);return l?[i,p(f,l,r,t+1)]:[i,f]}))}function T(e){return e.replace(/[^a-z0-9]/gi,"").toLowerCase()}function g(e){return e instanceof d.$ZodObject}function z(e){return e instanceof w}function Z(e){return e instanceof d.$ZodPipe&&g(e._zod.def.in)}function x(e){return e instanceof d.$ZodPipe&&g(e._zod.def.out)}function b(e){return(n,r)=>e(n)===e(r)}function C(e){if(g(e))return e._zod.def.shape;if(Z(e))return e._zod.def.in._zod.def.shape;if(x(e))return e._zod.def.out._zod.def.shape}function P(e){if(z(e))return e.shape}var y=e=>{if(e)return"_zod"in e?C(e):P(e)};import{safeParseAsync as R}from"zod/v4/core";var S=async e=>{let{schema:n,adapters:r,onError:t,onSuccess:s,keyMatching:a}=e,o=e.logger??console,f=await A(Array.isArray(r)?r:r?[r]:[],o,n,a??"strict"),i;if("_zod"in n?i=await R(n,f):i=await n.safeParseAsync(f),!i.success){if(t)return t(i.error),{};throw i.error}return s&&s(i.data),i.data},A=async(e,n,r,t)=>{if(!e||e.length===0)return process.env;let s=await Promise.all(e.map(async a=>{try{let o=await a.read();if(t==="strict")return o;let f=y(r);return f?p(o,f,t):o}catch(o){return a.silent||n.warn(`Cannot read data from ${a.name}: ${o instanceof Error?o.message:o}`),{}}}));return u({},...s)};export{S as loadConfig};