@stacksjs/env 0.70.160 → 0.70.161

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // @bun
2
2
  import{createCipheriv as s,createDecipheriv as a,createHash as E,randomBytes as u}from"crypto";function t(J,Q){let X=u(16),$=Q.length===32?Q:Buffer.from(Q.toString("hex").slice(0,64),"hex"),Z=s("aes-256-gcm",$,X),j=Buffer.concat([Z.update(J,"utf8"),Z.final()]),A=Z.getAuthTag();return{ciphertext:j.toString("hex"),iv:X.toString("hex"),authTag:A.toString("hex")}}function e(J,Q,X,$){let Z=Q.length===32?Q:Buffer.from(Q.toString("hex").slice(0,64),"hex");try{let j=a("aes-256-gcm",Z,Buffer.from(X,"hex"));return j.setAuthTag(Buffer.from($,"hex")),Buffer.concat([j.update(Buffer.from(J,"hex")),j.final()]).toString("utf8")}catch(j){throw Error(`Decryption failed (data may be corrupted or key is incorrect): ${j instanceof Error?j.message:String(j)}`)}}function w(){let J=u(32);return{publicKey:E("sha256").update(J).digest().toString("hex"),privateKey:J.toString("hex")}}function K(J,Q){let X=E("sha256").update(Buffer.from(Q,"hex")).digest(),{ciphertext:$,iv:Z,authTag:j}=t(J,X);return`encrypted:${Buffer.concat([Buffer.from(Z,"hex"),Buffer.from(j,"hex"),Buffer.from($,"hex")]).toString("base64")}`}function f(J,Q){if(!J.startsWith("encrypted:"))return J;let X=J.slice(10),$=Buffer.from(X,"base64");if($.length<32)throw Error("Invalid encrypted data: payload too short (need at least iv + authTag = 32 bytes)");let Z=$.subarray(0,16).toString("hex"),j=$.subarray(16,32).toString("hex"),A=$.subarray(32).toString("hex"),Y=E("sha256").update(Buffer.from(Q,"hex")).digest(),G=E("sha256").update(Y).digest();return e(A,G,Z,j)}function DJ(J){let Q=J.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return Q&&Q[1]?Q[1].toLowerCase():""}function c(J=""){if(!J)return process.env.DOTENV_PRIVATE_KEY;let Q=`DOTENV_PRIVATE_KEY_${J.toUpperCase()}`;return process.env[Q]}function L(J,Q={}){let X={},$=[],Z=[],j=J.split(`
3
3
  `);for(let A of j){let Y=A.trim();if(!Y||Y.startsWith("#"))continue;if(Y.startsWith("DOTENV_PUBLIC_KEY=")){let _=Y.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(_&&_[1]!==void 0)X.DOTENV_PUBLIC_KEY=_[1];continue}let G=Y.match(/^([^=]+)=(.*)$/);if(!G||G[1]===void 0||G[2]===void 0)continue;let W=G[1].trim(),O=G[2].trim();if(O.startsWith('"')&&O.endsWith('"')||O.startsWith("'")&&O.endsWith("'")){if(O=O.slice(1,-1),O.includes("\\n"))O=O.replace(/\\n/g,`
4
- `)}if(O.startsWith("encrypted:")||O.startsWith("enc:")){if(!Q.privateKey){Z.push(W);continue}try{let _=O.startsWith("enc:")?`encrypted:${O.slice(4)}`:O;O=f(_,Q.privateKey)}catch(_){$.push(`Failed to decrypt ${W}: ${_ instanceof Error?_.message:"Unknown error"}`)}}O=JJ(O,{...Q.processEnv||process.env,...X}),O=ZJ(O),X[W]=O}return{parsed:X,errors:$,skippedEncrypted:Z}}function JJ(J,Q){return J.replace(/\$\{([^}]+)\}/g,(X,$)=>{let Z=$.match(/^([^:\-+]+)(:-|-)(.+)$/);if(Z){let[,A,Y,G]=Z,W=Q[A];if(Y===":-")return W||G;else return W!==void 0?W:G}let j=$.match(/^([^:\-+]+)(:?\+)(.+)$/);if(j){let[,A,Y,G]=j,W=Q[A];if(Y===":+")return W?G:"";else return W!==void 0?G:""}return Q[$]||""})}var QJ=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function ZJ(J){return J.replace(/\$\(([^)]+)\)/g,(Q,X)=>{try{let $=X.trim().split(/\s+/),Z=$[0];if(!Z||!QJ.has(Z))return console.warn(`[env] Blocked command substitution for disallowed command: ${Z}`),"";let j=Bun.spawnSync($,{stdout:"pipe",stderr:"pipe"});if(j.exitCode===0)return new TextDecoder().decode(j.stdout).trim();console.warn(`[env] Command substitution failed (exit code ${j.exitCode}): ${Z}`)}catch($){console.warn(`[env] Command substitution error: ${$ instanceof Error?$.message:String($)}`)}return""})}async function IJ(J,Q={}){let X={},$=[],Z=[];for(let j of J)try{let A=Bun.file(j);if(!A.size)continue;let Y=await A.text(),{parsed:G,errors:W,skippedEncrypted:O}=L(Y,Q);$.push(...W),Z.push(...O);for(let[_,U]of Object.entries(G)){if(!Q.overload&&X[_]!==void 0)continue;X[_]=U}}catch(A){if(A?.code==="ENOENT")continue;$.push(`Failed to read ${j}: ${A instanceof Error?A.message:String(A)}`)}return{parsed:X,errors:$,skippedEncrypted:Z}}import{existsSync as h}from"fs";import{readFileSync as v}from"fs";import{resolve as m}from"path";function P(J){return typeof J==="string"&&(J.startsWith("encrypted:")||J.startsWith("enc:"))}function N(J){if(!J||P(J))return;let Q=J.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(Q))return;if(Q==="prod")return"production";if(Q==="stage")return"staging";if(Q==="dev")return"development";return Q}function y(J={}){let{path:Q=[".env"],overload:X=!1,env:$,privateKey:Z,keysFile:j=".env.keys",quiet:A=!1,cwd:Y=process.cwd()}=J,G=Array.isArray(Q)?Q:[Q],W=[],O=0,_=new Set(Object.entries(process.env).filter(([,H])=>H!==void 0&&!P(H)).map(([H])=>H)),U=Z;if(!U&&j){let H=m(Y,j);if(h(H))try{let q=v(H,"utf-8"),{parsed:B}=L(q);if($){let z=`DOTENV_PRIVATE_KEY_${$.toUpperCase()}`;U=B[z]}else U=B.DOTENV_PRIVATE_KEY}catch(q){W.push(`Failed to load keys file: ${q instanceof Error?q.message:"Unknown error"}`)}}if(!U)U=c($||"");for(let H of G){let q=m(Y,H);if(!h(q)){if(!A)W.push(`File not found: ${q}`);continue}try{let B=v(q,"utf-8"),{parsed:z,errors:D,skippedEncrypted:M}=L(B,{privateKey:U,processEnv:process.env});if(W.push(...D),M.length>0){for(let S of M)if(P(process.env[S]))delete process.env[S];let T=$?`DOTENV_PRIVATE_KEY_${$.toUpperCase()}`:"DOTENV_PRIVATE_KEY",b=M.slice(0,5).join(", "),x=M.length>5?`, \u2026 +${M.length-5} more`:"";console.warn(`[env] warning: skipped ${M.length} encrypted value(s) in ${H} (${T} not set; defaults apply): ${b}${x}`)}let I=0;for(let[T,b]of Object.entries(z)){if(T==="DOTENV_PUBLIC_KEY")continue;let x=process.env[T],S=P(x)&&b!==x;if(X||!_.has(T)||S)process.env[T]=b,O++,I++}if(!A&&!process.env.__ENV_LOADED__)console.log(`[env] loaded ${I}/${Object.keys(z).length} variables from ${H}`),process.env.__ENV_LOADED__="1"}catch(B){W.push(`Failed to load ${q}: ${B instanceof Error?B.message:"Unknown error"}`)}}return{loaded:O,errors:W}}function $J(J={}){return{name:"env-plugin",setup(Q){y(J)}}}function wJ(J={}){let Q=N(J.env)||N("development")||N(process.env.DOTENV_ENV)||N(process.env.APP_ENV)||"development",X=J.cwd||process.cwd(),$=[],Z=(Y)=>{if(!$.includes(Y)&&h(m(X,Y)))$.push(Y)};Z(".env"),Z(".env.local");let j=`.env.${Q}`,A=`.env.${Q}.local`;return Z(j),Z(A),y({...J,path:$,env:Q})}var xJ=$J;import{existsSync as F,readFileSync as C,writeFileSync as V}from"fs";import{resolve as g}from"path";function XJ(J={}){let Q=J.cwd||process.cwd(),X=g(Q,J.file||".env"),$=g(Q,J.keysFile||".env.keys");if(!F(X))return{success:!1,error:`File not found: ${X}`};try{let Z,j;if(F($)){let U=C($,"utf-8"),{parsed:H}=L(U),z=((J.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),D=z?`DOTENV_PUBLIC_KEY_${z}`:"DOTENV_PUBLIC_KEY",M=z?`DOTENV_PRIVATE_KEY_${z}`:"DOTENV_PRIVATE_KEY";if(Z=H[D]||"",j=H[M]||"",!Z||!j){let I=w();Z=I.publicKey,j=I.privateKey;let T=`
4
+ `)}if(O.startsWith("encrypted:")||O.startsWith("enc:")){if(!Q.privateKey){Z.push(W);continue}try{let _=O.startsWith("enc:")?`encrypted:${O.slice(4)}`:O;O=f(_,Q.privateKey)}catch(_){$.push(`Failed to decrypt ${W}: ${_ instanceof Error?_.message:"Unknown error"}`)}}O=JJ(O,{...Q.processEnv||process.env,...X}),O=ZJ(O),X[W]=O}return{parsed:X,errors:$,skippedEncrypted:Z}}function JJ(J,Q){return J.replace(/\$\{([^}]+)\}/g,(X,$)=>{let Z=$.match(/^([^:\-+]+)(:-|-)(.+)$/);if(Z){let[,A,Y,G]=Z,W=Q[A];if(Y===":-")return W||G;else return W!==void 0?W:G}let j=$.match(/^([^:\-+]+)(:?\+)(.+)$/);if(j){let[,A,Y,G]=j,W=Q[A];if(Y===":+")return W?G:"";else return W!==void 0?G:""}return Q[$]||""})}var QJ=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function ZJ(J){return J.replace(/\$\(([^)]+)\)/g,(Q,X)=>{try{let $=X.trim().split(/\s+/),Z=$[0];if(!Z||!QJ.has(Z))return console.warn(`[env] Blocked command substitution for disallowed command: ${Z}`),"";let j=Bun.spawnSync($,{stdout:"pipe",stderr:"pipe"});if(j.exitCode===0)return new TextDecoder().decode(j.stdout).trim();console.warn(`[env] Command substitution failed (exit code ${j.exitCode}): ${Z}`)}catch($){console.warn(`[env] Command substitution error: ${$ instanceof Error?$.message:String($)}`)}return""})}async function IJ(J,Q={}){let X={},$=[],Z=[];for(let j of J)try{let A=Bun.file(j);if(!A.size)continue;let Y=await A.text(),{parsed:G,errors:W,skippedEncrypted:O}=L(Y,Q);$.push(...W),Z.push(...O);for(let[_,U]of Object.entries(G)){if(!Q.overload&&X[_]!==void 0)continue;X[_]=U}}catch(A){if(A?.code==="ENOENT")continue;$.push(`Failed to read ${j}: ${A instanceof Error?A.message:String(A)}`)}return{parsed:X,errors:$,skippedEncrypted:Z}}import{existsSync as h}from"fs";import{readFileSync as v}from"fs";import{resolve as m}from"path";function P(J){return typeof J==="string"&&(J.startsWith("encrypted:")||J.startsWith("enc:"))}function N(J){if(!J||P(J))return;let Q=J.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(Q))return;if(Q==="prod")return"production";if(Q==="stage")return"staging";if(Q==="dev")return"development";return Q}function y(J={}){let{path:Q=[".env"],overload:X=!1,env:$,privateKey:Z,keysFile:j=".env.keys",quiet:A=!1,cwd:Y=process.cwd()}=J,G=Array.isArray(Q)?Q:[Q],W=[],O=0,_=new Set(Object.entries(process.env).filter(([,H])=>H!==void 0&&!P(H)).map(([H])=>H)),U=Z;if(!U&&j){let H=m(Y,j);if(h(H))try{let q=v(H,"utf-8"),{parsed:B}=L(q);if($){let z=`DOTENV_PRIVATE_KEY_${$.toUpperCase()}`;U=B[z]}else U=B.DOTENV_PRIVATE_KEY}catch(q){W.push(`Failed to load keys file: ${q instanceof Error?q.message:"Unknown error"}`)}}if(!U)U=c($||"");for(let H of G){let q=m(Y,H);if(!h(q)){if(!A)W.push(`File not found: ${q}`);continue}try{let B=v(q,"utf-8"),{parsed:z,errors:D,skippedEncrypted:M}=L(B,{privateKey:U,processEnv:process.env});if(W.push(...D),M.length>0){for(let S of M)if(P(process.env[S]))delete process.env[S];let T=$?`DOTENV_PRIVATE_KEY_${$.toUpperCase()}`:"DOTENV_PRIVATE_KEY",b=M.slice(0,5).join(", "),x=M.length>5?`, \u2026 +${M.length-5} more`:"";console.warn(`[env] warning: skipped ${M.length} encrypted value(s) in ${H} (${T} not set; defaults apply): ${b}${x}`)}let I=0;for(let[T,b]of Object.entries(z)){if(T==="DOTENV_PUBLIC_KEY")continue;let x=process.env[T],S=P(x)&&b!==x;if(X||!_.has(T)||S)process.env[T]=b,O++,I++}if(!A&&!process.env.__ENV_LOADED__)console.error(`[env] loaded ${I}/${Object.keys(z).length} variables from ${H}`),process.env.__ENV_LOADED__="1"}catch(B){W.push(`Failed to load ${q}: ${B instanceof Error?B.message:"Unknown error"}`)}}return{loaded:O,errors:W}}function $J(J={}){return{name:"env-plugin",setup(Q){y(J)}}}function wJ(J={}){let Q=N(J.env)||N("development")||N(process.env.DOTENV_ENV)||N(process.env.APP_ENV)||"development",X=J.cwd||process.cwd(),$=[],Z=(Y)=>{if(!$.includes(Y)&&h(m(X,Y)))$.push(Y)};Z(".env"),Z(".env.local");let j=`.env.${Q}`,A=`.env.${Q}.local`;return Z(j),Z(A),y({...J,path:$,env:Q})}var xJ=$J;import{existsSync as F,readFileSync as C,writeFileSync as V}from"fs";import{resolve as g}from"path";function XJ(J={}){let Q=J.cwd||process.cwd(),X=g(Q,J.file||".env"),$=g(Q,J.keysFile||".env.keys");if(!F(X))return{success:!1,error:`File not found: ${X}`};try{let Z,j;if(F($)){let U=C($,"utf-8"),{parsed:H}=L(U),z=((J.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),D=z?`DOTENV_PUBLIC_KEY_${z}`:"DOTENV_PUBLIC_KEY",M=z?`DOTENV_PRIVATE_KEY_${z}`:"DOTENV_PRIVATE_KEY";if(Z=H[D]||"",j=H[M]||"",!Z||!j){let I=w();Z=I.publicKey,j=I.privateKey;let T=`
5
5
  ${D}="${Z}"
6
6
  ${M}="${j}"
7
7
  `;V($,U+T,"utf-8")}}else{let U=w();Z=U.publicKey,j=U.privateKey;let B=((J.file||".env").split("/").pop()||"").replace(/^\.env\./,"").replace(/^\.env$/,"").toUpperCase(),z=B?`DOTENV_PUBLIC_KEY_${B}`:"DOTENV_PUBLIC_KEY",D=B?`DOTENV_PRIVATE_KEY_${B}`:"DOTENV_PRIVATE_KEY",M=`# .env.keys - Keep this file secure and never commit to source control
package/dist/plugin.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // @bun
2
2
  import{createCipheriv as f,createDecipheriv as m,createHash as D,randomBytes as K}from"crypto";function k(J,j){let Y=K(16),Q=j.length===32?j:Buffer.from(j.toString("hex").slice(0,64),"hex"),R=f("aes-256-gcm",Q,Y),U=Buffer.concat([R.update(J,"utf8"),R.final()]),Z=R.getAuthTag();return{ciphertext:U.toString("hex"),iv:Y.toString("hex"),authTag:Z.toString("hex")}}function h(J,j,Y,Q){let R=j.length===32?j:Buffer.from(j.toString("hex").slice(0,64),"hex");try{let U=m("aes-256-gcm",R,Buffer.from(Y,"hex"));return U.setAuthTag(Buffer.from(Q,"hex")),Buffer.concat([U.update(Buffer.from(J,"hex")),U.final()]).toString("utf8")}catch(U){throw Error(`Decryption failed (data may be corrupted or key is incorrect): ${U instanceof Error?U.message:String(U)}`)}}function o(){let J=K(32);return{publicKey:D("sha256").update(J).digest().toString("hex"),privateKey:J.toString("hex")}}function s(J,j){let Y=D("sha256").update(Buffer.from(j,"hex")).digest(),{ciphertext:Q,iv:R,authTag:U}=k(J,Y);return`encrypted:${Buffer.concat([Buffer.from(R,"hex"),Buffer.from(U,"hex"),Buffer.from(Q,"hex")]).toString("base64")}`}function N(J,j){if(!J.startsWith("encrypted:"))return J;let Y=J.slice(10),Q=Buffer.from(Y,"base64");if(Q.length<32)throw Error("Invalid encrypted data: payload too short (need at least iv + authTag = 32 bytes)");let R=Q.subarray(0,16).toString("hex"),U=Q.subarray(16,32).toString("hex"),Z=Q.subarray(32).toString("hex"),$=D("sha256").update(Buffer.from(j,"hex")).digest(),W=D("sha256").update($).digest();return h(Z,W,R,U)}function i(J){let j=J.match(/^DOTENV_PRIVATE_KEY_(.+)$/);return j&&j[1]?j[1].toLowerCase():""}function P(J=""){if(!J)return process.env.DOTENV_PRIVATE_KEY;let j=`DOTENV_PRIVATE_KEY_${J.toUpperCase()}`;return process.env[j]}function F(J,j={}){let Y={},Q=[],R=[],U=J.split(`
3
3
  `);for(let Z of U){let $=Z.trim();if(!$||$.startsWith("#"))continue;if($.startsWith("DOTENV_PUBLIC_KEY=")){let q=$.match(/^DOTENV_PUBLIC_KEY=["']?([^"'\n]+)["']?/);if(q&&q[1]!==void 0)Y.DOTENV_PUBLIC_KEY=q[1];continue}let W=$.match(/^([^=]+)=(.*)$/);if(!W||W[1]===void 0||W[2]===void 0)continue;let G=W[1].trim(),X=W[2].trim();if(X.startsWith('"')&&X.endsWith('"')||X.startsWith("'")&&X.endsWith("'")){if(X=X.slice(1,-1),X.includes("\\n"))X=X.replace(/\\n/g,`
4
- `)}if(X.startsWith("encrypted:")||X.startsWith("enc:")){if(!j.privateKey){R.push(G);continue}try{let q=X.startsWith("enc:")?`encrypted:${X.slice(4)}`:X;X=N(q,j.privateKey)}catch(q){Q.push(`Failed to decrypt ${G}: ${q instanceof Error?q.message:"Unknown error"}`)}}X=c(X,{...j.processEnv||process.env,...Y}),X=u(X),Y[G]=X}return{parsed:Y,errors:Q,skippedEncrypted:R}}function c(J,j){return J.replace(/\$\{([^}]+)\}/g,(Y,Q)=>{let R=Q.match(/^([^:\-+]+)(:-|-)(.+)$/);if(R){let[,Z,$,W]=R,G=j[Z];if($===":-")return G||W;else return G!==void 0?G:W}let U=Q.match(/^([^:\-+]+)(:?\+)(.+)$/);if(U){let[,Z,$,W]=U,G=j[Z];if($===":+")return G?W:"";else return G!==void 0?W:""}return j[Q]||""})}var y=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function u(J){return J.replace(/\$\(([^)]+)\)/g,(j,Y)=>{try{let Q=Y.trim().split(/\s+/),R=Q[0];if(!R||!y.has(R))return console.warn(`[env] Blocked command substitution for disallowed command: ${R}`),"";let U=Bun.spawnSync(Q,{stdout:"pipe",stderr:"pipe"});if(U.exitCode===0)return new TextDecoder().decode(U.stdout).trim();console.warn(`[env] Command substitution failed (exit code ${U.exitCode}): ${R}`)}catch(Q){console.warn(`[env] Command substitution error: ${Q instanceof Error?Q.message:String(Q)}`)}return""})}async function l(J,j={}){let Y={},Q=[],R=[];for(let U of J)try{let Z=Bun.file(U);if(!Z.size)continue;let $=await Z.text(),{parsed:W,errors:G,skippedEncrypted:X}=F($,j);Q.push(...G),R.push(...X);for(let[q,O]of Object.entries(W)){if(!j.overload&&Y[q]!==void 0)continue;Y[q]=O}}catch(Z){if(Z?.code==="ENOENT")continue;Q.push(`Failed to read ${U}: ${Z instanceof Error?Z.message:String(Z)}`)}return{parsed:Y,errors:Q,skippedEncrypted:R}}import{existsSync as g}from"fs";import{readFileSync as V}from"fs";import{resolve as z}from"path";function b(J){return typeof J==="string"&&(J.startsWith("encrypted:")||J.startsWith("enc:"))}function M(J){if(!J||b(J))return;let j=J.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(j))return;if(j==="prod")return"production";if(j==="stage")return"staging";if(j==="dev")return"development";return j}function x(J={}){let{path:j=[".env"],overload:Y=!1,env:Q,privateKey:R,keysFile:U=".env.keys",quiet:Z=!1,cwd:$=process.cwd()}=J,W=Array.isArray(j)?j:[j],G=[],X=0,q=new Set(Object.entries(process.env).filter(([,A])=>A!==void 0&&!b(A)).map(([A])=>A)),O=R;if(!O&&U){let A=z($,U);if(g(A))try{let _=V(A,"utf-8"),{parsed:B}=F(_);if(Q){let w=`DOTENV_PRIVATE_KEY_${Q.toUpperCase()}`;O=B[w]}else O=B.DOTENV_PRIVATE_KEY}catch(_){G.push(`Failed to load keys file: ${_ instanceof Error?_.message:"Unknown error"}`)}}if(!O)O=P(Q||"");for(let A of W){let _=z($,A);if(!g(_)){if(!Z)G.push(`File not found: ${_}`);continue}try{let B=V(_,"utf-8"),{parsed:w,errors:E,skippedEncrypted:I}=F(B,{privateKey:O,processEnv:process.env});if(G.push(...E),I.length>0){for(let T of I)if(b(process.env[T]))delete process.env[T];let L=Q?`DOTENV_PRIVATE_KEY_${Q.toUpperCase()}`:"DOTENV_PRIVATE_KEY",C=I.slice(0,5).join(", "),H=I.length>5?`, \u2026 +${I.length-5} more`:"";console.warn(`[env] warning: skipped ${I.length} encrypted value(s) in ${A} (${L} not set; defaults apply): ${C}${H}`)}let S=0;for(let[L,C]of Object.entries(w)){if(L==="DOTENV_PUBLIC_KEY")continue;let H=process.env[L],T=b(H)&&C!==H;if(Y||!q.has(L)||T)process.env[L]=C,X++,S++}if(!Z&&!process.env.__ENV_LOADED__)console.log(`[env] loaded ${S}/${Object.keys(w).length} variables from ${A}`),process.env.__ENV_LOADED__="1"}catch(B){G.push(`Failed to load ${_}: ${B instanceof Error?B.message:"Unknown error"}`)}}return{loaded:X,errors:G}}function d(J={}){return{name:"env-plugin",setup(j){x(J)}}}function Rj(J={}){let j=M(J.env)||M("development")||M(process.env.DOTENV_ENV)||M(process.env.APP_ENV)||"development",Y=J.cwd||process.cwd(),Q=[],R=($)=>{if(!Q.includes($)&&g(z(Y,$)))Q.push($)};R(".env"),R(".env.local");let U=`.env.${j}`,Z=`.env.${j}.local`;return R(U),R(Z),x({...J,path:Q,env:j})}var Xj=d;export{x as loadEnv,d as envPlugin,Xj as default,Rj as autoLoadEnv};
4
+ `)}if(X.startsWith("encrypted:")||X.startsWith("enc:")){if(!j.privateKey){R.push(G);continue}try{let q=X.startsWith("enc:")?`encrypted:${X.slice(4)}`:X;X=N(q,j.privateKey)}catch(q){Q.push(`Failed to decrypt ${G}: ${q instanceof Error?q.message:"Unknown error"}`)}}X=c(X,{...j.processEnv||process.env,...Y}),X=u(X),Y[G]=X}return{parsed:Y,errors:Q,skippedEncrypted:R}}function c(J,j){return J.replace(/\$\{([^}]+)\}/g,(Y,Q)=>{let R=Q.match(/^([^:\-+]+)(:-|-)(.+)$/);if(R){let[,Z,$,W]=R,G=j[Z];if($===":-")return G||W;else return G!==void 0?G:W}let U=Q.match(/^([^:\-+]+)(:?\+)(.+)$/);if(U){let[,Z,$,W]=U,G=j[Z];if($===":+")return G?W:"";else return G!==void 0?W:""}return j[Q]||""})}var y=new Set(["date","hostname","whoami","uname","pwd","echo","printf","cat","basename","dirname"]);function u(J){return J.replace(/\$\(([^)]+)\)/g,(j,Y)=>{try{let Q=Y.trim().split(/\s+/),R=Q[0];if(!R||!y.has(R))return console.warn(`[env] Blocked command substitution for disallowed command: ${R}`),"";let U=Bun.spawnSync(Q,{stdout:"pipe",stderr:"pipe"});if(U.exitCode===0)return new TextDecoder().decode(U.stdout).trim();console.warn(`[env] Command substitution failed (exit code ${U.exitCode}): ${R}`)}catch(Q){console.warn(`[env] Command substitution error: ${Q instanceof Error?Q.message:String(Q)}`)}return""})}async function l(J,j={}){let Y={},Q=[],R=[];for(let U of J)try{let Z=Bun.file(U);if(!Z.size)continue;let $=await Z.text(),{parsed:W,errors:G,skippedEncrypted:X}=F($,j);Q.push(...G),R.push(...X);for(let[q,O]of Object.entries(W)){if(!j.overload&&Y[q]!==void 0)continue;Y[q]=O}}catch(Z){if(Z?.code==="ENOENT")continue;Q.push(`Failed to read ${U}: ${Z instanceof Error?Z.message:String(Z)}`)}return{parsed:Y,errors:Q,skippedEncrypted:R}}import{existsSync as g}from"fs";import{readFileSync as V}from"fs";import{resolve as z}from"path";function b(J){return typeof J==="string"&&(J.startsWith("encrypted:")||J.startsWith("enc:"))}function M(J){if(!J||b(J))return;let j=J.trim().toLowerCase();if(!/^[a-z0-9_-]+$/.test(j))return;if(j==="prod")return"production";if(j==="stage")return"staging";if(j==="dev")return"development";return j}function x(J={}){let{path:j=[".env"],overload:Y=!1,env:Q,privateKey:R,keysFile:U=".env.keys",quiet:Z=!1,cwd:$=process.cwd()}=J,W=Array.isArray(j)?j:[j],G=[],X=0,q=new Set(Object.entries(process.env).filter(([,A])=>A!==void 0&&!b(A)).map(([A])=>A)),O=R;if(!O&&U){let A=z($,U);if(g(A))try{let _=V(A,"utf-8"),{parsed:B}=F(_);if(Q){let w=`DOTENV_PRIVATE_KEY_${Q.toUpperCase()}`;O=B[w]}else O=B.DOTENV_PRIVATE_KEY}catch(_){G.push(`Failed to load keys file: ${_ instanceof Error?_.message:"Unknown error"}`)}}if(!O)O=P(Q||"");for(let A of W){let _=z($,A);if(!g(_)){if(!Z)G.push(`File not found: ${_}`);continue}try{let B=V(_,"utf-8"),{parsed:w,errors:E,skippedEncrypted:I}=F(B,{privateKey:O,processEnv:process.env});if(G.push(...E),I.length>0){for(let T of I)if(b(process.env[T]))delete process.env[T];let L=Q?`DOTENV_PRIVATE_KEY_${Q.toUpperCase()}`:"DOTENV_PRIVATE_KEY",C=I.slice(0,5).join(", "),H=I.length>5?`, \u2026 +${I.length-5} more`:"";console.warn(`[env] warning: skipped ${I.length} encrypted value(s) in ${A} (${L} not set; defaults apply): ${C}${H}`)}let S=0;for(let[L,C]of Object.entries(w)){if(L==="DOTENV_PUBLIC_KEY")continue;let H=process.env[L],T=b(H)&&C!==H;if(Y||!q.has(L)||T)process.env[L]=C,X++,S++}if(!Z&&!process.env.__ENV_LOADED__)console.error(`[env] loaded ${S}/${Object.keys(w).length} variables from ${A}`),process.env.__ENV_LOADED__="1"}catch(B){G.push(`Failed to load ${_}: ${B instanceof Error?B.message:"Unknown error"}`)}}return{loaded:X,errors:G}}function d(J={}){return{name:"env-plugin",setup(j){x(J)}}}function Rj(J={}){let j=M(J.env)||M("development")||M(process.env.DOTENV_ENV)||M(process.env.APP_ENV)||"development",Y=J.cwd||process.cwd(),Q=[],R=($)=>{if(!Q.includes($)&&g(z(Y,$)))Q.push($)};R(".env"),R(".env.local");let U=`.env.${j}`,Z=`.env.${j}.local`;return R(U),R(Z),x({...J,path:Q,env:j})}var Xj=d;export{x as loadEnv,d as envPlugin,Xj as default,Rj as autoLoadEnv};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/env",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.160",
5
+ "version": "0.70.161",
6
6
  "description": "Stacks env helper methods.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "devDependencies": {
53
53
  "better-dx": "^0.2.17",
54
- "@stacksjs/path": "0.70.160",
55
- "@stacksjs/validation": "0.70.160"
54
+ "@stacksjs/path": "0.70.161",
55
+ "@stacksjs/validation": "0.70.161"
56
56
  }
57
57
  }