validate-env-vars
Version:
A lightweight utility to check the presence and validity of environment variables, as specified by a Zod schema
3 lines (2 loc) • 2.8 kB
JavaScript
var x=Object.defineProperty,L=Object.defineProperties;var _=Object.getOwnPropertyDescriptors;var y=Object.getOwnPropertySymbols;var C=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable;var E=(e,o,t)=>o in e?x(e,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[o]=t,m=(e,o)=>{for(var t in o||(o={}))C.call(o,t)&&E(e,t,o[t]);if(y)for(var t of y(o))j.call(o,t)&&E(e,t,o[t]);return e},O=(e,o)=>L(e,_(o));import{config as W}from"dotenv";import{expand as z}from"dotenv-expand";import{existsSync as w}from"fs";import{ZodObject as P}from"zod";var d="\x1B[31m",l="\x1B[33m",c="\x1B[32m",s="\x1B[0m",v=`${d}\u2715${s}`,u=`${c}\u2714${s}`,R=`${l}\u26A0${s}`,g=["ZodString","ZodEnum","ZodLiteral","ZodEffects","ZodUnion","ZodOptional"];function T(e){if(!(e instanceof P))throw new Error(`The provided schema must be a ZodObject. Received: ${typeof e}`);Object.values(e.shape).forEach(o=>{let t=o._def.typeName;if(!g.includes(t))throw new Error(`All fields in the schema must be Zod strings, Zod literals, or Zod enums. Received: ${t}`)})}function Z(e){if(!w(e))throw new Error(`File not found: ${e}`)}function A(e,o,t){let a={};for(let n of Object.keys(o.shape))a[n]={optional:o.shape[n].isOptional(),error:null,data:`${process.env[n]}`};if(e.success)for(let n of Object.keys(e.data))a[n].data=e.data[n];else for(let n of e.error.issues){let r=n.path[0],p=n.message;a[r]=O(m({},a[r]),{data:null,error:p})}let i=0;return Object.entries(a).forEach(([n,r])=>{var f;let p="";if(typeof((f=o.shape[n])==null?void 0:f.description)=="string"&&(p=`
\r - ${o.shape[n].description}`),r.error===null&&r.data!==""&&r.data!=="undefined"){let S=t?` ${c}'${r.data}'${s}`:"";console.log(`${u} ${n}${S}`)}else r.error===null&&r.optional?console.log(`${R} ${n} ${l}'${r.data}'${s}${p}`):(console.error(`${v} ${n}: ${d}${r.error}${s}${p}`),i++)}),i}var $=A;import{string as G,enum as H,literal as J,z as b}from"zod";var h=e=>b.string(e).min(1,{message:"Variable cannot be empty"}),X=e=>h(e).refine(o=>o!="undefined",{message:"Variable cannot equal 'undefined'"}),ee=e=>h(e).regex(/^-?\d+$/,{message:"Variable must be a valid integer"}),oe=e=>b.object(e);function K(e){let{schema:o,envPath:t,logVars:a}=e;T(o),Z(t);let i=W({path:t});if(i.error)throw new Error(i.error.message);z(i);let n=o.safeParse(process.env),r=$(n,o,a);if(!n.success)throw new Error(`${r} missing or invalid environment variable${r===1?"":"s"}`);console.log(`${c}All required environment variables are valid${s}`)}function M({schema:e,envPath:o=".env",exitOnError:t=!1,logVars:a=!0}){try{K({schema:e,envPath:o,logVars:a})}catch(i){if(t)console.error(`${d}${i.message}${s}`),process.exit(1);else throw i}}var pe=M;export{pe as default,H as envEnum,ee as envInteger,J as envLiteral,X as envNonEmptyString,oe as envObject,G as envString};