@stacksjs/rpx 0.11.35 → 0.11.36
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/bin/cli.js +175 -177
- package/dist/{chunk-52j763a0.js → chunk-abrzcb7x.js} +71 -71
- package/dist/{chunk-q0831dgh.js → chunk-bvq3wmhm.js} +1 -1
- package/dist/{chunk-j8pg56tn.js → chunk-mvrj419f.js} +1 -1
- package/dist/{chunk-35444zrq.js → chunk-w4t1nar9.js} +1 -1
- package/dist/index.js +2 -2
- package/dist/on-demand.d.ts +8 -0
- package/package.json +1 -1
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import{Ab as Hl,Bb as I$,Db as Rt,Eb as Y,Fb as G$,Jb as ah,Kb as hl,Mb as Gf,Nb as Jh,Pb as f$,Qb as Fh,zb as L}from"./chunk-35444zrq.js";import D$ from"node:dgram";import*as b$ from"node:fs/promises";import*as P$ from"node:path";import*as Yt from"node:process";import{spawn as H$}from"node:child_process";import*as Ti from"node:fs/promises";import{homedir as q$}from"node:os";import*as Zi from"node:path";import*as U from"node:process";var S={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as wl}from"node:child_process";import Z from"node:fs/promises";import*as ul from"node:os";import{homedir as en}from"node:os";import*as Ih from"node:path";import{join as D}from"node:path";import*as xi from"node:process";import{createRequire as l1}from"node:module";import{Resolver as l0}from"node:dns/promises";import{createHash as w1,sign as u1}from"node:crypto";import{createHash as h1}from"node:crypto";import{sign as $1}from"node:crypto";import{generateKeyPairSync as rw,X509Certificate as U1}from"node:crypto";import y0 from"node:os";import w0 from"node:path";import{existsSync as pl,statSync as iy}from"fs";import{existsSync as N1,mkdirSync as de,readdirSync as De,readFileSync as R1,writeFileSync as be}from"fs";import{homedir as xt}from"os";import{dirname as ve,resolve as Ji}from"path";import Vr from"process";import{existsSync as ty,statSync as ny}from"fs";import{existsSync as _0,mkdirSync as X1,readdirSync as W1,writeFileSync as S1}from"fs";import{homedir as kt}from"os";import{dirname as ry,resolve as Yi}from"path";import _t from"process";import{join as a1,relative as J1,resolve as fy}from"path";import Jr from"process";import{existsSync as fw,mkdirSync as ym,readdirSync as wm,writeFileSync as um}from"fs";import{homedir as u0}from"os";import{dirname as Am,resolve as Ei}from"path";import In from"process";import{join as F1,relative as I1,resolve as cy}from"path";import Fr from"process";import{existsSync as cw,mkdirSync as Cm,readdirSync as em,writeFileSync as mm}from"fs";import{dirname as jm,resolve as Ir}from"path";import z0 from"process";import{Buffer as Ct}from"buffer";import{createCipheriv as K1,createDecipheriv as _1,randomBytes as h0}from"crypto";import{closeSync as $0,createReadStream as ly,createWriteStream as z1,existsSync as A0,fsyncSync as yy,openSync as wy,writeFileSync as Q1}from"fs";import{access as M1,constants as uy,mkdir as O1,readdir as cr,rename as hy,stat as Vt,unlink as lr,writeFile as T0}from"fs/promises";import{join as dt}from"path";import yi from"process";import{pipeline as G1}from"stream/promises";import{createGzip as $y}from"zlib";import Dt from"process";import tt from"process";import{Buffer as oi}from"buffer";import{createCipheriv as H1,createDecipheriv as q1,randomBytes as E0}from"crypto";import{closeSync as Y0,createReadStream as Ay,createWriteStream as g1,existsSync as yr,fsyncSync as Ty,openSync as Ey,writeFileSync as L1}from"fs";import{access as s1,constants as Yy,mkdir as x1,readdir as wr,rename as By,stat as bt,unlink as ur,writeFile as B0}from"fs/promises";import{isAbsolute as k1,join as Pt,resolve as V1}from"path";import H from"process";import{pipeline as d1}from"stream/promises";import{createGzip as Cy}from"zlib";import Zt from"process";import nt from"process";import hr from"process";import{existsSync as $r}from"fs";import{resolve as C0}from"path";import{existsSync as D1}from"fs";import{existsSync as b1,readdirSync as P1}from"fs";import{extname as e0,resolve as ey}from"path";import Z1 from"process";import{join as v1,relative as o1,resolve as my}from"path";import Kr from"process";import{Buffer as pi}from"buffer";import{createCipheriv as p1,createDecipheriv as iA,randomBytes as m0}from"crypto";import{closeSync as U0,createReadStream as Uy,createWriteStream as tA,existsSync as Ar,fsyncSync as jy,openSync as Ny,writeFileSync as nA}from"fs";import{access as rA,constants as Ry,mkdir as fA,readdir as Tr,rename as Xy,stat as vt,unlink as Er,writeFile as j0}from"fs/promises";import{isAbsolute as cA,join as ot,resolve as lA}from"path";import q from"process";import{pipeline as yA}from"stream/promises";import{createGzip as Wy}from"zlib";import pt from"process";import rt from"process";import Yr from"process";import{existsSync as Br}from"fs";import{resolve as N0}from"path";import{existsSync as wA}from"fs";import{exec as IT}from"node:child_process";import k0 from"node:fs";import KT from"node:os";import Oi from"node:path";import Lw from"node:process";import{promisify as _T}from"node:util";import fn from"node:crypto";import ft from"node:fs";import D0 from"node:path";import tE from"node:crypto";import nE from"node:fs";import rE from"node:tls";import{execSync as lE}from"node:child_process";import xr from"node:os";var y1=l1(import.meta.url),xy=30000;async function mr(i,t={},n=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(n)})}catch(r){if(r&&typeof r==="object"&&r.name==="TimeoutError"){let f=Error(`ACME HTTP request to ${i} timed out after ${n}ms`);throw f.name="AcmeRequestTimeoutError",f}throw r}}async function ky(i,t,n={}){let r=n.timeoutMs??120000,f=n.intervalMs??3000,c=i.split(".").slice(-2).join("."),l;try{let u=new l0,h=await u.resolveNs(c),$=(await Promise.all(h.map((A)=>u.resolve4(A).catch(()=>[])))).flat();if($.length>0)l=new l0,l.setServers($)}catch{}let y=Date.now()+r,w=l??new l0;for(;;){try{if((await w.resolveTxt(i)).some((u)=>u.join("")===t))return!0}catch{}if(Date.now()>=y)return!1;await new Promise((u)=>setTimeout(u,f))}}class Fn{tokens=new Map;add(i,t){this.tokens.set(i,t)}get(i){return this.tokens.get(i)}remove(i){this.tokens.delete(i)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(i){let t=i.indexOf(Fn.PATH_PREFIX);if(t===-1)return;let n=i.slice(t+Fn.PATH_PREFIX.length);return this.get(n)}}var kr=new Fn;function Ur(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function J0(i){return Buffer.from(i,"base64url")}function Vy(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function dy(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return w1("sha256").update(t).digest("base64url")}function Dy(i){let{protectedHeader:t,payload:n,privateKey:r}=i,f=Ur(JSON.stringify(t)),c=n===""?"":Ur(JSON.stringify(n)),l=`${f}.${c}`,y=u1("sha256",Buffer.from(l),{key:r,dsaEncoding:"ieee-p1363"});return{protected:f,payload:c,signature:Ur(y)}}var by="https://acme-staging-v02.api.letsencrypt.org/directory",Py="https://acme-v02.api.letsencrypt.org/directory";class Sr extends Error{problem;httpStatus;constructor(i,t,n){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=n}}class ar{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=Vy(i.accountPublicKey),this.thumbprint=dy(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??xy}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await mr(this.directoryUrl,{},this.requestTimeoutMs);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await mr(i.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:n,useJwk:r}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(r)f.jwk=this.jwk;else f.kid=this.requireKid();let c=Dy({protectedHeader:f,payload:n,privateKey:this.accountKey}),l=await mr(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(c)},this.requestTimeoutMs),y=l.headers.get("replay-nonce");if(y)this.nonce=y;let w=l.headers.get("content-type")??"",u;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))u=await l.text();else{let h=await l.text();u=h?JSON.parse(h):{}}if(l.status>=400){let h=u??{};throw new Sr(`ACME request to ${t} failed (HTTP ${l.status}): ${h.type??""} ${h.detail??""}`.trim(),h,l.status)}return{status:l.status,headers:l.headers,body:u,location:l.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),n={termsOfServiceAgreed:!0};if(i.email)n.contact=[`mailto:${i.email}`];let r=await this.signedPost({url:t.newAccount,payload:n,useJwk:!0});if(!r.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=r.location,this.accountKid}async newOrder(i){let t=await this.directory(),n={identifiers:i.map((f)=>({type:"dns",value:f}))},r=await this.signedPost({url:t.newOrder,payload:n});if(!r.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:r.body,orderUrl:r.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return h1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getAuthorization(i);if(c.status==="valid")return;if(c.status==="invalid"){let l=c.challenges.find((y)=>y.status==="invalid");throw new Sr(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getOrder(i);if(c.status==="valid"){if(!c.certificate)throw Error("ACME order is valid but has no certificate URL");return c.certificate}if(c.status==="invalid")throw Error(`ACME order ${i} became invalid`);await ol(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let n=i.challenges.find((r)=>r.type===t);if(!n)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return n}}function Zy(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],n=t[0];if(!n)return{certPem:`${i.trim()}
|
|
1
|
+
import{Ab as g,Bb as ql,Cb as K$,Eb as at,Fb as E,Gb as H$,Kb as Jh,Lb as hl,Nb as Gf,Ob as Fh,Qb as c$,Rb as Ih}from"./chunk-w4t1nar9.js";import b$ from"node:dgram";import*as P$ from"node:fs/promises";import*as Z$ from"node:path";import*as et from"node:process";import{spawn as q$}from"node:child_process";import*as Ti from"node:fs/promises";import{homedir as s$}from"node:os";import*as Zi from"node:path";import*as C from"node:process";var W={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as wl}from"node:child_process";import Z from"node:fs/promises";import*as ul from"node:os";import{homedir as mn}from"node:os";import*as Kh from"node:path";import{join as D}from"node:path";import*as xi from"node:process";import{createRequire as y1}from"node:module";import{Resolver as l0}from"node:dns/promises";import{createHash as u1,sign as h1}from"node:crypto";import{createHash as $1}from"node:crypto";import{sign as A1}from"node:crypto";import{generateKeyPairSync as fw,X509Certificate as j1}from"node:crypto";import y0 from"node:os";import w0 from"node:path";import{existsSync as iy,statSync as ty}from"fs";import{existsSync as a1,mkdirSync as Dm,readdirSync as bm,readFileSync as N1,writeFileSync as Pm}from"fs";import{homedir as xt}from"os";import{dirname as om,resolve as Ji}from"path";import Vr from"process";import{existsSync as ny,statSync as ry}from"fs";import{existsSync as _0,mkdirSync as S1,readdirSync as W1,writeFileSync as X1}from"fs";import{homedir as kt}from"os";import{dirname as fy,resolve as ei}from"path";import _t from"process";import{join as J1,relative as F1,resolve as cy}from"path";import Jr from"process";import{existsSync as cw,mkdirSync as wC,readdirSync as uC,writeFileSync as hC}from"fs";import{homedir as u0}from"os";import{dirname as TC,resolve as Ei}from"path";import In from"process";import{join as I1,relative as K1,resolve as ly}from"path";import Fr from"process";import{existsSync as lw,mkdirSync as mC,readdirSync as CC,writeFileSync as UC}from"fs";import{dirname as RC,resolve as Ir}from"path";import z0 from"process";import{Buffer as Bt}from"buffer";import{createCipheriv as _1,createDecipheriv as z1,randomBytes as h0}from"crypto";import{closeSync as $0,createReadStream as yy,createWriteStream as Q1,existsSync as A0,fsyncSync as wy,openSync as uy,writeFileSync as M1}from"fs";import{access as O1,constants as hy,mkdir as G1,readdir as cr,rename as $y,stat as Vt,unlink as lr,writeFile as T0}from"fs/promises";import{join as dt}from"path";import yi from"process";import{pipeline as H1}from"stream/promises";import{createGzip as Ay}from"zlib";import Dt from"process";import tt from"process";import{Buffer as oi}from"buffer";import{createCipheriv as q1,createDecipheriv as s1,randomBytes as E0}from"crypto";import{closeSync as e0,createReadStream as Ty,createWriteStream as g1,existsSync as yr,fsyncSync as Ey,openSync as ey,writeFileSync as L1}from"fs";import{access as x1,constants as Yy,mkdir as k1,readdir as wr,rename as By,stat as bt,unlink as ur,writeFile as Y0}from"fs/promises";import{isAbsolute as V1,join as Pt,resolve as d1}from"path";import H from"process";import{pipeline as D1}from"stream/promises";import{createGzip as my}from"zlib";import Zt from"process";import nt from"process";import hr from"process";import{existsSync as $r}from"fs";import{resolve as B0}from"path";import{existsSync as b1}from"fs";import{existsSync as P1,readdirSync as Z1}from"fs";import{extname as m0,resolve as Cy}from"path";import v1 from"process";import{join as o1,relative as p1,resolve as Uy}from"path";import Kr from"process";import{Buffer as pi}from"buffer";import{createCipheriv as iA,createDecipheriv as tA,randomBytes as C0}from"crypto";import{closeSync as U0,createReadStream as jy,createWriteStream as nA,existsSync as Ar,fsyncSync as Ry,openSync as ay,writeFileSync as rA}from"fs";import{access as fA,constants as Ny,mkdir as cA,readdir as Tr,rename as Sy,stat as vt,unlink as Er,writeFile as j0}from"fs/promises";import{isAbsolute as lA,join as ot,resolve as yA}from"path";import q from"process";import{pipeline as wA}from"stream/promises";import{createGzip as Wy}from"zlib";import pt from"process";import rt from"process";import er from"process";import{existsSync as Yr}from"fs";import{resolve as R0}from"path";import{existsSync as uA}from"fs";import{exec as KT}from"node:child_process";import k0 from"node:fs";import _T from"node:os";import Oi from"node:path";import Lw from"node:process";import{promisify as zT}from"node:util";import fn from"node:crypto";import ft from"node:fs";import D0 from"node:path";import nE from"node:crypto";import rE from"node:fs";import fE from"node:tls";import{execSync as yE}from"node:child_process";import xr from"node:os";var w1=y1(import.meta.url),ky=30000;async function Cr(i,t={},n=30000){try{return await fetch(i,{...t,signal:AbortSignal.timeout(n)})}catch(r){if(r&&typeof r==="object"&&r.name==="TimeoutError"){let f=Error(`ACME HTTP request to ${i} timed out after ${n}ms`);throw f.name="AcmeRequestTimeoutError",f}throw r}}async function Vy(i,t,n={}){let r=n.timeoutMs??120000,f=n.intervalMs??3000,c=i.split(".").slice(-2).join("."),l;try{let u=new l0,h=await u.resolveNs(c),$=(await Promise.all(h.map((A)=>u.resolve4(A).catch(()=>[])))).flat();if($.length>0)l=new l0,l.setServers($)}catch{}let y=Date.now()+r,w=l??new l0;for(;;){try{if((await w.resolveTxt(i)).some((u)=>u.join("")===t))return!0}catch{}if(Date.now()>=y)return!1;await new Promise((u)=>setTimeout(u,f))}}class Fn{tokens=new Map;add(i,t){this.tokens.set(i,t)}get(i){return this.tokens.get(i)}remove(i){this.tokens.delete(i)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(i){let t=i.indexOf(Fn.PATH_PREFIX);if(t===-1)return;let n=i.slice(t+Fn.PATH_PREFIX.length);return this.get(n)}}var kr=new Fn;function Ur(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function J0(i){return Buffer.from(i,"base64url")}function dy(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function Dy(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return u1("sha256").update(t).digest("base64url")}function by(i){let{protectedHeader:t,payload:n,privateKey:r}=i,f=Ur(JSON.stringify(t)),c=n===""?"":Ur(JSON.stringify(n)),l=`${f}.${c}`,y=h1("sha256",Buffer.from(l),{key:r,dsaEncoding:"ieee-p1363"});return{protected:f,payload:c,signature:Ur(y)}}var Py="https://acme-staging-v02.api.letsencrypt.org/directory",Zy="https://acme-v02.api.letsencrypt.org/directory";class Wr extends Error{problem;httpStatus;constructor(i,t,n){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=n}}class Xr{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=dy(i.accountPublicKey),this.thumbprint=Dy(this.jwk),this.requestTimeoutMs=i.requestTimeoutMs??ky}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await Cr(this.directoryUrl,{},this.requestTimeoutMs);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await Cr(i.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:n,useJwk:r}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(r)f.jwk=this.jwk;else f.kid=this.requireKid();let c=by({protectedHeader:f,payload:n,privateKey:this.accountKey}),l=await Cr(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(c)},this.requestTimeoutMs),y=l.headers.get("replay-nonce");if(y)this.nonce=y;let w=l.headers.get("content-type")??"",u;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))u=await l.text();else{let h=await l.text();u=h?JSON.parse(h):{}}if(l.status>=400){let h=u??{};throw new Wr(`ACME request to ${t} failed (HTTP ${l.status}): ${h.type??""} ${h.detail??""}`.trim(),h,l.status)}return{status:l.status,headers:l.headers,body:u,location:l.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),n={termsOfServiceAgreed:!0};if(i.email)n.contact=[`mailto:${i.email}`];let r=await this.signedPost({url:t.newAccount,payload:n,useJwk:!0});if(!r.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=r.location,this.accountKid}async newOrder(i){let t=await this.directory(),n={identifiers:i.map((f)=>({type:"dns",value:f}))},r=await this.signedPost({url:t.newOrder,payload:n});if(!r.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:r.body,orderUrl:r.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return $1("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getAuthorization(i);if(c.status==="valid")return;if(c.status==="invalid"){let l=c.challenges.find((y)=>y.status==="invalid");throw new Wr(`Authorization for ${c.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await pl(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let c=await this.getOrder(i);if(c.status==="valid"){if(!c.certificate)throw Error("ACME order is valid but has no certificate URL");return c.certificate}if(c.status==="invalid")throw Error(`ACME order ${i} became invalid`);await pl(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let n=i.challenges.find((r)=>r.type===t);if(!n)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return n}}function vy(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],n=t[0];if(!n)return{certPem:`${i.trim()}
|
|
2
2
|
`,chainPem:""};let r=`${n.trim()}
|
|
3
3
|
`,f=t.slice(1).map((c)=>c.trim()).join(`
|
|
4
4
|
`);return{certPem:r,chainPem:f?`${f}
|
|
5
|
-
`:""}}function vy(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function ol(i){return new Promise((t)=>setTimeout(t,i))}function A1(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Ut(i,t){return Buffer.concat([Buffer.from([i]),A1(t.length),t])}function oy(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=[],r=i;while(r>0)n.unshift(r&255),r>>=8;if(n[0]&128)n.unshift(0);t=Buffer.from(n)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Ut(2,t)}function Kt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let n=[40*t[0]+t[1]];for(let r=2;r<t.length;r++){let f=t[r],c=[f&127];f=Math.floor(f/128);while(f>0)c.unshift(f&127|128),f=Math.floor(f/128);n.push(...c)}return Ut(6,Buffer.from(n))}function ai(...i){return Ut(48,Buffer.concat(i))}function F0(...i){return Ut(49,Buffer.concat(i))}function I0(i){return Ut(3,Buffer.concat([Buffer.from([0]),i]))}function py(i){return Ut(4,i)}function iw(i){return Ut(12,Buffer.from(i,"utf8"))}function K0(i,t,n){let r=128|(n?32:0)|i;return Ut(r,t)}var T1="1.2.840.10045.2.1",E1="1.2.840.10045.3.1.7",Y1="1.2.840.10045.4.3.2",B1="2.5.4.3",C1="1.2.840.113549.1.9.14",e1="2.5.29.17";function m1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let n=J0(t.x),r=J0(t.y);if(n.length!==32||r.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${n.length} y=${r.length}`);return Buffer.concat([Buffer.from([4]),n,r])}function tw(i){let{domains:t,publicKey:n,privateKey:r}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=ai(F0(ai(Kt(B1),iw(t[0])))),c=ai(ai(Kt(T1),Kt(E1)),I0(m1(n))),l=t.map((E)=>K0(2,Buffer.from(E,"ascii"),!1)),y=ai(...l),w=ai(Kt(e1),py(y)),u=ai(w),h=ai(Kt(C1),F0(u)),$=K0(0,h,!0),A=ai(oy(0),f,c,$),T=$1("sha256",A,r),C=ai(Kt(Y1));return ai(A,C,I0(T))}function nw(i){return tw(i).toString("base64url")}function j1(i){if(i){let{createPrivateKey:f,createPublicKey:c}=y1("node:crypto"),l=f(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:n}=rw("ec",{namedCurve:"P-256"}),r=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:n,pem:r}}async function b0(i){let{domains:t,method:n}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(n==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&n!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let r=i.directoryUrl??(i.staging===!1?Py:by),f=j1(i.accountKeyPem),c=new ar({directoryUrl:r,accountKey:f.privateKey,accountPublicKey:f.publicKey,requestTimeoutMs:i.requestTimeoutMs});await c.newAccount({email:i.email});let{order:l,orderUrl:y}=await c.newOrder(t),w=i.http01Store??kr,u=[],h=[];try{for(let F of l.authorizations){let a=await c.getAuthorization(F);if(a.status==="valid")continue;let J=ar.selectChallenge(a,n);if(n==="dns-01"){let v=vy(a.identifier.value),Mi=c.dns01TxtValue(J.token);await i.dnsProvider.setTxt(v,Mi),u.push({name:v,value:Mi}),await ky(v,Mi,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(J.token,c.keyAuthorization(J.token)),h.push(J.token);await c.notifyChallengeReady(J.url),await c.pollAuthorization(F,{timeoutMs:i.timeoutMs})}let{privateKey:$,publicKey:A}=rw("ec",{namedCurve:"P-256"}),T=nw({domains:t,publicKey:A,privateKey:$});await c.finalizeOrder(l.finalize,T);let C=await c.pollOrder(y,{timeoutMs:i.timeoutMs}),E=await c.downloadCertificate(C),{certPem:B,chainPem:e}=Zy(E),j=e?`${B}${e}`:B,X=$.export({format:"pem",type:"pkcs8"}).toString(),W=new Date(new U1(B).validTo);return{certPem:B,keyPem:X,chainPem:e,fullChainPem:j,accountKeyPem:f.pem,notAfter:W}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class lw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!pl(i))return!0;return iy(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=pl(n)?iy(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class yw{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var _r=new lw,P0=new yw,uA=Object.defineProperty,hA=(i)=>i;function $A(i,t){this[i]=hA.bind(null,t)}var AA=(i,t)=>{for(var n in t)uA(i,n,{get:t[n],enumerable:!0,configurable:!0,set:$A.bind(t,n)})},TA=(i,t)=>()=>(i&&(t=i(i=0)),t),ww={};AA(ww,{withErrorRecovery:()=>$w,tryLoadConfig:()=>OA,loadConfigWithResult:()=>QA,loadConfig:()=>Bw,isRetryableError:()=>JA,isConfigNotFoundError:()=>aA,isBunfigError:()=>Aw,globalPerformanceMonitor:()=>Qn,globalCache:()=>nn,getEnvOrDefault:()=>FA,generateConfigTypes:()=>GA,defaultGeneratedDir:()=>Xw,defaultConfigDir:()=>Rw,deepMergeWithArrayStrategy:()=>ic,deepMerge:()=>Tw,createLibraryConfig:()=>HA,config:()=>MA,bunfigPlugin:()=>qA,applyEnvVarsToConfig:()=>an,TypeGenerationError:()=>g0,SchemaValidationError:()=>_n,PluginError:()=>s0,PerformanceMonitor:()=>v0,FileSystemError:()=>q0,ErrorFactory:()=>mt,EnvVarError:()=>Hr,EnvProcessor:()=>dr,ConfigValidator:()=>tc,ConfigValidationError:()=>G0,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>H0,ConfigLoader:()=>nc,ConfigLoadError:()=>Kn,ConfigFileLoader:()=>Dr,ConfigCache:()=>Z0,CacheUtils:()=>ew,BunfigError:()=>Ri,BrowserConfigError:()=>L0,ArrayMergeStrategies:()=>jw});class Z0{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!ty(i))return!0;return ny(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=ty(n)?ny(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class v0{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function EA(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function YA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function BA(i){return i.getStats().size*2}function o0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let r=[...t];for(let f of i)if(V(f)&&"name"in f){if(!r.find((c)=>V(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(V(f)&&"path"in f){if(!r.find((c)=>V(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>zr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!V(t)||!V(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(V(f)&&V(n[r]))n[r]=o0(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&V(f[0])&&V(n[r][0])){let c=[...f];for(let l of n[r])if(V(l)&&"name"in l){if(!c.find((y)=>V(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(V(l)&&"path"in l){if(!c.find((y)=>V(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>zr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function zr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!zr(i[n],t[n]))return!1;return!0}if(V(i)&&V(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zr(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function CA(i,t){if(!cw(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return o0(t,r)}catch{return null}}catch{return null}}async function eA({name:i="",cwd:t,defaultConfig:n}){let r=t||z0.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=Ir(r,`${l}${y}`),u=await CA(w,n);if(u!==null)return u}try{let l=Ir(r,"package.json");if(cw(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return o0(n,y)}catch{}}}catch{}return n}function mA(i,t={}){let n=Fr.cwd();while(n.includes("storage"))n=cy(n,"..");let r=cy(n,i||"");if(t?.relative)return I1(Fr.cwd(),r);return r}async function UA(){try{let i=await eA({name:"clarity",defaultConfig:Nr,cwd:Fr.cwd(),endpoint:"",headers:{}});return{...Nr,...i}}catch{return Nr}}function b(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jA(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tt<"u"){let i=tt.type;if(i==="renderer"||i==="worker")return!1;return!!(tt.versions&&(tt.versions.node||tt.versions.bun))}return!1}class uw{async format(i){let t=await jA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...M0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??yi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Rr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Rr};return{...Rr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:M0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await M1(this.config.logDirectory,uy.F_OK|uy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await O1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Ct.from(i);try{if(!A0(this.currentLogFile))await T0(this.currentLogFile,"",{mode:420});if(r=wy(this.currentLogFile,"a",420),Q1(r,y,{flag:"a"}),yy(r),r!==void 0)$0(r),r=void 0;if((await Vt(this.currentLogFile)).size===0){if(await T0(this.currentLogFile,y,{flag:"w",mode:420}),(await Vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{$0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return dt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return dt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return dt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return h0(16).toString("hex")}generateKey(){return h0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=h0(16),r=K1("aes-256-gcm",t,n),f=Ct.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:Ct.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=$y(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(Ct.from(Ct.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(b())return;let i=await Vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await cr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Vt(n).catch(()=>null))try{if(await hy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await lr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await T0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Vt(n).catch(()=>null))await hy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await cr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await lr(dt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=ly(i),r=z1(t),f=$y();await G1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),A0(this.currentLogFile))try{let i=wy(this.currentLogFile,"r+");yy(i),$0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await cr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await lr(dt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=yi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${x.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!b()){let u=mw[i],h=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
|
|
5
|
+
`:""}}function oy(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function pl(i){return new Promise((t)=>setTimeout(t,i))}function T1(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Ut(i,t){return Buffer.concat([Buffer.from([i]),T1(t.length),t])}function py(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=[],r=i;while(r>0)n.unshift(r&255),r>>=8;if(n[0]&128)n.unshift(0);t=Buffer.from(n)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Ut(2,t)}function Kt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let n=[40*t[0]+t[1]];for(let r=2;r<t.length;r++){let f=t[r],c=[f&127];f=Math.floor(f/128);while(f>0)c.unshift(f&127|128),f=Math.floor(f/128);n.push(...c)}return Ut(6,Buffer.from(n))}function Xi(...i){return Ut(48,Buffer.concat(i))}function F0(...i){return Ut(49,Buffer.concat(i))}function I0(i){return Ut(3,Buffer.concat([Buffer.from([0]),i]))}function iw(i){return Ut(4,i)}function tw(i){return Ut(12,Buffer.from(i,"utf8"))}function K0(i,t,n){let r=128|(n?32:0)|i;return Ut(r,t)}var E1="1.2.840.10045.2.1",e1="1.2.840.10045.3.1.7",Y1="1.2.840.10045.4.3.2",B1="2.5.4.3",m1="1.2.840.113549.1.9.14",C1="2.5.29.17";function U1(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let n=J0(t.x),r=J0(t.y);if(n.length!==32||r.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${n.length} y=${r.length}`);return Buffer.concat([Buffer.from([4]),n,r])}function nw(i){let{domains:t,publicKey:n,privateKey:r}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=Xi(F0(Xi(Kt(B1),tw(t[0])))),c=Xi(Xi(Kt(E1),Kt(e1)),I0(U1(n))),l=t.map((e)=>K0(2,Buffer.from(e,"ascii"),!1)),y=Xi(...l),w=Xi(Kt(C1),iw(y)),u=Xi(w),h=Xi(Kt(m1),F0(u)),$=K0(0,h,!0),A=Xi(py(0),f,c,$),T=A1("sha256",A,r),B=Xi(Kt(Y1));return Xi(A,B,I0(T))}function rw(i){return nw(i).toString("base64url")}function R1(i){if(i){let{createPrivateKey:f,createPublicKey:c}=w1("node:crypto"),l=f(i),y=c(l.export({format:"pem",type:"pkcs8"}));return{privateKey:l,publicKey:y,pem:i}}let{privateKey:t,publicKey:n}=fw("ec",{namedCurve:"P-256"}),r=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:n,pem:r}}async function b0(i){let{domains:t,method:n}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(n==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some(($)=>$.startsWith("*."))&&n!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let r=i.directoryUrl??(i.staging===!1?Zy:Py),f=R1(i.accountKeyPem),c=new Xr({directoryUrl:r,accountKey:f.privateKey,accountPublicKey:f.publicKey,requestTimeoutMs:i.requestTimeoutMs});await c.newAccount({email:i.email});let{order:l,orderUrl:y}=await c.newOrder(t),w=i.http01Store??kr,u=[],h=[];try{for(let F of l.authorizations){let X=await c.getAuthorization(F);if(X.status==="valid")continue;let J=Xr.selectChallenge(X,n);if(n==="dns-01"){let v=oy(X.identifier.value),Mi=c.dns01TxtValue(J.token);await i.dnsProvider.setTxt(v,Mi),u.push({name:v,value:Mi}),await Vy(v,Mi,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(J.token,c.keyAuthorization(J.token)),h.push(J.token);await c.notifyChallengeReady(J.url),await c.pollAuthorization(F,{timeoutMs:i.timeoutMs})}let{privateKey:$,publicKey:A}=fw("ec",{namedCurve:"P-256"}),T=rw({domains:t,publicKey:A,privateKey:$});await c.finalizeOrder(l.finalize,T);let B=await c.pollOrder(y,{timeoutMs:i.timeoutMs}),e=await c.downloadCertificate(B),{certPem:Y,chainPem:m}=vy(e),j=m?`${Y}${m}`:Y,N=$.export({format:"pem",type:"pkcs8"}).toString(),S=new Date(new j1(Y).validTo);return{certPem:Y,keyPem:N,chainPem:m,fullChainPem:j,accountKeyPem:f.pem,notAfter:S}}finally{for(let{name:$,value:A}of u)await i.dnsProvider?.removeTxt($,A).catch(()=>{});for(let $ of h)w.remove($)}}class yw{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!iy(i))return!0;return ty(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=iy(n)?ty(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class ww{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var _r=new yw,P0=new ww,hA=Object.defineProperty,$A=(i)=>i;function AA(i,t){this[i]=$A.bind(null,t)}var TA=(i,t)=>{for(var n in t)hA(i,n,{get:t[n],enumerable:!0,configurable:!0,set:AA.bind(t,n)})},EA=(i,t)=>()=>(i&&(t=i(i=0)),t),uw={};TA(uw,{withErrorRecovery:()=>Aw,tryLoadConfig:()=>GA,loadConfigWithResult:()=>MA,loadConfig:()=>Bw,isRetryableError:()=>FA,isConfigNotFoundError:()=>JA,isBunfigError:()=>Tw,globalPerformanceMonitor:()=>Qn,globalCache:()=>nn,getEnvOrDefault:()=>IA,generateConfigTypes:()=>HA,defaultGeneratedDir:()=>Sw,defaultConfigDir:()=>Nw,deepMergeWithArrayStrategy:()=>ic,deepMerge:()=>Ew,createLibraryConfig:()=>qA,config:()=>OA,bunfigPlugin:()=>sA,applyEnvVarsToConfig:()=>Xn,TypeGenerationError:()=>s0,SchemaValidationError:()=>_n,PluginError:()=>L0,PerformanceMonitor:()=>v0,FileSystemError:()=>q0,ErrorFactory:()=>Ct,EnvVarError:()=>Hr,EnvProcessor:()=>dr,ConfigValidator:()=>tc,ConfigValidationError:()=>G0,ConfigNotFoundError:()=>Gr,ConfigMergeError:()=>H0,ConfigLoader:()=>nc,ConfigLoadError:()=>Kn,ConfigFileLoader:()=>Dr,ConfigCache:()=>Z0,CacheUtils:()=>Cw,BunfigError:()=>ai,BrowserConfigError:()=>g0,ArrayMergeStrategies:()=>Rw});class Z0{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!ny(i))return!0;return ry(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=ny(n)?ry(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class v0{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function eA(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function YA(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function BA(i){return i.getStats().size*2}function o0(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let r=[...t];for(let f of i)if(V(f)&&"name"in f){if(!r.find((c)=>V(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(V(f)&&"path"in f){if(!r.find((c)=>V(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>zr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!V(t)||!V(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(V(f)&&V(n[r]))n[r]=o0(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&V(f[0])&&V(n[r][0])){let c=[...f];for(let l of n[r])if(V(l)&&"name"in l){if(!c.find((y)=>V(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(V(l)&&"path"in l){if(!c.find((y)=>V(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>zr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function zr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!zr(i[n],t[n]))return!1;return!0}if(V(i)&&V(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zr(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function mA(i,t){if(!lw(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return o0(t,r)}catch{return null}}catch{return null}}async function CA({name:i="",cwd:t,defaultConfig:n}){let r=t||z0.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=Ir(r,`${l}${y}`),u=await mA(w,n);if(u!==null)return u}try{let l=Ir(r,"package.json");if(lw(l)){let y=(await import(l))[i];if(y&&typeof y==="object"&&!Array.isArray(y))try{return o0(n,y)}catch{}}}catch{}return n}function UA(i,t={}){let n=Fr.cwd();while(n.includes("storage"))n=ly(n,"..");let r=ly(n,i||"");if(t?.relative)return K1(Fr.cwd(),r);return r}async function jA(){try{let i=await CA({name:"clarity",defaultConfig:Rr,cwd:Fr.cwd(),endpoint:"",headers:{}});return{...Rr,...i}}catch{return Rr}}function b(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function RA(){if(tt.env.NODE_ENV==="test"||tt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof tt<"u"){let i=tt.type;if(i==="renderer"||i==="worker")return!1;return!!(tt.versions&&(tt.versions.node||tt.versions.bun))}return!1}class hw{async format(i){let t=await RA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Qr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...M0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new hw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??yi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...ar,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...ar};return{...ar,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:M0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await O1(this.config.logDirectory,hy.F_OK|hy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await G1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Bt.from(i);try{if(!A0(this.currentLogFile))await T0(this.currentLogFile,"",{mode:420});if(r=uy(this.currentLogFile,"a",420),M1(r,y,{flag:"a"}),wy(r),r!==void 0)$0(r),r=void 0;if((await Vt(this.currentLogFile)).size===0){if(await T0(this.currentLogFile,y,{flag:"w",mode:420}),(await Vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{$0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return dt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return dt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return dt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return h0(16).toString("hex")}generateKey(){return h0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=h0(16),r=_1("aes-256-gcm",t,n),f=Bt.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:Bt.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Ay(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(Bt.from(Bt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(b())return;let i=await Vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await cr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Vt(n).catch(()=>null))try{if(await $y(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await lr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await T0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Vt(n).catch(()=>null))await $y(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await cr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await lr(dt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=yy(i),r=Q1(t),f=Ay();await H1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),A0(this.currentLogFile))try{let i=uy(this.currentLogFile,"r+");wy(i),$0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await cr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await lr(dt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=yi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${x.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!b()){let u=Uw[i],h=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:x.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
|
|
6
6
|
`);for(let T of A)if(T.trim()&&!T.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:x.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let w=`${c} ${this.environment}.${i.toUpperCase()}: ${l}
|
|
7
7
|
`;if(y)w+=`${y}
|
|
8
8
|
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!b()){let n=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:x.blue("◐"),tag:n,message:`${x.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
9
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:x.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!b())console.error(w.trim());await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Qr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!A0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
9
|
+
`,w=w.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let u=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:x.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!b())console.error(w.trim());await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Qr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!A0(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return yy(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Bt.isBuffer(i)?i:Bt.from(i,"base64"),f=r.slice(0,16),c=r.slice(-16),l=r.slice(16,-16),y=z1("aes-256-gcm",n,f);return y.setAuthTag(c),Bt.concat([y.update(l),y.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return b()}isServerMode(){return!b()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!b()){let c=i.split(`
|
|
10
10
|
`),l=Math.max(...c.map((h)=>h.length))+2,y=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,u=c.map((h)=>{let $=" ".repeat(l-h.length-2);return`│ ${h}${$} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:x.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(y)})),u.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:x.cyan(w),showTimestamp:!1}))}else if(!b())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let f=`${r} ${this.environment}.INFO: [BOX] ${i}
|
|
11
11
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(b())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${x.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();yi.stdin.removeListener("data",n);try{if(typeof yi.stdin.setRawMode==="function")yi.stdin.setRawMode(!1)}catch{}yi.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof yi.stdin.setRawMode==="function")yi.stdin.setRawMode(!0)}catch{}yi.stdin.resume(),yi.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let f=/%([sdijfo%])/g,c=0;if(n=i.replace(f,(l,y)=>{if(y==="%")return"%";if(c>=t.length)return l;let w=t[c++];switch(y){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return l}}),c<t.length)n+=` ${t.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!b()){let f=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",c=x.blue("◐");console.error(`${c} ${f} ${x.cyan(n)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(i,t=""){if(!this.enabled||!this.fancy||b()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,r)),f!==void 0)this.activeProgressBar.message=f;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;yi.stdout.write(`${"\r".padEnd(yi.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||b()||!yi.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=x.green("━".repeat(r)),l=x.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||n===100?x.green("✓"):x.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=yi.stdout.columns||80,
|
|
13
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||b()||!yi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await cr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=dt(this.config.logDirectory,r);if(i.before)try{if((await Vt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await lr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function jr(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&g(t[0])&&"id"in t[0]&&t[0].id===3&&g(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(g(t)&&g(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(g(i)&&"arr"in i&&Array.isArray(i.arr)&&g(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&g(t[0])&&g(i[0])){let r=[...t];for(let f of i)if(g(f)&&"name"in f){if(!r.find((c)=>g(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(g(f)&&"path"in f){if(!r.find((c)=>g(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>Mr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!g(t)||!g(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(g(f)&&g(n[r]))n[r]=jr(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&g(f[0])&&g(n[r][0])){let c=[...f];for(let l of n[r])if(g(l)&&"name"in l){if(!c.find((y)=>g(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(g(l)&&"path"in l){if(!c.find((y)=>g(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>Mr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function p0(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:jr(i,t);if(Array.isArray(i))return n==="replace"?t:jr(i,t);if(!g(t)||!g(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=r[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(n==="replace")r[f]=c;else r[f]=jr(l,c);else if(g(c)&&g(l))r[f]=p0(l,c,n);else r[f]=c}return r}function Mr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Mr(i[n],t[n]))return!1;return!0}if(g(i)&&g(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Mr(i[f],t[f]))return!1}return!0}return!1}function g(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Cr(i,t,n="replace"){if(!fw(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return p0(t,f,n)}catch{return null}}catch{return null}}function NA(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...t};function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),T=`${r}_${$.map(A).join("_")}`,C=`${r}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(n)ui.info(`Checking environment variable ${T} for config ${i}.${$.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[u]=c(h,$);else{let E=In.env[T]||In.env[C];if(E!==void 0){if(n)ui.info(`Using environment variable ${E?T:C} for config ${i}.${$.join(".")}`);if(typeof h==="number")w[u]=Number(E);else if(typeof h==="boolean")w[u]=E.toLowerCase()==="true";else if(Array.isArray(h))try{let B=JSON.parse(E);if(Array.isArray(B))w[u]=B;else w[u]=E.split(",").map((e)=>e.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function RA({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?NA(i,f,c):f,u=n||In.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)ui.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${u}`);let $=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,Ei(u,"config"),Ei(u,".config"),r?Ei(u,r):void 0].filter(Boolean)));for(let B of E){if(c)ui.info(`Searching for configuration in: ${B}`);let e=[Ei(u,"config"),Ei(u,".config")].concat(r?[Ei(u,r)]:[]).includes(B)?[...$,...A,...T,...C]:[...A,...$,...C,...T];for(let j of e)for(let X of h){let W=Ei(B,`${j}${X}`),F=await Cr(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from: ${W}`);return F}}}if(i){let B=Ei(u0(),".config",i),e=["config",`${i}.config`];if(t)e.push(`${t}.config`);if(c)ui.info(`Checking user config directory: ${B}`);for(let j of e)for(let X of h){let W=Ei(B,`${j}${X}`),F=await Cr(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory: ${W}`);return F}}}if(i){let B=Ei(u0(),".config"),e=[`.${i}.config`];if(t)e.push(`.${t}.config`);if(c)ui.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of e)for(let X of h){let W=Ei(B,`${j}${X}`),F=await Cr(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory dotfile: ${W}`);return F}}}if(i){let B=u0(),e=[`.${i}.config`,`.${i}`];if(t)e.push(`.${t}.config`),e.push(`.${t}`);if(c)ui.info(`Checking user home directory for dotfile configs: ${B}`);for(let j of e)for(let X of h){let W=Ei(B,`${j}${X}`),F=await Cr(W,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user home directory: ${W}`);return F}}}try{let B=Ei(u,"package.json");if(fw(B)){let e=await import(B),j=e[i];if(!j&&t){if(j=e[t],j&&c)ui.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)ui.success(`Configuration loaded from package.json: ${j===e[i]?i:t}`);return p0(w,j,y)}catch(X){if(c)ui.warn("Failed to merge package.json config:",X)}}}catch(B){if(c)ui.warn("Failed to load package.json:",B)}if(c)ui.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function XA(i,t={}){let n=Jr.cwd();while(n.includes("storage"))n=fy(n,"..");let r=fy(n,i||"");if(t?.relative)return J1(Jr.cwd(),r);return r}async function WA(){try{let i=await RA({name:"clarity",alias:"logging",defaultConfig:Xr,cwd:Jr.cwd()});return{...Xr,...i||{}}}catch{return Xr}}function p(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function SA(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof nt<"u"){let i=nt.type;if(i==="renderer"||i==="worker")return!1;return!!(nt.versions&&(nt.versions.node||nt.versions.bun))}return!1}class hw{async format(i){let t=await SA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Zt.pid,hostname:t(),environment:Zt.env.NODE_ENV||"development",platform:Zt.platform,version:Zt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Zt.env.NODE_ENV||Zt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Or{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...O0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new hw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Wr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Wr};return{...Wr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:O0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await s1(this.config.logDirectory,Yy.F_OK|Yy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await x1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:oi.from(i);try{if(!yr(this.currentLogFile))await B0(this.currentLogFile,"",{mode:420});if(r=Ey(this.currentLogFile,"a",420),L1(r,y,{flag:"a"}),Ty(r),r!==void 0)Y0(r),r=void 0;if((await bt(this.currentLogFile)).size===0){if(await B0(this.currentLogFile,y,{flag:"w",mode:420}),(await bt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{Y0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Pt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Pt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Pt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return E0(16).toString("hex")}generateKey(){return E0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=E0(16),r=H1("aes-256-gcm",t,n),f=oi.isBuffer(i)?i:oi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=oi.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Cy(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(oi.from(oi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let i=await bt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await wr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await bt(n).catch(()=>null))try{if(await By(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await ur(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await B0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await bt(n).catch(()=>null))await By(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await wr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await ur(Pt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=Ay(i),r=g1(t),f=Cy();await d1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),yr(this.currentLogFile))try{let i=Ey(this.currentLogFile,"r+");Ty(i),Y0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await wr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await ur(Pt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?Q.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let i=typeof H.env.NO_COLOR<"u",t=H.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=H.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${Q.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=Q.underline(Q.blue(r)),l=this.toAbsoluteFilePath(f);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>Q.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Q.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Q.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Q.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>Q.strikethrough(r)),t}supportsHyperlinks(){if(p())return!1;let i=H.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=H.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(k1(t)||t.startsWith("./")||t.startsWith("../"))t=V1(t);else return null;return yr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":Uw[i],A=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:Q.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:Q.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let C=y.split(`
|
|
14
|
-
`);for(let
|
|
12
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(i,t=""){if(!this.enabled||!this.fancy||b()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,r)),f!==void 0)this.activeProgressBar.message=f;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;yi.stdout.write(`${"\r".padEnd(yi.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||b()||!yi.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=x.green("━".repeat(r)),l=x.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||n===100?x.green("✓"):x.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=yi.stdout.columns||80,B=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${B}`,yi.stdout.write(i.lastRenderedLine),t)yi.stdout.write(`
|
|
13
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||b()||!yi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await cr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=dt(this.config.logDirectory,r);if(i.before)try{if((await Vt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await lr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function jr(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&s(t[0])&&"id"in t[0]&&t[0].id===3&&s(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(s(t)&&s(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(s(i)&&"arr"in i&&Array.isArray(i.arr)&&s(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&s(t[0])&&s(i[0])){let r=[...t];for(let f of i)if(s(f)&&"name"in f){if(!r.find((c)=>s(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(s(f)&&"path"in f){if(!r.find((c)=>s(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((c)=>Mr(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!s(t)||!s(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(s(f)&&s(n[r]))n[r]=jr(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&s(f[0])&&s(n[r][0])){let c=[...f];for(let l of n[r])if(s(l)&&"name"in l){if(!c.find((y)=>s(y)&&("name"in y)&&y.name===l.name))c.push(l)}else if(s(l)&&"path"in l){if(!c.find((y)=>s(y)&&("path"in y)&&y.path===l.path))c.push(l)}else if(!c.some((y)=>Mr(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function p0(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:jr(i,t);if(Array.isArray(i))return n==="replace"?t:jr(i,t);if(!s(t)||!s(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=r[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(n==="replace")r[f]=c;else r[f]=jr(l,c);else if(s(c)&&s(l))r[f]=p0(l,c,n);else r[f]=c}return r}function Mr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Mr(i[n],t[n]))return!1;return!0}if(s(i)&&s(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Mr(i[f],t[f]))return!1}return!0}return!1}function s(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Br(i,t,n="replace"){if(!cw(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return p0(t,f,n)}catch{return null}}catch{return null}}function aA(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...t};function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=(e)=>e.replace(/([A-Z])/g,"_$1").toUpperCase(),T=`${r}_${$.map(A).join("_")}`,B=`${r}_${$.map((e)=>e.toUpperCase()).join("_")}`;if(n)ui.info(`Checking environment variable ${T} for config ${i}.${$.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[u]=c(h,$);else{let e=In.env[T]||In.env[B];if(e!==void 0){if(n)ui.info(`Using environment variable ${e?T:B} for config ${i}.${$.join(".")}`);if(typeof h==="number")w[u]=Number(e);else if(typeof h==="boolean")w[u]=e.toLowerCase()==="true";else if(Array.isArray(h))try{let Y=JSON.parse(e);if(Array.isArray(Y))w[u]=Y;else w[u]=e.split(",").map((m)=>m.trim())}catch{w[u]=e.split(",").map((Y)=>Y.trim())}else w[u]=e}}}return w}return c(f)}async function NA({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?aA(i,f,c):f,u=n||In.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)ui.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${u}`);let $=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],B=t?[`${t}.config`,`.${t}.config`]:[],e=Array.from(new Set([u,Ei(u,"config"),Ei(u,".config"),r?Ei(u,r):void 0].filter(Boolean)));for(let Y of e){if(c)ui.info(`Searching for configuration in: ${Y}`);let m=[Ei(u,"config"),Ei(u,".config")].concat(r?[Ei(u,r)]:[]).includes(Y)?[...$,...A,...T,...B]:[...A,...$,...B,...T];for(let j of m)for(let N of h){let S=Ei(Y,`${j}${N}`),F=await Br(S,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from: ${S}`);return F}}}if(i){let Y=Ei(u0(),".config",i),m=["config",`${i}.config`];if(t)m.push(`${t}.config`);if(c)ui.info(`Checking user config directory: ${Y}`);for(let j of m)for(let N of h){let S=Ei(Y,`${j}${N}`),F=await Br(S,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory: ${S}`);return F}}}if(i){let Y=Ei(u0(),".config"),m=[`.${i}.config`];if(t)m.push(`.${t}.config`);if(c)ui.info(`Checking user config directory for dotfile configs: ${Y}`);for(let j of m)for(let N of h){let S=Ei(Y,`${j}${N}`),F=await Br(S,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user config directory dotfile: ${S}`);return F}}}if(i){let Y=u0(),m=[`.${i}.config`,`.${i}`];if(t)m.push(`.${t}.config`),m.push(`.${t}`);if(c)ui.info(`Checking user home directory for dotfile configs: ${Y}`);for(let j of m)for(let N of h){let S=Ei(Y,`${j}${N}`),F=await Br(S,w,y);if(F!==null){if(c)ui.success(`Configuration loaded from user home directory: ${S}`);return F}}}try{let Y=Ei(u,"package.json");if(cw(Y)){let m=await import(Y),j=m[i];if(!j&&t){if(j=m[t],j&&c)ui.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)ui.success(`Configuration loaded from package.json: ${j===m[i]?i:t}`);return p0(w,j,y)}catch(N){if(c)ui.warn("Failed to merge package.json config:",N)}}}catch(Y){if(c)ui.warn("Failed to load package.json:",Y)}if(c)ui.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function SA(i,t={}){let n=Jr.cwd();while(n.includes("storage"))n=cy(n,"..");let r=cy(n,i||"");if(t?.relative)return F1(Jr.cwd(),r);return r}async function WA(){try{let i=await NA({name:"clarity",alias:"logging",defaultConfig:Nr,cwd:Jr.cwd()});return{...Nr,...i||{}}}catch{return Nr}}function p(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function XA(){if(nt.env.NODE_ENV==="test"||nt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof nt<"u"){let i=nt.type;if(i==="renderer"||i==="worker")return!1;return!!(nt.versions&&(nt.versions.node||nt.versions.bun))}return!1}class $w{async format(i){let t=await XA(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Zt.pid,hostname:t(),environment:Zt.env.NODE_ENV||"development",platform:Zt.platform,version:Zt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Zt.env.NODE_ENV||Zt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Or{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...O0},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new $w,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Sr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Sr};return{...Sr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:O0.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await x1(this.config.logDirectory,Yy.F_OK|Yy.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await k1(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:oi.from(i);try{if(!yr(this.currentLogFile))await Y0(this.currentLogFile,"",{mode:420});if(r=ey(this.currentLogFile,"a",420),L1(r,y,{flag:"a"}),Ey(r),r!==void 0)e0(r),r=void 0;if((await bt(this.currentLogFile)).size===0){if(await Y0(this.currentLogFile,y,{flag:"w",mode:420}),(await bt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{e0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Pt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Pt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Pt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return E0(16).toString("hex")}generateKey(){return E0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=E0(16),r=q1("aes-256-gcm",t,n),f=oi.isBuffer(i)?i:oi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=oi.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=my(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(oi.from(oi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let i=await bt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await wr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await bt(n).catch(()=>null))try{if(await By(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await ur(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await Y0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await bt(n).catch(()=>null))await By(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await wr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await ur(Pt(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=Ty(i),r=g1(t),f=my();await D1(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),yr(this.currentLogFile))try{let i=ey(this.currentLogFile,"r+");Ey(i),e0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await wr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await ur(Pt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?Q.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let i=typeof H.env.NO_COLOR<"u",t=H.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=H.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${Q.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=Q.underline(Q.blue(r)),l=this.toAbsoluteFilePath(f);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>Q.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>Q.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>Q.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>Q.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>Q.strikethrough(r)),t}supportsHyperlinks(){if(p())return!1;let i=H.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=H.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(V1(t)||t.startsWith("./")||t.startsWith("../"))t=d1(t);else return null;return yr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":jw[i],A=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:Q.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:Q.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let B=y.split(`
|
|
14
|
+
`);for(let e of B)if(e.trim()&&!e.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:Q.gray(` ${e}`),level:i,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
|
|
15
15
|
`;if(y)h+=`${y}
|
|
16
16
|
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let n={update:(f,c)=>{},finish:(f)=>{},interrupt:(f,c)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,c="info")=>{if(!p()&&H.stdout.isTTY)H.stdout.write(`
|
|
17
17
|
`);if(this[c==="warning"?"warn":c](f),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":Q.blue("◐"),tag:n,message:`${Q.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
18
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":Q.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!p())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Or(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!yr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
18
|
+
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":Q.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!p())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Or(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!yr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ty(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=oi.isBuffer(i)?i:oi.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=s1("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=oi.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return p()}isServerMode(){return!p()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
|
|
19
19
|
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:Q.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:Q.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:Q.cyan(h),showTimestamp:!1}))}else if(!p())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let l=`${r} ${this.environment}.INFO: [BOX] ${c}
|
|
20
20
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(p())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${Q.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();H.stdin.removeListener("data",n);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(n=i.replace(l,(w,u)=>{if(u==="%")return"%";if(y>=t.length)return w;let h=t[y++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return w}}),y<t.length)n+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?Q.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${Q.blue("◐")} `;console.error(`${y}${l} ${Q.cyan(r)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=Q.green("━".repeat(r)),l=Q.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?Q.green("✓"):Q.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${Q.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=H.stdout.columns||80,
|
|
22
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||p()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await wr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Pt(this.config.logDirectory,r);if(i.before)try{if((await bt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await ur(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function
|
|
21
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=Q.green("━".repeat(r)),l=Q.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?Q.green("✓"):Q.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${Q.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=H.stdout.columns||80,B=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${B}`,H.stdout.write(i.lastRenderedLine),t)H.stdout.write(`
|
|
22
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||p()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await wr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Pt(this.config.logDirectory,r);if(i.before)try{if((await bt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await ur(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Aw(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function Tw(i){return i instanceof ai}function JA(i){return i instanceof Gr}function FA(i){if(Tw(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>i.message.toLowerCase().includes(t.toLowerCase()))}class dr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Qn.track("applyEnvironmentVariables",u,{configName:i});return u()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=hr.env[w]||(u?hr.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=hr.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof Hr)throw $;throw Ct.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Ct.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(hr.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
23
23
|
|
|
24
24
|
`;for(let r of i)n+=`${r.key}
|
|
25
25
|
`,n+=` Type: ${r.type}
|
|
@@ -31,25 +31,25 @@ import{Ab as Hl,Bb as I$,Db as Rt,Eb as Y,Fb as G$,Jb as ah,Kb as hl,Mb as Gf,Nb
|
|
|
31
31
|
`;n+=`| Variable | Type | Description | Example |
|
|
32
32
|
`,n+=`|----------|------|-------------|----------|
|
|
33
33
|
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
34
|
-
`;return n}}function FA(i,t){let n=Cw("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function Tw(i,t,n={}){return Ew(i,t,n,new WeakMap)}function Ew(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return Yw(i,t,f,r);if(!Fi(t)||!Fi(i))return t;return zA(i,t,n,r)}function Yw(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return IA(i,t);case"smart":return KA(i,t,r);default:return t}return t}function IA(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>Q0(f,r)))n.push(r);return n}function KA(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Fi(t[0])&&Fi(i[0]))return _A(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function _A(i,t,n){let r=[...t];for(let f of i){if(!Fi(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((w)=>Fi(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function zA(i,t,n,r){let f=t;if(Fi(f)&&r.has(f))return r.get(f);let c={...i};if(Fi(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Fi(y)&&Fi(w))c[l]=Ew(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Yw(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function ic(i,t,n="replace"){return Tw(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Q0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Q0(i[n],t[n]))return!1;return!0}if(Fi(i)&&Fi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Q0(i[f],t[f]))return!1}return!0}return!1}function Fi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Dr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=nn.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!$r(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new Kn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Kn(i,Error("Configuration must export a valid object"),"unknown");let C={config:ic(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)nn.setWithFileCheck("file",C,i,c);return C}catch(u){throw u instanceof Error?mt.configLoad(i,u):mt.configLoad(i,Error(String(u)))}};if(l)return Qn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(C0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return $w(async()=>{return $r(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!$r(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=C0(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=C0(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!$r(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class tc{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await Qn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!D1(t))throw new _n(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new _n(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(r.push({path:n,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(r.push({path:n?`${n}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,required:!c,type:this.mapTypeScriptType(l)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Nw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class nc{fileLoader=new Dr;envProcessor=new dr;validator=new tc;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)Gi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw Gi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||_t.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let C=await this.loadHomeConfiguration(r,f,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Yi($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw mt.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?an(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)Gi.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)Gi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?an(i,n,f):n,y=[Yi(kt(),".config",i),Yi(kt(),".config"),kt()];for(let w of y){if(f)Gi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)Gi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?an(i,r,c):r;try{let w=Yi(n,"package.json");if(!_0(w))return null;let u=await import(w),h=u[i],$=i;if(!h&&t)h=u[t],$=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)Gi.success(`Configuration loaded from package.json: ${$}`);return{config:ic(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)Gi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:an(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw mt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return nn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);nn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Yi(i,"config"),Yi(i,".config"),t?Yi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Yi(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Yi(kt(),".config",i),Yi(kt(),".config"),kt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Sy(i){let t=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||n}async function QA(i){return ct.loadConfig({...i,__strictErrorHandling:!0})}async function Bw(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await ct.loadConfig(i);else r=await ct.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)Gi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ct.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function MA(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await ct.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Sy(n)))return(await ct.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await ct.loadConfig({...i,cwd:i.cwd||_t.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Sy(t)))return(await ct.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function OA(i,t,n="replace"){let r=new Dr;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function an(i,t,n=!1){let r=new dr,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=_t.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}function GA(i){let t=Yi(_t.cwd(),i.configDir),n=Yi(_t.cwd(),i.generatedDir),r=Yi(n,"config-types.ts");if(!_0(ry(r)))X1(ry(r),{recursive:!0,mode:511});let f=_0(t)?W1(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${AT}
|
|
34
|
+
`;return n}}function IA(i,t){let n=mw("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function Ew(i,t,n={}){return ew(i,t,n,new WeakMap)}function ew(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return Yw(i,t,f,r);if(!Fi(t)||!Fi(i))return t;return QA(i,t,n,r)}function Yw(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return KA(i,t);case"smart":return _A(i,t,r);default:return t}return t}function KA(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>Q0(f,r)))n.push(r);return n}function _A(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Fi(t[0])&&Fi(i[0]))return zA(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function zA(i,t,n){let r=[...t];for(let f of i){if(!Fi(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((w)=>Fi(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function QA(i,t,n,r){let f=t;if(Fi(f)&&r.has(f))return r.get(f);let c={...i};if(Fi(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Fi(y)&&Fi(w))c[l]=ew(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Yw(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function ic(i,t,n="replace"){return Ew(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Q0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Q0(i[n],t[n]))return!1;return!0}if(Fi(i)&&Fi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Q0(i[f],t[f]))return!1}return!0}return!1}function Fi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Dr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=nn.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!$r(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new Kn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Kn(i,Error("Configuration must export a valid object"),"unknown");let B={config:ic(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)nn.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Ct.configLoad(i,u):Ct.configLoad(i,Error(String(u)))}};if(l)return Qn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(B0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return Aw(async()=>{return $r(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!$r(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=B0(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=B0(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!$r(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class tc{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await Qn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!b1(t))throw new _n(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new _n(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(r.push({path:n,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(r.push({path:n?`${n}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,required:!c,type:this.mapTypeScriptType(l)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:aw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class nc{fileLoader=new Dr;envProcessor=new dr;validator=new tc;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)Gi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw Gi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||_t.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let B=await this.loadHomeConfiguration(r,f,y,u,h,w);if(B)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(B,A,w,r,h);let e=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(e)return A.push(ei($,"package.json")),this.finalizeResult(e,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Ct.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Xn(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)Gi.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)Gi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Xn(i,n,f):n,y=[ei(kt(),".config",i),ei(kt(),".config"),kt()];for(let w of y){if(f)Gi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)Gi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Xn(i,r,c):r;try{let w=ei(n,"package.json");if(!_0(w))return null;let u=await import(w),h=u[i],$=i;if(!h&&t)h=u[t],$=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)Gi.success(`Configuration loaded from package.json: ${$}`);return{config:ic(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)Gi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Xn(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Ct.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return nn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);nn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,ei(i,"config"),ei(i,".config"),t?ei(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(ei(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[ei(kt(),".config",i),ei(kt(),".config"),kt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Xy(i){let t=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||n}async function MA(i){return ct.loadConfig({...i,__strictErrorHandling:!0})}async function Bw(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await ct.loadConfig(i);else r=await ct.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)Gi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let l=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ct.applyEnvironmentVariables(l.name||"",t,!0,l.verbose||!1))?.config??t;return t}}async function OA(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await ct.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Xy(n)))return(await ct.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await ct.loadConfig({...i,cwd:i.cwd||_t.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Xy(t)))return(await ct.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function GA(i,t,n="replace"){let r=new Dr;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Xn(i,t,n=!1){let r=new dr,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((e)=>e.toUpperCase()).join("")}`,`${f}_${$.map((e)=>e.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,B;for(let e of A)if(T=_t.env[e],T!==void 0){B=e;break}if(T!==void 0&&B)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let e=Number(T);if(!Number.isNaN(e))w[u]=e}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((e)=>e.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}function HA(i){let t=ei(_t.cwd(),i.configDir),n=ei(_t.cwd(),i.generatedDir),r=ei(n,"config-types.ts");if(!_0(fy(r)))S1(fy(r),{recursive:!0,mode:511});let f=_0(t)?W1(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${TT}
|
|
35
35
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
36
|
-
`;
|
|
37
|
-
${f.map((w)=>{let u=
|
|
36
|
+
`;X1(r,c,{mode:438})}function qA(i){let t=null,n=null,r=()=>{if(!n)n=Bw(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)Gi.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get(c,l){if(t)return t[l];let y=f[l];return r(),y},has(c,l){return l in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(c,l){return Object.getOwnPropertyDescriptor(t||f,l)},set(c,l,y){if(!t)t={...f};return t[l]=y,!0}})}function sA(i){let t=Cy(v1.cwd(),i?.configDir||"./config");function n(){if(!P1(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=Z1(t).filter((w)=>f.has(m0(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),y=new Map;for(let{base:w,file:u}of l){let h=m0(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=m0($).toLowerCase();if(c.indexOf(h)<c.indexOf(A))y.set(w,u)}return Array.from(y.entries()).map(([w,u])=>({base:w,file:u})).sort((w,u)=>w.base.localeCompare(u.base))}function r(){let f=n(),c=f.map((w)=>w.base),l=c.length?c.map((w)=>`'${w}'`).join(" | "):"string",y=f.length?`{
|
|
37
|
+
${f.map((w)=>{let u=Cy(t,w.file).replace(/\\/g,"/");return` '${w.base}': typeof import('${u}').default`}).join(`,
|
|
38
38
|
`)}
|
|
39
39
|
}`:"Record<string, any>";return`export type ConfigNames = ${l}
|
|
40
40
|
export type ConfigByName = ${y}
|
|
41
41
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
42
42
|
export type ConfigOf = Config
|
|
43
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Cw,nn,Qn,ew,gA,LA,ay,Nr,M0,wi,x,sA,Jy,xA,Fy,kA,VA,R0,dA,Iy,Ky,X0,DA,bA,PA,ZA,Rr,mw,vA,ui,oA,pA,_y,Xr,O0,ii,Q,iT,zy,tT,Qy,nT,rT,W0,fT,My,Oy,cT,S0,lT,yT,wT,uT,hT,Wr,Uw,$T,AT="0.15.6",Ri,Gr,Kn,G0,H0,Hr,q0,g0,_n,L0,s0,mt,jw,Nw,Gi,ct,Rw,Xw,TT=TA(async()=>{Cw=import.meta.require,nn=new Z0,Qn=new v0,ew={createKey:EA,isEquivalent:YA,estimateMemoryUsage:BA},gA=Ir(z0.cwd(),"config"),LA=Ir(z0.cwd(),"src/generated"),ay=Fr.env.CLARITY_LOG_DIR||F1(mA(),"logs"),Nr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ay,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},M0=await UA(),wi={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},x=wi,sA=wi.red,Jy=wi.green,xA=wi.yellow,Fy=wi.blue,kA=wi.magenta,VA=wi.cyan,R0=wi.white,dA=wi.gray,Iy=wi.bgRed,Ky=wi.bgYellow,X0=wi.bold,DA=wi.dim,bA=wi.italic,PA=wi.underline,ZA=wi.reset,Rr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},mw={debug:"\uD83D\uDD0D",info:Fy("ℹ"),success:Jy("✓"),warning:Ky(R0(X0(" WARN "))),error:Iy(R0(X0(" ERROR ")))},vA=new Qr("stacks"),ui=new Qr("bunfig",{showTags:!0}),oA=Ei(In.cwd(),"config"),pA=Ei(In.cwd(),"src/generated"),_y=Jr.env.CLARITY_LOG_DIR||a1(XA(),"logs"),Xr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_y,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},O0=await WA(),ii={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},Q=ii,iT=ii.red,zy=ii.green,tT=ii.yellow,Qy=ii.blue,nT=ii.magenta,rT=ii.cyan,W0=ii.white,fT=ii.gray,My=ii.bgRed,Oy=ii.bgYellow,cT=ii.bgGray,S0=ii.bold,lT=ii.dim,yT=ii.italic,wT=ii.underline,uT=ii.strikethrough,hT=ii.reset,Wr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Uw={debug:"\uD83D\uDD0D",info:Qy("ℹ"),success:zy("✓"),warning:Oy(W0(S0(" WARN "))),error:My(W0(S0(" ERROR ")))},$T=new Or("stacks"),Ri=class extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Gr=class extends Ri{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${i}"${r} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}},Kn=class extends Ri{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}},G0=class extends Ri{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}},H0=class extends Ri{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Hr=class extends Ri{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}},q0=class extends Ri{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}},g0=class extends Ri{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}},_n=class extends Ri{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}},L0=class extends Ri{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}},s0=class extends Ri{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}},mt={configNotFound(i,t,n){return new Gr(i,t,n)},configLoad(i,t,n){return new Kn(i,t,n)},configValidation(i,t,n){return new G0(i,t,n)},configMerge(i,t,n,r){return new H0(i,t,n,r)},envVar(i,t,n,r){return new Hr(i,t,n,r)},fileSystem(i,t,n){return new q0(i,t,n)},typeGeneration(i,t,n){return new g0(i,t,n)},schemaValidation(i,t,n){return new _n(i,t,n)},browserConfig(i,t,n,r){return new L0(i,t,n,r)},plugin(i,t,n){return new s0(i,t,n)}},jw={replace:"replace",concat:"concat",smart:"smart"},Nw=/^https?:\/\//,Gi=new Or("bunfig",{showTags:!0}),ct=new nc,Rw=Yi(_t.cwd(),"config"),Xw=Yi(_t.cwd(),"src/generated")});function ET(i,t={}){let n=Kr.cwd();while(n.includes("storage"))n=my(n,"..");let r=my(n,i||"");if(t?.relative)return o1(Kr.cwd(),r);return r}var YT=Kr.env.CLARITY_LOG_DIR||v1(ET(),"logs"),Ww={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:YT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},qr={...Ww},AU=(async()=>{try{let{loadConfig:i}=await TT().then(()=>ww),t=await i({name:"clarity",alias:"logging",defaultConfig:Ww,cwd:Kr.cwd()});if(t)Object.assign(qr,t)}catch{}return qr})();function ti(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function BT(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof rt<"u"){let i=rt.type;if(i==="renderer"||i==="worker")return!1;return!!(rt.versions&&(rt.versions.node||rt.versions.bun))}return!1}class Sw{async format(i){let t=await BT(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:pt.pid,hostname:t(),environment:pt.env.NODE_ENV||"development",platform:pt.platform,version:pt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pt.env.NODE_ENV||pt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ci={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=ci,TU=ci.red,CT=ci.green,EU=ci.yellow,eT=ci.blue,YU=ci.magenta,BU=ci.cyan,Gy=ci.white,CU=ci.gray,mT=ci.bgRed,UT=ci.bgYellow,eU=ci.bgGray,Hy=ci.bold,mU=ci.dim,UU=ci.italic,jU=ci.underline,NU=ci.strikethrough,RU=ci.reset,a0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jT={debug:"\uD83D\uDD0D",info:eT("ℹ"),success:CT("✓"),warning:UT(Gy(Hy(" WARN "))),error:mT(Gy(Hy(" ERROR ")))};class br{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...qr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Sw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...a0,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...a0};return{...a0,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:qr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await rA(this.config.logDirectory,Ry.F_OK|Ry.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await fA(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:pi.from(i);try{if(!Ar(this.currentLogFile))await j0(this.currentLogFile,"",{mode:420});if(r=Ny(this.currentLogFile,"a",420),nA(r,y,{flag:"a"}),jy(r),r!==void 0)U0(r),r=void 0;if((await vt(this.currentLogFile)).size===0){if(await j0(this.currentLogFile,y,{flag:"w",mode:420}),(await vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{U0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ot(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ot(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ot(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ti())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return m0(16).toString("hex")}generateKey(){return m0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=m0(16),r=p1("aes-256-gcm",t,n),f=pi.isBuffer(i)?i:pi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=pi.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Wy(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(pi.from(pi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Tr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await vt(n).catch(()=>null))try{if(await Xy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await Er(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await j0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await vt(n).catch(()=>null))await Xy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await Tr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await Er(ot(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=Uy(i),r=tA(t),f=Wy();await yA(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ar(this.currentLogFile))try{let i=Ny(this.currentLogFile,"r+");jy(i),U0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ti()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Tr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Er(ot(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ti())return!1;let i=typeof q.env.NO_COLOR<"u",t=q.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof q.stderr<"u"&&q.stderr.isTTY||typeof q.stdout<"u"&&q.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=q.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${O.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=O.underline(O.blue(r)),l=this.toAbsoluteFilePath(f);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>O.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>O.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>O.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>O.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>O.strikethrough(r)),t}supportsHyperlinks(){if(ti())return!1;let i=q.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=q.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(cA(t)||t.startsWith("./")||t.startsWith("../"))t=lA(t);else return null;return Ar(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":jT[i],A=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:O.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:O.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let C=y.split(`
|
|
44
|
-
`);for(let
|
|
43
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var mw,nn,Qn,Cw,gA,LA,Jy,Rr,M0,wi,x,xA,Fy,kA,Iy,VA,dA,a0,DA,Ky,_y,N0,bA,PA,ZA,vA,ar,Uw,oA,ui,pA,iT,zy,Nr,O0,ii,Q,tT,Qy,nT,My,rT,fT,S0,cT,Oy,Gy,lT,W0,yT,wT,uT,hT,$T,Sr,jw,AT,TT="0.15.6",ai,Gr,Kn,G0,H0,Hr,q0,s0,_n,g0,L0,Ct,Rw,aw,Gi,ct,Nw,Sw,ET=EA(async()=>{mw=import.meta.require,nn=new Z0,Qn=new v0,Cw={createKey:eA,isEquivalent:YA,estimateMemoryUsage:BA},gA=Ir(z0.cwd(),"config"),LA=Ir(z0.cwd(),"src/generated"),Jy=Fr.env.CLARITY_LOG_DIR||I1(UA(),"logs"),Rr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Jy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},M0=await jA(),wi={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},x=wi,xA=wi.red,Fy=wi.green,kA=wi.yellow,Iy=wi.blue,VA=wi.magenta,dA=wi.cyan,a0=wi.white,DA=wi.gray,Ky=wi.bgRed,_y=wi.bgYellow,N0=wi.bold,bA=wi.dim,PA=wi.italic,ZA=wi.underline,vA=wi.reset,ar={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Uw={debug:"\uD83D\uDD0D",info:Iy("ℹ"),success:Fy("✓"),warning:_y(a0(N0(" WARN "))),error:Ky(a0(N0(" ERROR ")))},oA=new Qr("stacks"),ui=new Qr("bunfig",{showTags:!0}),pA=Ei(In.cwd(),"config"),iT=Ei(In.cwd(),"src/generated"),zy=Jr.env.CLARITY_LOG_DIR||J1(SA(),"logs"),Nr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},O0=await WA(),ii={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},Q=ii,tT=ii.red,Qy=ii.green,nT=ii.yellow,My=ii.blue,rT=ii.magenta,fT=ii.cyan,S0=ii.white,cT=ii.gray,Oy=ii.bgRed,Gy=ii.bgYellow,lT=ii.bgGray,W0=ii.bold,yT=ii.dim,wT=ii.italic,uT=ii.underline,hT=ii.strikethrough,$T=ii.reset,Sr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jw={debug:"\uD83D\uDD0D",info:My("ℹ"),success:Qy("✓"),warning:Gy(S0(W0(" WARN "))),error:Oy(S0(W0(" ERROR ")))},AT=new Or("stacks"),ai=class extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Gr=class extends ai{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${i}"${r} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}},Kn=class extends ai{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}},G0=class extends ai{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}},H0=class extends ai{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Hr=class extends ai{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}},q0=class extends ai{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}},s0=class extends ai{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}},_n=class extends ai{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}},g0=class extends ai{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}},L0=class extends ai{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Ct={configNotFound(i,t,n){return new Gr(i,t,n)},configLoad(i,t,n){return new Kn(i,t,n)},configValidation(i,t,n){return new G0(i,t,n)},configMerge(i,t,n,r){return new H0(i,t,n,r)},envVar(i,t,n,r){return new Hr(i,t,n,r)},fileSystem(i,t,n){return new q0(i,t,n)},typeGeneration(i,t,n){return new s0(i,t,n)},schemaValidation(i,t,n){return new _n(i,t,n)},browserConfig(i,t,n,r){return new g0(i,t,n,r)},plugin(i,t,n){return new L0(i,t,n)}},Rw={replace:"replace",concat:"concat",smart:"smart"},aw=/^https?:\/\//,Gi=new Or("bunfig",{showTags:!0}),ct=new nc,Nw=ei(_t.cwd(),"config"),Sw=ei(_t.cwd(),"src/generated")});function eT(i,t={}){let n=Kr.cwd();while(n.includes("storage"))n=Uy(n,"..");let r=Uy(n,i||"");if(t?.relative)return p1(Kr.cwd(),r);return r}var YT=Kr.env.CLARITY_LOG_DIR||o1(eT(),"logs"),Ww={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:YT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},qr={...Ww},TU=(async()=>{try{let{loadConfig:i}=await ET().then(()=>uw),t=await i({name:"clarity",alias:"logging",defaultConfig:Ww,cwd:Kr.cwd()});if(t)Object.assign(qr,t)}catch{}return qr})();function ti(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function BT(){if(rt.env.NODE_ENV==="test"||rt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof rt<"u"){let i=rt.type;if(i==="renderer"||i==="worker")return!1;return!!(rt.versions&&(rt.versions.node||rt.versions.bun))}return!1}class Xw{async format(i){let t=await BT(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:pt.pid,hostname:t(),environment:pt.env.NODE_ENV||"development",platform:pt.platform,version:pt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:pt.env.NODE_ENV||pt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ci={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=ci,EU=ci.red,mT=ci.green,eU=ci.yellow,CT=ci.blue,YU=ci.magenta,BU=ci.cyan,Hy=ci.white,mU=ci.gray,UT=ci.bgRed,jT=ci.bgYellow,CU=ci.bgGray,qy=ci.bold,UU=ci.dim,jU=ci.italic,RU=ci.underline,aU=ci.strikethrough,NU=ci.reset,X0={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},RT={debug:"\uD83D\uDD0D",info:CT("ℹ"),success:mT("✓"),warning:jT(Hy(qy(" WARN "))),error:UT(Hy(qy(" ERROR ")))};class br{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...qr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Xw,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...X0,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...X0};return{...X0,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:qr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,c=3,l=1000;while(f<c)try{try{try{await fA(this.config.logDirectory,Ny.F_OK|Ny.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await cA(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let y=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:pi.from(i);try{if(!Ar(this.currentLogFile))await j0(this.currentLogFile,"",{mode:420});if(r=ay(this.currentLogFile,"a",420),rA(r,y,{flag:"a"}),Ry(r),r!==void 0)U0(r),r=void 0;if((await vt(this.currentLogFile)).size===0){if(await j0(this.currentLogFile,y,{flag:"w",mode:420}),(await vt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let u=w;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<c-1){let h=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${c}:`,h);let $=l*2**f;await new Promise((A)=>setTimeout(A,$)),f++;continue}}if(u?.code&&["ENOSPC","EDQUOT"].includes(u.code))throw Error(`Disk quota exceeded or no space left on device: ${u.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",u),u}finally{if(r!==void 0)try{U0(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch(y){if(f===c-1){let u=y,h=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),y}f++;let w=l*2**(f-1);await new Promise((u)=>setTimeout(u,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return ot(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return ot(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return ot(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ti())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,l],[,y])=>y.createdAt.getTime()-l.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,c=Math.max(1,f);if(r.length>c)for(let[l]of r.slice(c))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return C0(16).toString("hex")}generateKey(){return C0(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=C0(16),r=iA("aes-256-gcm",t,n),f=pi.isBuffer(i)?i:pi.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=pi.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Wy(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(pi.from(pi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await vt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Tr(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await vt(n).catch(()=>null))try{if(await Sy(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await Er(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await j0(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await vt(n).catch(()=>null))await Sy(n,c)}if(this.currentLogFile=r,t.maxFiles){let f=(await Tr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,l)=>l.localeCompare(c));for(let c of f.slice(t.maxFiles))await Er(ot(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=jy(i),r=nA(t),f=Wy();await wA(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Ar(this.currentLogFile))try{let i=ay(this.currentLogFile,"r+");Ry(i),U0(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ti()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Tr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Er(ot(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ti())return!1;let i=typeof q.env.NO_COLOR<"u",t=q.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof q.stderr<"u"&&q.stderr.isTTY||typeof q.stdout<"u"&&q.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=q.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${O.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=O.underline(O.blue(r)),l=this.toAbsoluteFilePath(f);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>O.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>O.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>O.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>O.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>O.strikethrough(r)),t}supportsHyperlinks(){if(ti())return!1;let i=q.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=q.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(lA(t)||t.startsWith("./")||t.startsWith("../"))t=yA(t);else return null;return Ar(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":RT[i],A=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:O.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:O.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let B=y.split(`
|
|
44
|
+
`);for(let e of B)if(e.trim()&&!e.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:O.gray(` ${e}`),level:i,showTimestamp:!1}))}break}}else if(!ti()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
|
|
45
45
|
`;if(y)h+=`${y}
|
|
46
46
|
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let n={update:(f,c)=>{},finish:(f)=>{},interrupt:(f,c)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,c="info")=>{if(!ti()&&q.stdout.isTTY)q.stdout.write(`
|
|
47
47
|
`);if(this[c==="warning"?"warn":c](f),this.activeProgressBar&&this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":O.blue("◐"),tag:n,message:`${O.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),w=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
48
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":O.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ti())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new br(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!Ar(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
48
|
+
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":O.green("✓"),tag:u,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ti())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new br(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!Ar(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return jy(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=pi.isBuffer(i)?i:pi.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=tA("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=pi.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ti()}isServerMode(){return!ti()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
|
|
49
49
|
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:O.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:O.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:O.cyan(h),showTimestamp:!1}))}else if(!ti())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let l=`${r} ${this.environment}.INFO: [BOX] ${c}
|
|
50
50
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(ti())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();q.stdin.removeListener("data",n);try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!1)}catch{}q.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!0)}catch{}q.stdin.resume(),q.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(n=i.replace(l,(w,u)=>{if(u==="%")return"%";if(y>=t.length)return w;let h=t[y++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return w}}),y<t.length)n+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${y}${l} ${O.cyan(r)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!q.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=O.green("━".repeat(r)),l=O.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?O.green("✓"):O.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=q.stdout.columns||80,
|
|
52
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ti()||!q.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ti()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Tr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=ot(this.config.logDirectory,r);if(i.before)try{if((await vt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Er(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var
|
|
51
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!q.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=O.green("━".repeat(r)),l=O.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?O.green("✓"):O.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=q.stdout.columns||80,B=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${B}`,q.stdout.write(i.lastRenderedLine),t)q.stdout.write(`
|
|
52
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ti()||!q.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ti()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Tr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=ot(this.config.logDirectory,r);if(i.before)try{if((await vt(f)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${f}:`,c);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await Er(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var SU=new br("stacks");class si extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Jw extends si{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class sr extends si{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class Fw extends si{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Iw extends si{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class rc extends si{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class Kw extends si{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class _w extends si{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class gr extends si{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class zw extends si{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class Qw extends si{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var rn={configNotFound(i,t,n){return new Jw(i,t,n)},configLoad(i,t,n){return new sr(i,t,n)},configValidation(i,t,n){return new Fw(i,t,n)},configMerge(i,t,n,r){return new Iw(i,t,n,r)},envVar(i,t,n,r){return new rc(i,t,n,r)},fileSystem(i,t,n){return new Kw(i,t,n)},typeGeneration(i,t,n){return new _w(i,t,n)},schemaValidation(i,t,n){return new gr(i,t,n)},browserConfig(i,t,n,r){return new zw(i,t,n,r)},plugin(i,t,n){return new Qw(i,t,n)}};async function aT(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class fc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return P0.track("applyEnvironmentVariables",u,{configName:i});return u()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=er.env[w]||(u?er.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=er.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof rc)throw $;throw rn.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw rn.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(er.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
53
53
|
|
|
54
54
|
`;for(let r of i)n+=`${r.key}
|
|
55
55
|
`,n+=` Type: ${r.type}
|
|
@@ -61,32 +61,32 @@ export type ConfigOf = Config
|
|
|
61
61
|
`;n+=`| Variable | Type | Description | Example |
|
|
62
62
|
`,n+=`|----------|------|-------------|----------|
|
|
63
63
|
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
64
|
-
`;return n}}function RT(i,t,n={}){return Qw(i,t,n,new WeakMap)}function Qw(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return Mw(i,t,f,r);if(!Ii(t)||!Ii(i))return t;return aT(i,t,n,r)}function Mw(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return XT(i,t);case"smart":return WT(i,t,r);default:return t}return t}function XT(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>x0(f,r)))n.push(r);return n}function WT(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return ST(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function ST(i,t,n){let r=[...t];for(let f of i){if(!Ii(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((w)=>Ii(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function aT(i,t,n,r){let f=t;if(Ii(f)&&r.has(f))return r.get(f);let c={...i};if(Ii(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Ii(y)&&Ii(w))c[l]=Qw(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Mw(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function Ow(i,t,n="replace"){return RT(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function x0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!x0(i[n],t[n]))return!1;return!0}if(Ii(i)&&Ii(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!x0(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Gw{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=_r.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!Br(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new gr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new gr(i,Error("Configuration must export a valid object"),"unknown");let C={config:Ow(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)_r.setWithFileCheck("file",C,i,c);return C}catch(u){throw u instanceof Error?rn.configLoad(i,u):rn.configLoad(i,Error(String(u)))}};if(l)return P0.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(N0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of r){if(!c)continue;if(n.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)n.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return n.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return NT(async()=>{return Br(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!Br(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=N0(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=N0(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!Br(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var JT=/^https?:\/\//;class Hw{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await P0.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!wA(t))throw new Lr(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Lr(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(r.push({path:n,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(r.push({path:n?`${n}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,required:!c,type:this.mapTypeScriptType(l)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:JT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var it=new br("bunfig",{showTags:!0});function FT(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class qw{fileLoader=new Gw;envProcessor=new fc;validator=new Hw;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)it.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){if(y instanceof Error&&y.name==="ConfigNotFoundError")throw y;let w=Date.now()-t;throw it.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||Vr.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let C=await this.loadHomeConfiguration(r,f,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Ji($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw rn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${FT(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?er(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)it.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)it.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?er(i,n,f):n,y=[Ji(xt(),".config",i),Ji(xt(),".config"),xt()];for(let w of y){if(f)it.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)it.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?er(i,r,c):r;try{let w=Ji(n,"package.json");if(!N1(w))return null;let u={};try{u=JSON.parse(R1(w,"utf8"))}catch(A){if(c)it.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let h=u[i],$=i;if(!h&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(u[T]){h=u[T],$=T;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)it.success(`Configuration loaded from package.json: ${$}`);return{config:Ow(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)it.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:er(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw rn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return _r.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);_r.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ji(i,"config"),Ji(i,".config"),t?Ji(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ji(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ji(xt(),".config",i),Ji(xt(),".config"),xt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var WU=new qw;function er(i,t,n=!1){let r=new fc,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=Vr.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}var SU=Ji(Vr.cwd(),"config"),aU=Ji(Vr.cwd(),"src/generated"),gw={altNameIPs:["127.0.0.1"],altNameURIs:["localhost"],organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:"tlsx.localhost",validityDays:825,hostCertCN:"tlsx.localhost",domain:"tlsx.localhost",rootCA:{certificate:"",privateKey:""},basePath:"",caCertPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};var o=gw,Hi={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var R={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},tn={info:(...i)=>console.log(...i),warn:(...i)=>console.warn(...i),success:(...i)=>console.log(...i),error:(...i)=>console.error(...i),debug:(...i)=>console.debug(...i)};function sw(i){return k0.readFileSync(i,"utf8")}function V0(i,t){let n=[];function r(f){let c;try{c=k0.readdirSync(f)}catch{return}for(let l of c){let y=Oi.join(f,l);try{if(k0.statSync(y).isDirectory())r(y);else if(l===t)n.push(f)}catch{continue}}}return r(i),n}function N(i,t,n){if(n||o.verbose)console.debug(`[tlsx:${i}] ${t}`)}var zT=_T(IT);function xw(){return Lw.env.SUDO_PASSWORD}var qy="[redacted]",QT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),MT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function OT(i){let t=i.toLowerCase();return QT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function sr(i){if(Array.isArray(i))return i.map((n)=>sr(n));if(typeof i==="string")return MT.test(i)?qy:i;if(!i||typeof i!=="object")return i;let t={};for(let[n,r]of Object.entries(i)){if(OT(n)){t[n]=qy;continue}t[n]=sr(r)}return t}function Pr(i){return JSON.stringify(sr(i))}function GT(i){let t=xw();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let n=t.replace(/'/g,"'\\''"),r=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function et(i,t={}){let n=GT(i);try{let{stdout:r,stderr:f}=await zT(n,{cwd:t.cwd||Lw.cwd(),timeout:t.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${i}
|
|
65
|
-
Error: ${r.message}`);throw f.stack=r.stack,f}}function
|
|
64
|
+
`;return n}}function NT(i,t,n={}){return Mw(i,t,n,new WeakMap)}function Mw(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return Ow(i,t,f,r);if(!Ii(t)||!Ii(i))return t;return JT(i,t,n,r)}function Ow(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return ST(i,t);case"smart":return WT(i,t,r);default:return t}return t}function ST(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>x0(f,r)))n.push(r);return n}function WT(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return XT(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function XT(i,t,n){let r=[...t];for(let f of i){if(!Ii(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((w)=>Ii(w)&&(y in w)&&w[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function JT(i,t,n,r){let f=t;if(Ii(f)&&r.has(f))return r.get(f);let c={...i};if(Ii(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(Ii(y)&&Ii(w))c[l]=Mw(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Ow(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function Gw(i,t,n="replace"){return NT(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function x0(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!x0(i[n],t[n]))return!1;return!0}if(Ii(i)&&Ii(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!x0(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Hw{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=_r.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!Yr(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new sr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new sr(i,Error("Configuration must export a valid object"),"unknown");let B={config:Gw(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)_r.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?rn.configLoad(i,u):rn.configLoad(i,Error(String(u)))}};if(l)return P0.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(R0(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of r){if(!c)continue;if(n.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)n.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return n.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return aT(async()=>{return Yr(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!Yr(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=R0(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=R0(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!Yr(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var FT=/^https?:\/\//;class qw{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await P0.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!uA(t))throw new gr(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new gr(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(r.push({path:n,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(r.push({path:n?`${n}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,required:!c,type:this.mapTypeScriptType(l)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:FT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var it=new br("bunfig",{showTags:!0});function IT(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class sw{fileLoader=new Hw;envProcessor=new fc;validator=new qw;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)it.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){if(y instanceof Error&&y.name==="ConfigNotFoundError")throw y;let w=Date.now()-t;throw it.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||Vr.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let B=await this.loadHomeConfiguration(r,f,y,u,h,w);if(B)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(B,A,w,r,h);let e=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(e)return A.push(Ji($,"package.json")),this.finalizeResult(e,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw rn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${IT(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?mr(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)it.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)it.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?mr(i,n,f):n,y=[Ji(xt(),".config",i),Ji(xt(),".config"),xt()];for(let w of y){if(f)it.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)it.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?mr(i,r,c):r;try{let w=Ji(n,"package.json");if(!a1(w))return null;let u={};try{u=JSON.parse(N1(w,"utf8"))}catch(A){if(c)it.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let h=u[i],$=i;if(!h&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(u[T]){h=u[T],$=T;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)it.success(`Configuration loaded from package.json: ${$}`);return{config:Gw(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)it.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:mr(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw rn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return _r.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);_r.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ji(i,"config"),Ji(i,".config"),t?Ji(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ji(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ji(xt(),".config",i),Ji(xt(),".config"),xt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var WU=new sw;function mr(i,t,n=!1){let r=new fc,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((e)=>e.toUpperCase()).join("")}`,`${f}_${$.map((e)=>e.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,B;for(let e of A)if(T=Vr.env[e],T!==void 0){B=e;break}if(T!==void 0&&B)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let e=Number(T);if(!Number.isNaN(e))w[u]=e}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((e)=>e.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}var XU=Ji(Vr.cwd(),"config"),JU=Ji(Vr.cwd(),"src/generated"),gw={altNameIPs:["127.0.0.1"],altNameURIs:["localhost"],organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:"tlsx.localhost",validityDays:825,hostCertCN:"tlsx.localhost",domain:"tlsx.localhost",rootCA:{certificate:"",privateKey:""},basePath:"",caCertPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:w0.join(y0.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1};var o=gw,Hi={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var a={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},tn={info:(...i)=>console.log(...i),warn:(...i)=>console.warn(...i),success:(...i)=>console.log(...i),error:(...i)=>console.error(...i),debug:(...i)=>console.debug(...i)};function xw(i){return k0.readFileSync(i,"utf8")}function V0(i,t){let n=[];function r(f){let c;try{c=k0.readdirSync(f)}catch{return}for(let l of c){let y=Oi.join(f,l);try{if(k0.statSync(y).isDirectory())r(y);else if(l===t)n.push(f)}catch{continue}}}return r(i),n}function R(i,t,n){if(n||o.verbose)console.debug(`[tlsx:${i}] ${t}`)}var QT=zT(KT);function kw(){return Lw.env.SUDO_PASSWORD}var sy="[redacted]",MT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),OT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function GT(i){let t=i.toLowerCase();return MT.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function Lr(i){if(Array.isArray(i))return i.map((n)=>Lr(n));if(typeof i==="string")return OT.test(i)?sy:i;if(!i||typeof i!=="object")return i;let t={};for(let[n,r]of Object.entries(i)){if(GT(n)){t[n]=sy;continue}t[n]=Lr(r)}return t}function Pr(i){return JSON.stringify(Lr(i))}function HT(i){let t=kw();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let n=t.replace(/'/g,"'\\''"),r=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function mt(i,t={}){let n=HT(i);try{let{stdout:r,stderr:f}=await QT(n,{cwd:t.cwd||Lw.cwd(),timeout:t.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${i}
|
|
65
|
+
Error: ${r.message}`);throw f.stack=r.stack,f}}function Vw(i){if(i.domain)return i.domain;if(i.domains?.length)return i.domains[0];throw Error("Either domain or domains must be specified")}function cc(i){let t=Oi.join(_T.homedir(),".stacks","ssl"),n=i.basePath&&i.basePath.trim()!==""?i.basePath:o.basePath&&o.basePath.trim()!==""?o.basePath:t,r=i.certPath?Oi.isAbsolute(i.certPath)?i.certPath:Oi.join(n,i.certPath):Oi.join(n,o.certPath),f=i.keyPath?Oi.isAbsolute(i.keyPath)?i.keyPath:Oi.join(n,i.keyPath):Oi.join(n,o.keyPath),c=i.caCertPath?Oi.isAbsolute(i.caCertPath)?i.caCertPath:Oi.join(n,i.caCertPath):Oi.join(n,o.caCertPath);return{certPath:r,keyPath:f,caCertPath:c,basePath:n}}function dw(i){let t=[],n=new Set;if(i.domain)n.add(i.domain);if(i.domains?.length)i.domains.forEach((r)=>n.add(r));for(let r of n)t.push({type:2,value:r});if(i.altNameIPs?.length)for(let r of i.altNameIPs)t.push({type:7,ip:r});if(i.altNameURIs?.length)for(let r of i.altNameURIs)t.push({type:6,value:r});if(i.subjectAltNames?.length)t.push(...i.subjectAltNames);return R(a.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function lc(i){let t=i.notBeforeDays??Hi.DEFAULT_NOT_BEFORE_DAYS,n=i.validityDays??(i.validityYears?i.validityYears*365:Hi.DEFAULT_VALIDITY_DAYS);R(a.CERT,"Calculating certificate validity dates",i.verbose);let r=new Date(Date.now()-86400*t*1000),f=new Date(r.getTime()+n*24*60*60*1000);return r.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),R(a.CERT,`Validity period: ${r.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:r,notAfter:f}}var qi={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},Yi={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};function Jn(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Si(i,t){let n=Jn(t.length);return Buffer.concat([Buffer.from([i]),n,t])}function zn(i){let t=i.split(".").map(Number),n=[];n.push(40*t[0]+t[1]);for(let r=2;r<t.length;r++){let f=t[r],c=[];c.unshift(f&127),f>>=7;while(f>0)c.unshift(f&127|128),f>>=7;n.push(...c)}return Si(qi.OID,Buffer.from(n))}function d0(i){let t;if(typeof i==="bigint"){let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Si(qi.INTEGER,t)}function Dw(i,t=0){return Si(qi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function bw(i){return Si(qi.OCTET_STRING,i)}function Ni(...i){return Si(qi.SEQUENCE,Buffer.concat(i))}function qT(...i){return Si(qi.SET,Buffer.concat(i))}function sT(i){return Si(qi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function gT(i){return Si(qi.UTF8_STRING,Buffer.from(i,"utf8"))}function LT(){return Buffer.from([qi.NULL,0])}function gy(i,t,n=!0){let r=160|i|(n?0:0),f=Jn(t.length);return Buffer.concat([Buffer.from([r]),f,t])}function Ly(i){let t=i.getUTCFullYear();if(t>=2050){let n=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Si(qi.GENERALIZED_TIME,Buffer.from(n,"ascii"))}else{let n=(t%100).toString().padStart(2,"0"),r=(i.getUTCMonth()+1).toString().padStart(2,"0"),f=i.getUTCDate().toString().padStart(2,"0"),c=i.getUTCHours().toString().padStart(2,"0"),l=i.getUTCMinutes().toString().padStart(2,"0"),y=i.getUTCSeconds().toString().padStart(2,"0"),w=`${n}${r}${f}${c}${l}${y}Z`;return Si(qi.UTC_TIME,Buffer.from(w,"ascii"))}}function xT(i,t){return Ni(Ly(i),Ly(t))}function xy(i){let t=[];for(let n of i){let r;switch(n.shortName){case"CN":r=Yi.COMMON_NAME;break;case"C":r=Yi.COUNTRY;break;case"L":r=Yi.LOCALITY;break;case"ST":r=Yi.STATE;break;case"O":r=Yi.ORGANIZATION;break;case"OU":r=Yi.ORGANIZATIONAL_UNIT;break;default:continue}let f=n.shortName==="C"?sT(n.value):gT(n.value),c=Ni(zn(r),f);t.push(qT(c))}return Ni(...t)}function Pw(i){return Ni(zn(i),LT())}function kT(i){return i.export({type:"spki",format:"der"})}function VT(i){if(i.includes(":")){let t=i;if(i.includes("::")){let f=i.split("::"),c=f[0]?f[0].split(":"):[],l=f[1]?f[1].split(":"):[],y=8-c.length-l.length,w=Array.from({length:y},()=>"0");t=[...c,...w,...l].join(":")}let n=t.split(":"),r=Buffer.alloc(16);for(let f=0;f<8;f++){let c=Number.parseInt(n[f]||"0",16);r.writeUInt16BE(c,f*2)}return r}else{let t=i.split(".").map((n)=>Number.parseInt(n,10));return Buffer.from(t)}}function dT(i){let t=[];for(let n of i)if(n.type===2&&n.value){let r=Jn(n.value.length);t.push(Buffer.concat([Buffer.from([130]),r,Buffer.from(n.value,"ascii")]))}else if(n.type===7&&n.ip){let r=VT(n.ip),f=Jn(r.length);t.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=Jn(n.value.length);t.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return Ni(...t)}function DT(i,t){if(i){if(t!==void 0)return Ni(Si(1,Buffer.from([255])),d0(t));return Ni(Si(1,Buffer.from([255])))}return Ni()}function bT(i){let t=0;if(i.digitalSignature)t|=128;if(i.keyEncipherment)t|=32;if(i.keyCertSign)t|=4;if(i.cRLSign)t|=2;let n=0,r=t;while(r>0&&(r&1)===0)n++,r>>=1;if(t===0)n=7;return Dw(Buffer.from([t]),n)}function PT(i){let t=[];if(i.serverAuth)t.push(zn(Yi.SERVER_AUTH));if(i.clientAuth)t.push(zn(Yi.CLIENT_AUTH));return Ni(...t)}function Wn(i,t,n){let r=[zn(i)];if(t)r.push(Si(1,Buffer.from([255])));return r.push(bw(n)),Ni(...r)}function ZT(i){let t=[];if(t.push(gy(0,d0(2))),t.push(d0(i.serialNumber)),t.push(Pw(Yi.SHA256_WITH_RSA)),t.push(xy(i.issuer)),t.push(xT(i.notBefore,i.notAfter)),t.push(xy(i.subject)),t.push(kT(i.publicKey)),i.extensions){let n=[];if(i.extensions.basicConstraints)n.push(Wn(Yi.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,DT(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)n.push(Wn(Yi.KEY_USAGE,i.extensions.keyUsage.critical??!0,bT(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)n.push(Wn(Yi.EXTENDED_KEY_USAGE,!1,PT(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)n.push(Wn(Yi.SUBJECT_ALT_NAME,!1,dT(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)n.push(Wn(Yi.SUBJECT_KEY_IDENTIFIER,!1,bw(i.extensions.subjectKeyIdentifier)));if(n.length>0)t.push(gy(3,Ni(...n)))}return Ni(...t)}function vT(i,t){let n=fn.createSign("SHA256");n.update(i);let r=n.sign(t);return Ni(i,Pw(Yi.SHA256_WITH_RSA),Dw(r))}function oT(i,t){let n=i.toString("base64"),r=[];for(let f=0;f<n.length;f+=64)r.push(n.slice(f,f+64));return`-----BEGIN ${t}-----
|
|
66
66
|
${r.join(`
|
|
67
67
|
`)}
|
|
68
68
|
-----END ${t}-----
|
|
69
|
-
`}function yc(){let i=fn.randomBytes(20);return i[0]=i[0]&127||1,i}function
|
|
70
|
-
`);for(let c of f){let[l,...y]=c.split("="),w=y.join("=");if(l&&w)r.push({shortName:l.trim(),value:w.trim()})}return{publicKey:n,subject:r}}async function wc(i={}){
|
|
71
|
-
`);for(let r of n){let[f,...c]=r.split("="),l=c.join("=");if(f&&l)t.push({shortName:f.trim(),value:l.trim()})}return t}function
|
|
72
|
-
`).some((r)=>{let f=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===n}))return N(R.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return N(R.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(n){return N(R.TRUST,`Error checking certificate trust: ${n}`,t),!1}}var wE={platform:"darwin",async addCertificate(i,t){if(await yE(i,t?.verbose)){N(R.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),tn.success("Certificate is already trusted in system keychain");return}N(R.TRUST,"Adding certificate to macOS keychain",t?.verbose),await et(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,n){let r=n||o.commonName;N(R.TRUST,`Removing certificate ${r} from macOS keychain`,t?.verbose);try{await et(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),N(R.TRUST,`Removed certificate ${r} from macOS keychain`,t?.verbose)}catch(f){throw N(R.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},uE={platform:"win32",async addCertificate(i,t){N(R.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await et(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,n){let r=n||o.commonName;N(R.TRUST,`Removing certificate ${r} from Windows certificate store`,t?.verbose);try{await et(`certutil -delstore -enterprise Root "${r}"`),N(R.TRUST,`Removed certificate ${r} from Windows certificate store`,t?.verbose)}catch(f){throw N(R.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},hE={platform:"linux",async addCertificate(i,t){N(R.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let n=xr.homedir(),r=Hi.LINUX_CERT_DB_FILENAME,f=Hi.LINUX_TRUST_ARGS;N(R.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let c=V0(n,r);if(c.length===0){tn.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of c){N(R.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{N(R.TRUST,`Attempting to delete existing cert for ${o.commonName}`,t?.verbose),await et(`certutil -d sql:${l} -D -n ${o.commonName}`)}catch(y){N(R.TRUST,`Warning: Error deleting existing cert: ${y}`,t?.verbose),console.warn(`Error deleting existing cert: ${y}`)}N(R.TRUST,`Adding new certificate to ${l}`,t?.verbose),await et(`certutil -d sql:${l} -A -t ${f} -n ${o.commonName} -i ${i}`),tn.info(`Cert added to ${l}`)}},async removeCertificate(i,t,n){let r=n||o.commonName;N(R.TRUST,`Removing certificate ${r} from Linux certificate store`,t?.verbose);let f=xr.homedir(),c=Hi.LINUX_CERT_DB_FILENAME;N(R.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let l=V0(f,c);if(l.length===0){tn.warn("No certificate databases found. Cannot remove certificate.");return}for(let y of l){N(R.TRUST,`Processing certificate database in ${y}`,t?.verbose);try{await et(`certutil -d sql:${y} -D -n "${r}"`),tn.info(`Cert removed from ${y}`)}catch(w){N(R.TRUST,`Error removing cert from ${y}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${y}: ${w}`)}}}},$E={darwin:wE,win32:uE,linux:hE};async function Tc(i,t,n){N(R.TRUST,`Adding certificate to system trust store with options: ${Pr(n)}`,n?.verbose),N(R.TRUST,"Storing certificate and private key",n?.verbose);let r=ow(i,n);N(R.TRUST,"Storing CA certificate",n?.verbose);let f=pw(t,n),c=xr.platform();N(R.TRUST,`Detected platform: ${c}`,n?.verbose);let l=$E[c];if(!l){let y=`Unsupported platform: ${c}`;throw N(R.TRUST,`Error: ${y}`,n?.verbose),Error(y)}return await l.addCertificate(f,n),N(R.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{homedir as tl}from"node:os";import{join as nl,resolve as $R}from"node:path";import{existsSync as tu,statSync as nu}from"fs";import{existsSync as AE,mkdirSync as Wj,readdirSync as Sj,readFileSync as TE,writeFileSync as aj}from"fs";import{homedir as cn}from"os";import{dirname as Ij,resolve as Ki}from"path";import _f from"process";import{existsSync as ru,statSync as fu}from"fs";import{existsSync as zc,mkdirSync as EE,readdirSync as YE,writeFileSync as BE}from"fs";import{homedir as ln}from"os";import{dirname as cu,resolve as ei}from"path";import zt from"process";import{join as CE,relative as eE,resolve as lu}from"path";import mf from"process";import{existsSync as xu,mkdirSync as gj,readdirSync as Lj,writeFileSync as sj}from"fs";import{homedir as Ec}from"os";import{dirname as Vj,resolve as Ci}from"path";import On from"process";import{join as mE,relative as UE,resolve as yu}from"path";import Uf from"process";import{existsSync as ku,mkdirSync as Zj,readdirSync as vj,writeFileSync as oj}from"fs";import{dirname as iN,resolve as jf}from"path";import Qc from"process";import{Buffer as jt}from"buffer";import{createCipheriv as jE,createDecipheriv as NE,randomBytes as Yc}from"crypto";import{closeSync as Bc,createReadStream as wu,createWriteStream as RE,existsSync as Cc,fsyncSync as uu,openSync as hu,writeFileSync as XE}from"fs";import{access as WE,constants as $u,mkdir as SE,readdir as or,rename as Au,stat as yn,unlink as pr,writeFile as ec}from"fs/promises";import{join as wn}from"path";import hi from"process";import{pipeline as aE}from"stream/promises";import{createGzip as Tu}from"zlib";import un from"process";import ut from"process";import{Buffer as lt}from"buffer";import{createCipheriv as JE,createDecipheriv as FE,randomBytes as mc}from"crypto";import{closeSync as Uc,createReadStream as Eu,createWriteStream as IE,existsSync as tf,fsyncSync as Yu,openSync as Bu,writeFileSync as KE}from"fs";import{access as _E,constants as Cu,mkdir as zE,readdir as nf,rename as eu,stat as hn,unlink as rf,writeFile as jc}from"fs/promises";import{isAbsolute as QE,join as $n,resolve as ME}from"path";import _ from"process";import{pipeline as OE}from"stream/promises";import{createGzip as mu}from"zlib";import An from"process";import ht from"process";import ff from"process";import{existsSync as cf}from"fs";import{resolve as Nc}from"path";import{existsSync as GE}from"fs";import{existsSync as HE,readdirSync as qE}from"fs";import{extname as Rc,resolve as Uu}from"path";import gE from"process";import{join as LE,relative as sE,resolve as ju}from"path";import Nf from"process";import{Buffer as yt}from"buffer";import{createCipheriv as xE,createDecipheriv as kE,randomBytes as Xc}from"crypto";import{closeSync as Wc,createReadStream as Nu,createWriteStream as VE,existsSync as lf,fsyncSync as Ru,openSync as Xu,writeFileSync as dE}from"fs";import{access as DE,constants as Wu,mkdir as bE,readdir as yf,rename as Su,stat as Tn,unlink as wf,writeFile as Sc}from"fs/promises";import{isAbsolute as PE,join as En,resolve as ZE}from"path";import z from"process";import{pipeline as vE}from"stream/promises";import{createGzip as au}from"zlib";import Yn from"process";import $t from"process";import hf from"process";import{existsSync as $f}from"fs";import{resolve as _c}from"path";import{existsSync as CB}from"fs";class Lu{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!tu(i))return!0;return nu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=tu(n)?nu(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class su{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var ef=new Lu,Vc=new su;var oE=Object.defineProperty,pE=(i)=>i;function iY(i,t){this[i]=pE.bind(null,t)}var tY=(i,t)=>{for(var n in t)oE(i,n,{get:t[n],enumerable:!0,configurable:!0,set:iY.bind(t,n)})},nY=(i,t)=>()=>(i&&(t=i(i=0)),t),Vu={};tY(Vu,{withErrorRecovery:()=>bu,tryLoadConfig:()=>WY,loadConfigWithResult:()=>RY,loadConfig:()=>pu,isRetryableError:()=>CY,isConfigNotFoundError:()=>BY,isBunfigError:()=>Pu,globalPerformanceMonitor:()=>qn,globalCache:()=>Bn,getEnvOrDefault:()=>eY,generateConfigTypes:()=>SY,defaultGeneratedDir:()=>yh,defaultConfigDir:()=>lh,deepMergeWithArrayStrategy:()=>Zc,deepMerge:()=>Zu,createLibraryConfig:()=>aY,config:()=>XY,bunfigPlugin:()=>JY,applyEnvVarsToConfig:()=>Mn,TypeGenerationError:()=>Lc,SchemaValidationError:()=>Hn,PluginError:()=>xc,PerformanceMonitor:()=>Dc,FileSystemError:()=>gc,ErrorFactory:()=>Nt,EnvVarError:()=>Jf,EnvProcessor:()=>zf,ConfigValidator:()=>vc,ConfigValidationError:()=>Hc,ConfigNotFoundError:()=>af,ConfigMergeError:()=>qc,ConfigLoader:()=>oc,ConfigLoadError:()=>Gn,ConfigFileLoader:()=>Qf,ConfigCache:()=>dc,CacheUtils:()=>th,BunfigError:()=>Si,BrowserConfigError:()=>sc,ArrayMergeStrategies:()=>fh});class dc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!ru(i))return!0;return fu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=ru(n)?fu(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Dc{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function rY(i,t={}){let r=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return r?`${i}:${r}`:i}function fY(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function cY(i){return i.getStats().size*2}function bc(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&d(t[0])&&"id"in t[0]&&t[0].id===3&&d(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(d(t)&&d(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(d(i)&&"arr"in i&&Array.isArray(i.arr)&&d(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&d(t[0])&&d(i[0])){let r=[...t];for(let f of i)if(d(f)&&"name"in f){if(!r.find((l)=>d(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(d(f)&&"path"in f){if(!r.find((l)=>d(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((c)=>Rf(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!d(t)||!d(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(d(f)&&d(n[r]))n[r]=bc(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&d(f[0])&&d(n[r][0])){let c=[...f];for(let l of n[r])if(d(l)&&"name"in l){if(!c.find((w)=>d(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(d(l)&&"path"in l){if(!c.find((w)=>d(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Rf(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function Rf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Rf(i[n],t[n]))return!1;return!0}if(d(i)&&d(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Rf(i[f],t[f]))return!1}return!0}return!1}function d(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function lY(i,t){if(!ku(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return bc(t,r)}catch{return null}}catch{return null}}async function yY({name:i="",cwd:t,defaultConfig:n}){let r=t||Qc.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=jf(r,`${l}${y}`),u=await lY(w,n);if(u!==null)return u}try{let l=jf(r,"package.json");if(ku(l)){let w=(await import(l))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return bc(n,w)}catch{}}}catch{}return n}function wY(i,t={}){let n=Uf.cwd();while(n.includes("storage"))n=yu(n,"..");let r=yu(n,i||"");if(t?.relative)return UE(Uf.cwd(),r);return r}async function uY(){try{let i=await yY({name:"clarity",defaultConfig:Ef,cwd:Uf.cwd(),endpoint:"",headers:{}});return{...Ef,...i}}catch{return Ef}}function P(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hY(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let i=ut.type;if(i==="renderer"||i==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class du{async format(i){let t=await hY(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:un.pid,hostname:t(),environment:un.env.NODE_ENV||"development",platform:un.platform,version:un.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:un.env.NODE_ENV||un.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Xf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Oc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new du,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??hi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Yf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Yf};return{...Yf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Oc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await WE(this.config.logDirectory,$u.F_OK|$u.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await SE(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:jt.from(i);try{if(!Cc(this.currentLogFile))await ec(this.currentLogFile,"",{mode:420});if(f=hu(this.currentLogFile,"a",420),XE(f,w,{flag:"a"}),uu(f),f!==void 0)Bc(f),f=void 0;if((await yn(this.currentLogFile)).size===0){if(await ec(this.currentLogFile,w,{flag:"w",mode:420}),(await yn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{Bc(f)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return wn(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return wn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return wn(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(P())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Yc(16).toString("hex")}generateKey(){return Yc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Yc(16),r=jE("aes-256-gcm",t,n),f=jt.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:jt.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Tu(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(jt.from(jt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(P())return;let i=await yn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await or(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await yn(n).catch(()=>null))try{if(await Au(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await pr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await ec(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await yn(n).catch(()=>null))await Au(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await or(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await pr(wn(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=wu(i),r=RE(t),f=Tu();await aE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Cc(this.currentLogFile))try{let i=hu(this.currentLogFile,"r+");uu(i),Bc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await or(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await pr(wn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?k.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=hi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${k.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!P()){let u=nh[i],h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:k.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:k.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
|
|
69
|
+
`}function yc(){let i=fn.randomBytes(20);return i[0]=i[0]&127||1,i}function Zw(i=2048){let{privateKey:t,publicKey:n}=fn.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:n}}function pT(i){let t=i.export({type:"spki",format:"der"});return fn.createHash("sha1").update(t).digest()}function vw(i){let t={serialNumber:i.serialNumber||yc(),notBefore:i.notBefore,notAfter:i.notAfter,subject:i.subject,issuer:i.issuer||i.subject,publicKey:i.publicKey,extensions:{basicConstraints:{isCA:i.isCA??!1,critical:!0,pathLenConstraint:i.pathLenConstraint},subjectKeyIdentifier:pT(i.publicKey)}};if(i.keyUsage)t.extensions.keyUsage={...i.keyUsage,critical:!0};if(i.extendedKeyUsage)t.extensions.extendedKeyUsage=i.extendedKeyUsage;if(i.subjectAltName?.length)t.extensions.subjectAltName=i.subjectAltName;let n=ZT(t),r=vT(n,i.signingKey);return{certificate:oT(r,"CERTIFICATE"),certificateDer:r}}function ow(i){return i.export({type:"pkcs8",format:"pem"})}function iE(i){return fn.createPrivateKey(i)}function tE(i){let t=new fn.X509Certificate(i),n=t.publicKey,r=[],f=t.subject.split(`
|
|
70
|
+
`);for(let c of f){let[l,...y]=c.split("="),w=y.join("=");if(l&&w)r.push({shortName:l.trim(),value:w.trim()})}return{publicKey:n,subject:r}}async function wc(i={}){R("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Hi.DEFAULT_KEY_SIZE;R("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:n,publicKey:r}=Zw(t),f=[{shortName:"C",value:i.countryName||o.countryName},{shortName:"ST",value:i.stateName||o.stateName},{shortName:"L",value:i.localityName||o.localityName},{shortName:"O",value:i.organization||"Local Development CA"},{shortName:"OU",value:i.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:i.commonName||"Local Development Root CA"}],{notBefore:c,notAfter:l}=lc({validityYears:i.validityYears||Hi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:y}=vw({serialNumber:yc(),notBefore:c,notAfter:l,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:y,privateKey:ow(n),notBefore:c,notAfter:l}}async function uc(i){if(R("ca","Generating new certificate",i.verbose),R("ca",`Options: ${Pr(i)}`,i.verbose),!i.domain&&!i.domains?.length)throw Error("Either domain or domains must be specified");if(!i.rootCA?.certificate||!i.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=tE(i.rootCA.certificate),n=iE(i.rootCA.privateKey);R("ca",`Generating ${Hi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let r=Hi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:c}=Zw(r),l=i.commonName||Vw(i),y=i.certificateAttributes||[{shortName:"C",value:i.countryName||o.countryName},{shortName:"ST",value:i.stateName||o.stateName},{shortName:"L",value:i.localityName||o.localityName},{shortName:"O",value:i.organizationName||o.organizationName},{shortName:"CN",value:l}],{notBefore:w,notAfter:u}=lc({validityDays:i.validityDays||Hi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),h=dw(i),$=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},A=i.extKeyUsage||{serverAuth:!0},{certificate:T}=vw({serialNumber:yc(),notBefore:w,notAfter:u,subject:y,issuer:t,publicKey:c,signingKey:n,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:$,extendedKeyUsage:A,subjectAltName:h});return{certificate:T,privateKey:ow(f),notBefore:w,notAfter:u}}function pw(i,t){R(a.STORAGE,`Storing certificate and private key with options: ${Pr(t)}`,t?.verbose);let{certPath:n,keyPath:r}=cc({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});R(a.STORAGE,`Certificate path: ${n}`,t?.verbose),R(a.STORAGE,`Private key path: ${r}`,t?.verbose);let f=D0.dirname(n);if(!ft.existsSync(f))R(a.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),ft.mkdirSync(f,{recursive:!0});R(a.STORAGE,"Writing certificate file",t?.verbose),ft.writeFileSync(n,i.certificate);let c=D0.dirname(r);if(!ft.existsSync(c))R(a.STORAGE,`Creating private key directory: ${c}`,t?.verbose),ft.mkdirSync(c,{recursive:!0});return R(a.STORAGE,"Writing private key file",t?.verbose),ft.writeFileSync(r,i.privateKey),R(a.STORAGE,"Certificate and private key stored successfully",t?.verbose),n}function iu(i,t){R(a.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:n}=cc({basePath:t?.basePath,caCertPath:t?.caCertPath});R(a.STORAGE,`CA certificate path: ${n}`,t?.verbose);let r=D0.dirname(n);if(!ft.existsSync(r))R(a.STORAGE,`Creating CA certificate directory: ${r}`,t?.verbose),ft.mkdirSync(r,{recursive:!0});return R(a.STORAGE,"Writing CA certificate file",t?.verbose),ft.writeFileSync(n,i),R(a.STORAGE,"CA certificate stored successfully",t?.verbose),n}function Zr(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=xw(i);return new nE.X509Certificate(t)}function vr(i){return Zr(i).fingerprint256.replace(/:/g,"").toUpperCase()}function hc(i){return tu(Zr(i).subject)}function $c(i,t,n=443,r=4000){let f;try{f=t.includes("-----BEGIN")?t:rE.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((c)=>{let l=!1,y=(u)=>{if(l)return;l=!0,c(u)},w=fE.connect({host:i,port:n,servername:i,ca:f,rejectUnauthorized:!0},()=>{y(w.authorized),w.end()});w.setTimeout(r,()=>{w.destroy(),y(!1)}),w.on("error",()=>y(!1))})}function cE(i){let t=[],n=i.split(`
|
|
71
|
+
`);for(let r of n){let[f,...c]=r.split("="),l=c.join("=");if(f&&l)t.push({shortName:f.trim(),value:l.trim()})}return t}function tu(i){return cE(i).find((t)=>t.shortName==="CN")?.value||""}function lE(i){let t=[],n=tu(i.subject);if(n&&!/^\d+\.\d+\.\d+\.\d+$/.test(n))t.push(n);let r=i.subjectAltName;if(r){let f=r.split(", ");for(let c of f)if(c.startsWith("DNS:"))t.push(c.slice(4))}return[...new Set(t)]}function Ac(i,t){let n=Zr(i),r=lE(n);for(let f of r){if(f===t)return!0;if(f.startsWith("*.")){let c=f.slice(2);if(t.endsWith(c)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function wE(i,t){if(xr.platform()!=="darwin")return!1;try{let n=vr(i);if(!n)return R(a.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(yE("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
72
|
+
`).some((r)=>{let f=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===n}))return R(a.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return R(a.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(n){return R(a.TRUST,`Error checking certificate trust: ${n}`,t),!1}}var uE={platform:"darwin",async addCertificate(i,t){if(await wE(i,t?.verbose)){R(a.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),tn.success("Certificate is already trusted in system keychain");return}R(a.TRUST,"Adding certificate to macOS keychain",t?.verbose),await mt(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,n){let r=n||o.commonName;R(a.TRUST,`Removing certificate ${r} from macOS keychain`,t?.verbose);try{await mt(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),R(a.TRUST,`Removed certificate ${r} from macOS keychain`,t?.verbose)}catch(f){throw R(a.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},hE={platform:"win32",async addCertificate(i,t){R(a.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await mt(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,n){let r=n||o.commonName;R(a.TRUST,`Removing certificate ${r} from Windows certificate store`,t?.verbose);try{await mt(`certutil -delstore -enterprise Root "${r}"`),R(a.TRUST,`Removed certificate ${r} from Windows certificate store`,t?.verbose)}catch(f){throw R(a.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},$E={platform:"linux",async addCertificate(i,t){R(a.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let n=xr.homedir(),r=Hi.LINUX_CERT_DB_FILENAME,f=Hi.LINUX_TRUST_ARGS;R(a.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let c=V0(n,r);if(c.length===0){tn.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of c){R(a.TRUST,`Processing certificate database in ${l}`,t?.verbose);try{R(a.TRUST,`Attempting to delete existing cert for ${o.commonName}`,t?.verbose),await mt(`certutil -d sql:${l} -D -n ${o.commonName}`)}catch(y){R(a.TRUST,`Warning: Error deleting existing cert: ${y}`,t?.verbose),console.warn(`Error deleting existing cert: ${y}`)}R(a.TRUST,`Adding new certificate to ${l}`,t?.verbose),await mt(`certutil -d sql:${l} -A -t ${f} -n ${o.commonName} -i ${i}`),tn.info(`Cert added to ${l}`)}},async removeCertificate(i,t,n){let r=n||o.commonName;R(a.TRUST,`Removing certificate ${r} from Linux certificate store`,t?.verbose);let f=xr.homedir(),c=Hi.LINUX_CERT_DB_FILENAME;R(a.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let l=V0(f,c);if(l.length===0){tn.warn("No certificate databases found. Cannot remove certificate.");return}for(let y of l){R(a.TRUST,`Processing certificate database in ${y}`,t?.verbose);try{await mt(`certutil -d sql:${y} -D -n "${r}"`),tn.info(`Cert removed from ${y}`)}catch(w){R(a.TRUST,`Error removing cert from ${y}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${y}: ${w}`)}}}},AE={darwin:uE,win32:hE,linux:$E};async function Tc(i,t,n){R(a.TRUST,`Adding certificate to system trust store with options: ${Pr(n)}`,n?.verbose),R(a.TRUST,"Storing certificate and private key",n?.verbose);let r=pw(i,n);R(a.TRUST,"Storing CA certificate",n?.verbose);let f=iu(t,n),c=xr.platform();R(a.TRUST,`Detected platform: ${c}`,n?.verbose);let l=AE[c];if(!l){let y=`Unsupported platform: ${c}`;throw R(a.TRUST,`Error: ${y}`,n?.verbose),Error(y)}return await l.addCertificate(f,n),R(a.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{homedir as tl}from"node:os";import{join as nl,resolve as Aa}from"node:path";import{existsSync as nu,statSync as ru}from"fs";import{existsSync as TE,mkdirSync as Wj,readdirSync as Xj,readFileSync as EE,writeFileSync as Jj}from"fs";import{homedir as cn}from"os";import{dirname as Kj,resolve as Ki}from"path";import _f from"process";import{existsSync as fu,statSync as cu}from"fs";import{existsSync as zc,mkdirSync as eE,readdirSync as YE,writeFileSync as BE}from"fs";import{homedir as ln}from"os";import{dirname as lu,resolve as mi}from"path";import zt from"process";import{join as mE,relative as CE,resolve as yu}from"path";import Cf from"process";import{existsSync as ku,mkdirSync as gj,readdirSync as Lj,writeFileSync as xj}from"fs";import{homedir as Ec}from"os";import{dirname as dj,resolve as Bi}from"path";import On from"process";import{join as UE,relative as jE,resolve as wu}from"path";import Uf from"process";import{existsSync as Vu,mkdirSync as vj,readdirSync as oj,writeFileSync as pj}from"fs";import{dirname as tR,resolve as jf}from"path";import Qc from"process";import{Buffer as jt}from"buffer";import{createCipheriv as RE,createDecipheriv as aE,randomBytes as ec}from"crypto";import{closeSync as Yc,createReadStream as uu,createWriteStream as NE,existsSync as Bc,fsyncSync as hu,openSync as $u,writeFileSync as SE}from"fs";import{access as WE,constants as Au,mkdir as XE,readdir as or,rename as Tu,stat as yn,unlink as pr,writeFile as mc}from"fs/promises";import{join as wn}from"path";import hi from"process";import{pipeline as JE}from"stream/promises";import{createGzip as Eu}from"zlib";import un from"process";import ut from"process";import{Buffer as lt}from"buffer";import{createCipheriv as FE,createDecipheriv as IE,randomBytes as Cc}from"crypto";import{closeSync as Uc,createReadStream as eu,createWriteStream as KE,existsSync as tf,fsyncSync as Yu,openSync as Bu,writeFileSync as _E}from"fs";import{access as zE,constants as mu,mkdir as QE,readdir as nf,rename as Cu,stat as hn,unlink as rf,writeFile as jc}from"fs/promises";import{isAbsolute as ME,join as $n,resolve as OE}from"path";import _ from"process";import{pipeline as GE}from"stream/promises";import{createGzip as Uu}from"zlib";import An from"process";import ht from"process";import ff from"process";import{existsSync as cf}from"fs";import{resolve as Rc}from"path";import{existsSync as HE}from"fs";import{existsSync as qE,readdirSync as sE}from"fs";import{extname as ac,resolve as ju}from"path";import gE from"process";import{join as LE,relative as xE,resolve as Ru}from"path";import Rf from"process";import{Buffer as yt}from"buffer";import{createCipheriv as kE,createDecipheriv as VE,randomBytes as Nc}from"crypto";import{closeSync as Sc,createReadStream as au,createWriteStream as dE,existsSync as lf,fsyncSync as Nu,openSync as Su,writeFileSync as DE}from"fs";import{access as bE,constants as Wu,mkdir as PE,readdir as yf,rename as Xu,stat as Tn,unlink as wf,writeFile as Wc}from"fs/promises";import{isAbsolute as ZE,join as En,resolve as vE}from"path";import z from"process";import{pipeline as oE}from"stream/promises";import{createGzip as Ju}from"zlib";import en from"process";import $t from"process";import hf from"process";import{existsSync as $f}from"fs";import{resolve as _c}from"path";import{existsSync as mY}from"fs";class Lu{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!nu(i))return!0;return ru(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=nu(n)?ru(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class xu{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var mf=new Lu,Vc=new xu;var pE=Object.defineProperty,ie=(i)=>i;function te(i,t){this[i]=ie.bind(null,t)}var ne=(i,t)=>{for(var n in t)pE(i,n,{get:t[n],enumerable:!0,configurable:!0,set:te.bind(t,n)})},re=(i,t)=>()=>(i&&(t=i(i=0)),t),du={};ne(du,{withErrorRecovery:()=>Pu,tryLoadConfig:()=>We,loadConfigWithResult:()=>Ne,loadConfig:()=>ih,isRetryableError:()=>me,isConfigNotFoundError:()=>Be,isBunfigError:()=>Zu,globalPerformanceMonitor:()=>qn,globalCache:()=>Yn,getEnvOrDefault:()=>Ce,generateConfigTypes:()=>Xe,defaultGeneratedDir:()=>wh,defaultConfigDir:()=>yh,deepMergeWithArrayStrategy:()=>Zc,deepMerge:()=>vu,createLibraryConfig:()=>Je,config:()=>Se,bunfigPlugin:()=>Fe,applyEnvVarsToConfig:()=>Mn,TypeGenerationError:()=>gc,SchemaValidationError:()=>Hn,PluginError:()=>xc,PerformanceMonitor:()=>Dc,FileSystemError:()=>sc,ErrorFactory:()=>Rt,EnvVarError:()=>Jf,EnvProcessor:()=>zf,ConfigValidator:()=>vc,ConfigValidationError:()=>Hc,ConfigNotFoundError:()=>Xf,ConfigMergeError:()=>qc,ConfigLoader:()=>oc,ConfigLoadError:()=>Gn,ConfigFileLoader:()=>Qf,ConfigCache:()=>dc,CacheUtils:()=>nh,BunfigError:()=>Wi,BrowserConfigError:()=>Lc,ArrayMergeStrategies:()=>ch});class dc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),c=r??this.options.ttl,l=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:c,hits:0,size:l}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!fu(i))return!0;return cu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=fu(n)?cu(n):null,c=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:c},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Dc{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let c=await t(),l=performance.now()-r;return this.recordMetric({operation:i,duration:l,timestamp:f,...n}),c}catch(c){let l=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:l,timestamp:f,...n}),c}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,c)=>f+c,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function fe(i,t={}){let r=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return r?`${i}:${r}`:i}function ce(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function le(i){return i.getStats().size*2}function bc(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&d(t[0])&&"id"in t[0]&&t[0].id===3&&d(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(d(t)&&d(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(d(i)&&"arr"in i&&Array.isArray(i.arr)&&d(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&d(t[0])&&d(i[0])){let r=[...t];for(let f of i)if(d(f)&&"name"in f){if(!r.find((l)=>d(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(d(f)&&"path"in f){if(!r.find((l)=>d(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((c)=>af(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!d(t)||!d(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(d(f)&&d(n[r]))n[r]=bc(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&d(f[0])&&d(n[r][0])){let c=[...f];for(let l of n[r])if(d(l)&&"name"in l){if(!c.find((w)=>d(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(d(l)&&"path"in l){if(!c.find((w)=>d(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>af(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function af(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!af(i[n],t[n]))return!1;return!0}if(d(i)&&d(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!af(i[f],t[f]))return!1}return!0}return!1}function d(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function ye(i,t){if(!Vu(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return bc(t,r)}catch{return null}}catch{return null}}async function we({name:i="",cwd:t,defaultConfig:n}){let r=t||Qc.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],c=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let l of c)for(let y of f){let w=jf(r,`${l}${y}`),u=await ye(w,n);if(u!==null)return u}try{let l=jf(r,"package.json");if(Vu(l)){let w=(await import(l))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return bc(n,w)}catch{}}}catch{}return n}function ue(i,t={}){let n=Uf.cwd();while(n.includes("storage"))n=wu(n,"..");let r=wu(n,i||"");if(t?.relative)return jE(Uf.cwd(),r);return r}async function he(){try{let i=await we({name:"clarity",defaultConfig:Ef,cwd:Uf.cwd(),endpoint:"",headers:{}});return{...Ef,...i}}catch{return Ef}}function P(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function $e(){if(ut.env.NODE_ENV==="test"||ut.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ut<"u"){let i=ut.type;if(i==="renderer"||i==="worker")return!1;return!!(ut.versions&&(ut.versions.node||ut.versions.bun))}return!1}class Du{async format(i){let t=await $e(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:un.pid,hostname:t(),environment:un.env.NODE_ENV||"development",platform:un.platform,version:un.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:un.env.NODE_ENV||un.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Nf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Oc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Du,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??hi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...ef,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...ef};return{...ef,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Oc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await WE(this.config.logDirectory,Au.F_OK|Au.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await XE(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:jt.from(i);try{if(!Bc(this.currentLogFile))await mc(this.currentLogFile,"",{mode:420});if(f=$u(this.currentLogFile,"a",420),SE(f,w,{flag:"a"}),hu(f),f!==void 0)Yc(f),f=void 0;if((await yn(this.currentLogFile)).size===0){if(await mc(this.currentLogFile,w,{flag:"w",mode:420}),(await yn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{Yc(f)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return wn(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return wn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return wn(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(P())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return ec(16).toString("hex")}generateKey(){return ec(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=ec(16),r=RE("aes-256-gcm",t,n),f=jt.concat([r.update(i,"utf8"),r.final()]),c=r.getAuthTag();return{encrypted:jt.concat([n,f,c]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Eu(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(jt.from(jt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(P())return;let i=await yn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await or(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await yn(n).catch(()=>null))try{if(await Tu(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await pr(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await mc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await yn(n).catch(()=>null))await Tu(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await or(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await pr(wn(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=uu(i),r=NE(t),f=Eu();await JE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Bc(this.currentLogFile))try{let i=$u(this.currentLogFile,"r+");hu(i),Yc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await or(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await pr(wn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?k.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=hi.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${k.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);if(this.fancy&&!P()){let u=rh[i],h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",$;switch(i){case"debug":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:k.gray(l),level:i}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:k.green(l),level:i}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:f,icon:u,tag:h,message:l,level:i}),console.error($),y){let A=y.split(`
|
|
73
73
|
`);for(let T of A)if(T.trim()&&!T.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:k.gray(` ${T}`),level:i,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let w=`${c} ${this.environment}.${i.toUpperCase()}: ${l}
|
|
74
74
|
`;if(y)w+=`${y}
|
|
75
75
|
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!P()){let n=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:k.blue("◐"),tag:n,message:`${k.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)u+=` ${JSON.stringify(n)}`;if(u+=`
|
|
76
|
-
`,u=u.replace(this.ANSI_PATTERN,""),this.fancy&&!P()){let h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:k.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!P())console.error(u.trim());await this.writeToFile(u)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new
|
|
76
|
+
`,u=u.replace(this.ANSI_PATTERN,""),this.fancy&&!P()){let h=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:k.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!P())console.error(u.trim());await this.writeToFile(u)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Nf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Bc(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uu(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=jt.isBuffer(i)?i:jt.from(i,"base64"),f=r.slice(0,16),c=r.slice(-16),l=r.slice(16,-16),y=aE("aes-256-gcm",n,f);return y.setAuthTag(c),jt.concat([y.update(l),y.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!P()){let c=i.split(`
|
|
77
77
|
`),l=Math.max(...c.map((h)=>h.length))+2,y=`┌${"─".repeat(l)}┐`,w=`└${"─".repeat(l)}┘`,u=c.map((h)=>{let $=" ".repeat(l-h.length-2);return`│ ${h}${$} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:k.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:k.cyan(y)})),u.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:n,message:k.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:k.cyan(w),showTimestamp:!1}))}else if(!P())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let f=`${r} ${this.environment}.INFO: [BOX] ${i}
|
|
78
78
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(P())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${k.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();hi.stdin.removeListener("data",n);try{if(typeof hi.stdin.setRawMode==="function")hi.stdin.setRawMode(!1)}catch{}hi.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof hi.stdin.setRawMode==="function")hi.stdin.setRawMode(!0)}catch{}hi.stdin.resume(),hi.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let l=/%([sdijfo%])/g,y=0;if(n=i.replace(l,(w,u)=>{if(u==="%")return"%";if(y>=t.length)return w;let h=t[y++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return w}}),y<t.length)n+=` ${t.slice(y).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}if(this.fancy&&!P()){let l=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",y=k.blue("◐");console.error(`${y} ${l} ${k.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
79
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(c)}progress(i,t=""){if(!this.enabled||!this.fancy||P()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(l,y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,l)),y!==void 0)this.activeProgressBar.message=y;let w=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,w)},finish:(l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=this.activeProgressBar.total,l!==void 0)this.activeProgressBar.message=l;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(l,y="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;hi.stdout.write(`${"\r".padEnd(hi.stdout.columns||80)}\r`),this.log(y,l),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||P()||!hi.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=k.green("━".repeat(r)),l=k.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||n===100?k.green("✓"):k.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=hi.stdout.columns||80,
|
|
80
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||P()||!hi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await or(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=wn(this.config.logDirectory,r);if(i.before)try{if((await yn(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await pr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Tf(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&s(t[0])&&"id"in t[0]&&t[0].id===3&&s(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(s(t)&&s(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(s(i)&&"arr"in i&&Array.isArray(i.arr)&&s(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&s(t[0])&&s(i[0])){let r=[...t];for(let f of i)if(s(f)&&"name"in f){if(!r.find((l)=>s(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(s(f)&&"path"in f){if(!r.find((l)=>s(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((c)=>Wf(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!s(t)||!s(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(s(f)&&s(n[r]))n[r]=Tf(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&s(f[0])&&s(n[r][0])){let c=[...f];for(let l of n[r])if(s(l)&&"name"in l){if(!c.find((w)=>s(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(s(l)&&"path"in l){if(!c.find((w)=>s(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Wf(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function Pc(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:Tf(i,t);if(Array.isArray(i))return n==="replace"?t:Tf(i,t);if(!s(t)||!s(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=r[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(n==="replace")r[f]=c;else r[f]=Tf(l,c);else if(s(c)&&s(l))r[f]=Pc(l,c,n);else r[f]=c}return r}function Wf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Wf(i[n],t[n]))return!1;return!0}if(s(i)&&s(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Wf(i[f],t[f]))return!1}return!0}return!1}function s(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function uf(i,t,n="replace"){if(!xu(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Pc(t,f,n)}catch{return null}}catch{return null}}function $Y(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...t};function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),T=`${r}_${$.map(A).join("_")}`,C=`${r}_${$.map((E)=>E.toUpperCase()).join("_")}`;if(n)Ai.info(`Checking environment variable ${T} for config ${i}.${$.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[u]=c(h,$);else{let E=On.env[T]||On.env[C];if(E!==void 0){if(n)Ai.info(`Using environment variable ${E?T:C} for config ${i}.${$.join(".")}`);if(typeof h==="number")w[u]=Number(E);else if(typeof h==="boolean")w[u]=E.toLowerCase()==="true";else if(Array.isArray(h))try{let B=JSON.parse(E);if(Array.isArray(B))w[u]=B;else w[u]=E.split(",").map((e)=>e.trim())}catch{w[u]=E.split(",").map((B)=>B.trim())}else w[u]=E}}}return w}return c(f)}async function AY({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?$Y(i,f,c):f,u=n||On.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)Ai.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${u}`);let $=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],C=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([u,Ci(u,"config"),Ci(u,".config"),r?Ci(u,r):void 0].filter(Boolean)));for(let B of E){if(c)Ai.info(`Searching for configuration in: ${B}`);let j=[Ci(u,"config"),Ci(u,".config")].concat(r?[Ci(u,r)]:[]).includes(B)?[...$,...A,...T,...C]:[...A,...$,...C,...T];for(let X of j)for(let W of h){let F=Ci(B,`${X}${W}`),a=await uf(F,w,y);if(a!==null){if(c)Ai.success(`Configuration loaded from: ${F}`);return a}}}if(i){let B=Ci(Ec(),".config",i),e=["config",`${i}.config`];if(t)e.push(`${t}.config`);if(c)Ai.info(`Checking user config directory: ${B}`);for(let j of e)for(let X of h){let W=Ci(B,`${j}${X}`),F=await uf(W,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory: ${W}`);return F}}}if(i){let B=Ci(Ec(),".config"),e=[`.${i}.config`];if(t)e.push(`.${t}.config`);if(c)Ai.info(`Checking user config directory for dotfile configs: ${B}`);for(let j of e)for(let X of h){let W=Ci(B,`${j}${X}`),F=await uf(W,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory dotfile: ${W}`);return F}}}if(i){let B=Ec(),e=[`.${i}.config`,`.${i}`];if(t)e.push(`.${t}.config`),e.push(`.${t}`);if(c)Ai.info(`Checking user home directory for dotfile configs: ${B}`);for(let j of e)for(let X of h){let W=Ci(B,`${j}${X}`),F=await uf(W,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user home directory: ${W}`);return F}}}try{let B=Ci(u,"package.json");if(xu(B)){let e=await import(B),j=e[i];if(!j&&t){if(j=e[t],j&&c)Ai.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)Ai.success(`Configuration loaded from package.json: ${j===e[i]?i:t}`);return Pc(w,j,y)}catch(X){if(c)Ai.warn("Failed to merge package.json config:",X)}}}catch(B){if(c)Ai.warn("Failed to load package.json:",B)}if(c)Ai.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function TY(i,t={}){let n=mf.cwd();while(n.includes("storage"))n=lu(n,"..");let r=lu(n,i||"");if(t?.relative)return eE(mf.cwd(),r);return r}async function EY(){try{let i=await AY({name:"clarity",alias:"logging",defaultConfig:Bf,cwd:mf.cwd()});return{...Bf,...i||{}}}catch{return Bf}}function ni(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function YY(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ht<"u"){let i=ht.type;if(i==="renderer"||i==="worker")return!1;return!!(ht.versions&&(ht.versions.node||ht.versions.bun))}return!1}class Du{async format(i){let t=await YY(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:An.pid,hostname:t(),environment:An.env.NODE_ENV||"development",platform:An.platform,version:An.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:An.env.NODE_ENV||An.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Sf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Gc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Du,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Cf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Cf};return{...Cf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Gc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await _E(this.config.logDirectory,Cu.F_OK|Cu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await zE(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:lt.from(i);try{if(!tf(this.currentLogFile))await jc(this.currentLogFile,"",{mode:420});if(f=Bu(this.currentLogFile,"a",420),KE(f,w,{flag:"a"}),Yu(f),f!==void 0)Uc(f),f=void 0;if((await hn(this.currentLogFile)).size===0){if(await jc(this.currentLogFile,w,{flag:"w",mode:420}),(await hn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{Uc(f)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return $n(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return $n(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return $n(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ni())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return mc(16).toString("hex")}generateKey(){return mc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=mc(16),r=JE("aes-256-gcm",t,n),f=lt.isBuffer(i)?i:lt.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=lt.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=mu(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(lt.from(lt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ni())return;if(!this.shouldWriteToFile())return;let i=await hn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await nf(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await hn(n).catch(()=>null))try{if(await eu(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await rf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await jc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await hn(n).catch(()=>null))await eu(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await nf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await rf($n(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=Eu(i),r=IE(t),f=mu();await OE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),tf(this.currentLogFile))try{let i=Bu(this.currentLogFile,"r+");Yu(i),Uc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ni()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await nf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await rf($n(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?M.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=_.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${M.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=M.underline(M.blue(r)),l=this.toAbsoluteFilePath(f);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>M.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>M.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>M.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>M.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>M.strikethrough(r)),t}supportsHyperlinks(){if(ni())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=_.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(QE(t)||t.startsWith("./")||t.startsWith("../"))t=ME(t);else return null;return tf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":rh[i],A=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:M.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:M.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let C=y.split(`
|
|
81
|
-
`);for(let
|
|
79
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(c)}progress(i,t=""){if(!this.enabled||!this.fancy||P()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(l,y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,l)),y!==void 0)this.activeProgressBar.message=y;let w=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,w)},finish:(l)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=this.activeProgressBar.total,l!==void 0)this.activeProgressBar.message=l;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(l,y="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;hi.stdout.write(`${"\r".padEnd(hi.stdout.columns||80)}\r`),this.log(y,l),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||P()||!hi.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=k.green("━".repeat(r)),l=k.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=t||n===100?k.green("✓"):k.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=hi.stdout.columns||80,B=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${B}`,hi.stdout.write(i.lastRenderedLine),t)hi.stdout.write(`
|
|
80
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||P()||!hi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await or(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=wn(this.config.logDirectory,r);if(i.before)try{if((await yn(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await pr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function Tf(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&L(t[0])&&"id"in t[0]&&t[0].id===3&&L(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(L(t)&&L(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(L(i)&&"arr"in i&&Array.isArray(i.arr)&&L(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&L(t[0])&&L(i[0])){let r=[...t];for(let f of i)if(L(f)&&"name"in f){if(!r.find((l)=>L(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(L(f)&&"path"in f){if(!r.find((l)=>L(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((c)=>Sf(c,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!L(t)||!L(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(L(f)&&L(n[r]))n[r]=Tf(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&L(f[0])&&L(n[r][0])){let c=[...f];for(let l of n[r])if(L(l)&&"name"in l){if(!c.find((w)=>L(w)&&("name"in w)&&w.name===l.name))c.push(l)}else if(L(l)&&"path"in l){if(!c.find((w)=>L(w)&&("path"in w)&&w.path===l.path))c.push(l)}else if(!c.some((y)=>Sf(y,l)))c.push(l);n[r]=c}else if(f.every((c)=>typeof c==="string")&&n[r].every((c)=>typeof c==="string")){let c=[...f];for(let l of n[r])if(!c.includes(l))c.push(l);n[r]=c}else n[r]=f;else n[r]=f}return n}function Pc(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:Tf(i,t);if(Array.isArray(i))return n==="replace"?t:Tf(i,t);if(!L(t)||!L(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let c=t[f],l=r[f];if(c===null||c===void 0)continue;if(Array.isArray(c)||Array.isArray(l))if(n==="replace")r[f]=c;else r[f]=Tf(l,c);else if(L(c)&&L(l))r[f]=Pc(l,c,n);else r[f]=c}return r}function Sf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Sf(i[n],t[n]))return!1;return!0}if(L(i)&&L(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Sf(i[f],t[f]))return!1}return!0}return!1}function L(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function uf(i,t,n="replace"){if(!ku(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Pc(t,f,n)}catch{return null}}catch{return null}}function Ae(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...t};function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=(e)=>e.replace(/([A-Z])/g,"_$1").toUpperCase(),T=`${r}_${$.map(A).join("_")}`,B=`${r}_${$.map((e)=>e.toUpperCase()).join("_")}`;if(n)Ai.info(`Checking environment variable ${T} for config ${i}.${$.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))w[u]=c(h,$);else{let e=On.env[T]||On.env[B];if(e!==void 0){if(n)Ai.info(`Using environment variable ${e?T:B} for config ${i}.${$.join(".")}`);if(typeof h==="number")w[u]=Number(e);else if(typeof h==="boolean")w[u]=e.toLowerCase()==="true";else if(Array.isArray(h))try{let Y=JSON.parse(e);if(Array.isArray(Y))w[u]=Y;else w[u]=e.split(",").map((m)=>m.trim())}catch{w[u]=e.split(",").map((Y)=>Y.trim())}else w[u]=e}}}return w}return c(f)}async function Te({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:c=!1,checkEnv:l=!0,arrayStrategy:y="replace"}){let w=l&&typeof f==="object"&&f!==null&&!Array.isArray(f)?Ae(i,f,c):f,u=n||On.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(c)Ai.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${u}`);let $=[i,`.${i}`].filter(Boolean),A=[`${i}.config`,`.${i}.config`].filter(Boolean),T=t?[t,`.${t}`]:[],B=t?[`${t}.config`,`.${t}.config`]:[],e=Array.from(new Set([u,Bi(u,"config"),Bi(u,".config"),r?Bi(u,r):void 0].filter(Boolean)));for(let Y of e){if(c)Ai.info(`Searching for configuration in: ${Y}`);let j=[Bi(u,"config"),Bi(u,".config")].concat(r?[Bi(u,r)]:[]).includes(Y)?[...$,...A,...T,...B]:[...A,...$,...B,...T];for(let N of j)for(let S of h){let F=Bi(Y,`${N}${S}`),X=await uf(F,w,y);if(X!==null){if(c)Ai.success(`Configuration loaded from: ${F}`);return X}}}if(i){let Y=Bi(Ec(),".config",i),m=["config",`${i}.config`];if(t)m.push(`${t}.config`);if(c)Ai.info(`Checking user config directory: ${Y}`);for(let j of m)for(let N of h){let S=Bi(Y,`${j}${N}`),F=await uf(S,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory: ${S}`);return F}}}if(i){let Y=Bi(Ec(),".config"),m=[`.${i}.config`];if(t)m.push(`.${t}.config`);if(c)Ai.info(`Checking user config directory for dotfile configs: ${Y}`);for(let j of m)for(let N of h){let S=Bi(Y,`${j}${N}`),F=await uf(S,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user config directory dotfile: ${S}`);return F}}}if(i){let Y=Ec(),m=[`.${i}.config`,`.${i}`];if(t)m.push(`.${t}.config`),m.push(`.${t}`);if(c)Ai.info(`Checking user home directory for dotfile configs: ${Y}`);for(let j of m)for(let N of h){let S=Bi(Y,`${j}${N}`),F=await uf(S,w,y);if(F!==null){if(c)Ai.success(`Configuration loaded from user home directory: ${S}`);return F}}}try{let Y=Bi(u,"package.json");if(ku(Y)){let m=await import(Y),j=m[i];if(!j&&t){if(j=m[t],j&&c)Ai.success(`Using alias "${t}" configuration from package.json`)}if(j&&typeof j==="object"&&!Array.isArray(j))try{if(c)Ai.success(`Configuration loaded from package.json: ${j===m[i]?i:t}`);return Pc(w,j,y)}catch(N){if(c)Ai.warn("Failed to merge package.json config:",N)}}}catch(Y){if(c)Ai.warn("Failed to load package.json:",Y)}if(c)Ai.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function Ee(i,t={}){let n=Cf.cwd();while(n.includes("storage"))n=yu(n,"..");let r=yu(n,i||"");if(t?.relative)return CE(Cf.cwd(),r);return r}async function ee(){try{let i=await Te({name:"clarity",alias:"logging",defaultConfig:Yf,cwd:Cf.cwd()});return{...Yf,...i||{}}}catch{return Yf}}function ni(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ye(){if(ht.env.NODE_ENV==="test"||ht.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ht<"u"){let i=ht.type;if(i==="renderer"||i==="worker")return!1;return!!(ht.versions&&(ht.versions.node||ht.versions.bun))}return!1}class bu{async format(i){let t=await Ye(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:An.pid,hostname:t(),environment:An.env.NODE_ENV||"development",platform:An.platform,version:An.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:An.env.NODE_ENV||An.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Wf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Gc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new bu,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Bf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Bf};return{...Bf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Gc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await zE(this.config.logDirectory,mu.F_OK|mu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await QE(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:lt.from(i);try{if(!tf(this.currentLogFile))await jc(this.currentLogFile,"",{mode:420});if(f=Bu(this.currentLogFile,"a",420),_E(f,w,{flag:"a"}),Yu(f),f!==void 0)Uc(f),f=void 0;if((await hn(this.currentLogFile)).size===0){if(await jc(this.currentLogFile,w,{flag:"w",mode:420}),(await hn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{Uc(f)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return $n(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return $n(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return $n(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ni())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Cc(16).toString("hex")}generateKey(){return Cc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Cc(16),r=FE("aes-256-gcm",t,n),f=lt.isBuffer(i)?i:lt.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=lt.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Uu(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(lt.from(lt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ni())return;if(!this.shouldWriteToFile())return;let i=await hn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await nf(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await hn(n).catch(()=>null))try{if(await Cu(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await rf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await jc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await hn(n).catch(()=>null))await Cu(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await nf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await rf($n(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=eu(i),r=KE(t),f=Uu();await GE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),tf(this.currentLogFile))try{let i=Bu(this.currentLogFile,"r+");Yu(i),Uc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ni()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await nf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await rf($n(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?M.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=_.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${M.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=M.underline(M.blue(r)),l=this.toAbsoluteFilePath(f);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>M.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>M.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>M.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>M.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>M.strikethrough(r)),t}supportsHyperlinks(){if(ni())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=_.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(ME(t)||t.startsWith("./")||t.startsWith("../"))t=OE(t);else return null;return tf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":fh[i],A=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:M.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:M.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let B=y.split(`
|
|
81
|
+
`);for(let e of B)if(e.trim()&&!e.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:M.gray(` ${e}`),level:i,showTimestamp:!1}))}break}}else if(!ni()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}if(!this.shouldLog(i))return;let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
|
|
82
82
|
`;if(y)h+=`${y}
|
|
83
83
|
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let n={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!ni()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(y,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,y),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!ni()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!ni()&&_.stdout.isTTY)_.stdout.write(`
|
|
84
84
|
`);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!ni()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":M.blue("◐"),tag:n,message:`${M.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)u+=` ${JSON.stringify(n)}`;if(u+=`
|
|
85
|
-
`,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":M.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ni())console.error(u.trim());if(this.shouldWriteToFile())await this.writeToFile(u)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new
|
|
85
|
+
`,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":M.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ni())console.error(u.trim());if(this.shouldWriteToFile())await this.writeToFile(u)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Wf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ni())throw Error("createReadStream is not supported in browser environments");if(!tf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return eu(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=lt.isBuffer(i)?i:lt.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=IE("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=lt.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ni()}isServerMode(){return!ni()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
|
|
86
86
|
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:M.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:M.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:M.cyan(h),showTimestamp:!1}))}else if(!ni())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let l=`${r} ${this.environment}.INFO: [BOX] ${c}
|
|
87
87
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(ni())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${M.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();_.stdin.removeListener("data",n);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,u=0;if(n=i.replace(w,(h,$)=>{if($==="%")return"%";if(u>=t.length)return h;let A=t[u++];switch($){case"s":return String(A);case"d":case"i":return Number(A).toString();case"j":case"o":return JSON.stringify(A,null,2);default:return h}}),u<t.length)n+=` ${t.slice(u).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${M.blue("◐")} `;console.error(`${u}${w} ${M.cyan(r)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
88
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=M.green("━".repeat(r)),l=M.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?M.green("✓"):M.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=_.stdout.columns||80,
|
|
89
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ni()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await nf(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=$n(this.config.logDirectory,r);if(i.before)try{if((await hn(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await rf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function
|
|
88
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=M.green("━".repeat(r)),l=M.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?M.green("✓"):M.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=_.stdout.columns||80,B=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${B}`,_.stdout.write(i.lastRenderedLine),t)_.stdout.write(`
|
|
89
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ni()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await nf(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=$n(this.config.logDirectory,r);if(i.before)try{if((await hn(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await rf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Pu(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function Zu(i){return i instanceof Wi}function Be(i){return i instanceof Xf}function me(i){if(Zu(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>i.message.toLowerCase().includes(n.toLowerCase()))}class zf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return qn.track("applyEnvironmentVariables",u,{configName:i});return u()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=ff.env[w]||(u?ff.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=ff.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof Jf)throw $;throw Rt.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Rt.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(ff.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
90
90
|
|
|
91
91
|
`;for(let r of i)n+=`${r.key}
|
|
92
92
|
`,n+=` Type: ${r.type}
|
|
@@ -98,25 +98,25 @@ ${r.join(`
|
|
|
98
98
|
`;n+=`| Variable | Type | Description | Example |
|
|
99
99
|
`,n+=`|----------|------|-------------|----------|
|
|
100
100
|
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
101
|
-
`;return n}}function eY(i,t){let n=ih("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function Zu(i,t,n={}){return vu(i,t,n,new WeakMap)}function vu(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return ou(i,t,f,r);if(!_i(t)||!_i(i))return t;return NY(i,t,n,r)}function ou(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return mY(i,t);case"smart":return UY(i,t,r);default:return t}return t}function mY(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>Mc(f,r)))n.push(r);return n}function UY(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return jY(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function jY(i,t,n){let r=[...t];for(let f of i){if(!_i(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((u)=>_i(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function NY(i,t,n,r){let f=t;if(_i(f)&&r.has(f))return r.get(f);let c={...i};if(_i(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(_i(y)&&_i(w))c[l]=vu(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=ou(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function Zc(i,t,n="replace"){return Zu(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Mc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Mc(i[n],t[n]))return!1;return!0}if(_i(i)&&_i(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Mc(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Qf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=Bn.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!cf(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new Gn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Gn(i,Error("Configuration must export a valid object"),"unknown");let B={config:Zc(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Bn.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Nt.configLoad(i,u):Nt.configLoad(i,Error(String(u)))}};if(l)return qn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(Nc(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return bu(async()=>{return cf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!cf(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=Nc(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=Nc(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!cf(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class vc{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await qn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!GE(t))throw new Hn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Hn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(r.push({path:n,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(r.push({path:n?`${n}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,required:!c,type:this.mapTypeScriptType(l)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ch},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class oc{fileLoader=new Qf;envProcessor=new zf;validator=new vc;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)Li.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw Li.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||zt.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let C=await this.loadHomeConfiguration(r,f,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(ei($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Nt.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Mn(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)Li.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)Li.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Mn(i,n,f):n,y=[ei(ln(),".config",i),ei(ln(),".config"),ln()];for(let w of y){if(f)Li.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)Li.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Mn(i,r,c):r;try{let w=ei(n,"package.json");if(!zc(w))return null;let u=await import(w),h=u[i],$=i;if(!h&&t)h=u[t],$=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)Li.success(`Configuration loaded from package.json: ${$}`);return{config:Zc(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)Li.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Mn(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Nt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Bn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Bn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,ei(i,"config"),ei(i,".config"),t?ei(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(ei(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[ei(ln(),".config",i),ei(ln(),".config"),ln()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Ju(i){let n=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return n||r}async function RY(i){return At.loadConfig({...i,__strictErrorHandling:!0})}async function pu(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await At.loadConfig(i);else r=await At.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)Li.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let y=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await At.applyEnvironmentVariables(y.name||"",t,!0,y.verbose||!1))?.config??t;return t}}async function XY(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await At.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Ju(n)))return(await At.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await At.loadConfig({...i,cwd:i.cwd||zt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Ju(t)))return(await At.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function WY(i,t,n="replace"){let r=new Qf;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Mn(i,t,n=!1){let r=new zf,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=zt.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}function SY(i){let t=ei(zt.cwd(),i.configDir),n=ei(zt.cwd(),i.generatedDir),r=ei(n,"config-types.ts");if(!zc(cu(r)))EE(cu(r),{recursive:!0,mode:511});let f=zc(t)?YE(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${tB}
|
|
101
|
+
`;return n}}function Ce(i,t){let n=th("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function vu(i,t,n={}){return ou(i,t,n,new WeakMap)}function ou(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return pu(i,t,f,r);if(!_i(t)||!_i(i))return t;return ae(i,t,n,r)}function pu(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return Ue(i,t);case"smart":return je(i,t,r);default:return t}return t}function Ue(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>Mc(f,r)))n.push(r);return n}function je(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return Re(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function Re(i,t,n){let r=[...t];for(let f of i){if(!_i(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((u)=>_i(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function ae(i,t,n,r){let f=t;if(_i(f)&&r.has(f))return r.get(f);let c={...i};if(_i(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(_i(y)&&_i(w))c[l]=ou(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=pu(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function Zc(i,t,n="replace"){return vu(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Mc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Mc(i[n],t[n]))return!1;return!0}if(_i(i)&&_i(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Mc(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Qf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=Yn.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!cf(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new Gn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Gn(i,Error("Configuration must export a valid object"),"unknown");let Y={config:Zc(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Yn.setWithFileCheck("file",Y,i,c);return Y}catch(u){throw u instanceof Error?Rt.configLoad(i,u):Rt.configLoad(i,Error(String(u)))}};if(l)return qn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(Rc(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return Pu(async()=>{return cf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!cf(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=Rc(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=Rc(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!cf(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class vc{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await qn.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!HE(t))throw new Hn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Hn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(r.push({path:n,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(r.push({path:n?`${n}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,required:!c,type:this.mapTypeScriptType(l)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:lh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class oc{fileLoader=new Qf;envProcessor=new zf;validator=new vc;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)gi.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){let w=Date.now()-t;throw gi.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||zt.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let B=await this.loadHomeConfiguration(r,f,y,u,h,w);if(B)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(B,A,w,r,h);let e=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(e)return A.push(mi($,"package.json")),this.finalizeResult(e,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Rt.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Mn(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)gi.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)gi.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Mn(i,n,f):n,y=[mi(ln(),".config",i),mi(ln(),".config"),ln()];for(let w of y){if(f)gi.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)gi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Mn(i,r,c):r;try{let w=mi(n,"package.json");if(!zc(w))return null;let u=await import(w),h=u[i],$=i;if(!h&&t)h=u[t],$=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)gi.success(`Configuration loaded from package.json: ${$}`);return{config:Zc(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)gi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Mn(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Rt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Yn.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Yn.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,mi(i,"config"),mi(i,".config"),t?mi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(mi(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[mi(ln(),".config",i),mi(ln(),".config"),ln()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Fu(i){let n=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return n||r}async function Ne(i){return At.loadConfig({...i,__strictErrorHandling:!0})}async function ih(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await At.loadConfig(i);else r=await At.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",c=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||c.includes("config"))&&i.verbose)gi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let y=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await At.applyEnvironmentVariables(y.name||"",t,!0,y.verbose||!1))?.config??t;return t}}async function Se(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await At.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Fu(n)))return(await At.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await At.loadConfig({...i,cwd:i.cwd||zt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Fu(t)))return(await At.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function We(i,t,n="replace"){let r=new Qf;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Mn(i,t,n=!1){let r=new zf,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((e)=>e.toUpperCase()).join("")}`,`${f}_${$.map((e)=>e.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,B;for(let e of A)if(T=zt.env[e],T!==void 0){B=e;break}if(T!==void 0&&B)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let e=Number(T);if(!Number.isNaN(e))w[u]=e}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((e)=>e.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}function Xe(i){let t=mi(zt.cwd(),i.configDir),n=mi(zt.cwd(),i.generatedDir),r=mi(n,"config-types.ts");if(!zc(lu(r)))eE(lu(r),{recursive:!0,mode:511});let f=zc(t)?YE(t).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],c=`// Generated by bunfig v${nY}
|
|
102
102
|
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
103
|
-
`;BE(r,c,{mode:438})}function
|
|
104
|
-
${f.map((u)=>{let h=
|
|
103
|
+
`;BE(r,c,{mode:438})}function Je(i){let t=null,n=null,r=()=>{if(!n)n=ih(i).then((c)=>{return t=c,c},(c)=>{let l="defaultConfig"in i?i.defaultConfig:{};if(t=l,"verbose"in i&&i.verbose)gi.warn("Config loading failed, using defaults:",[c instanceof Error?c:Error(String(c))]);return l});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get(c,l){if(t)return t[l];let y=f[l];return r(),y},has(c,l){return l in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(c,l){return Object.getOwnPropertyDescriptor(t||f,l)},set(c,l,y){if(!t)t={...f};return t[l]=y,!0}})}function Fe(i){let t=ju(gE.cwd(),i?.configDir||"./config");function n(){if(!qE(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),c=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=sE(t).filter((w)=>f.has(ac(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),y=new Map;for(let{base:w,file:u}of l){let h=ac(u).toLowerCase(),$=y.get(w);if(!$){y.set(w,u);continue}let A=ac($).toLowerCase();if(c.indexOf(h)<c.indexOf(A))y.set(w,u)}return Array.from(y.entries()).map(([w,u])=>({base:w,file:u})).sort((w,u)=>w.base.localeCompare(u.base))}function r(){let f=n(),c=f.map((u)=>u.base),l=c.length?c.map((u)=>`'${u}'`).join(" | "):"string",y=f.length?`{
|
|
104
|
+
${f.map((u)=>{let h=ju(t,u.file).replace(/\\/g,"/");return` '${u.base}': typeof import('${h}').default`}).join(`,
|
|
105
105
|
`)}
|
|
106
106
|
}`:"Record<string, any>";return`export type ConfigNames = ${l}
|
|
107
107
|
export type ConfigByName = ${y}
|
|
108
108
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
109
109
|
export type ConfigOf = Config
|
|
110
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var ih,Bn,qn,th,FY,IY,Fu,Ef,Oc,$i,k,KY,Iu,_Y,Ku,zY,QY,ac,MY,_u,zu,Jc,OY,GY,HY,qY,Yf,nh,gY,Ai,LY,sY,Qu,Bf,Gc,ri,M,xY,Mu,kY,Ou,VY,dY,Fc,DY,Gu,Hu,bY,Ic,PY,ZY,vY,oY,pY,Cf,rh,iB,tB="0.15.6",Si,af,Gn,Hc,qc,Jf,gc,Lc,Hn,sc,xc,Nt,fh,ch,Li,At,lh,yh,nB=nY(async()=>{ih=import.meta.require,Bn=new dc,qn=new Dc,th={createKey:rY,isEquivalent:fY,estimateMemoryUsage:cY},FY=jf(Qc.cwd(),"config"),IY=jf(Qc.cwd(),"src/generated"),Fu=Uf.env.CLARITY_LOG_DIR||mE(wY(),"logs"),Ef={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Fu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Oc=await uY(),$i={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},k=$i,KY=$i.red,Iu=$i.green,_Y=$i.yellow,Ku=$i.blue,zY=$i.magenta,QY=$i.cyan,ac=$i.white,MY=$i.gray,_u=$i.bgRed,zu=$i.bgYellow,Jc=$i.bold,OY=$i.dim,GY=$i.italic,HY=$i.underline,qY=$i.reset,Yf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nh={debug:"\uD83D\uDD0D",info:Ku("ℹ"),success:Iu("✓"),warning:zu(ac(Jc(" WARN "))),error:_u(ac(Jc(" ERROR ")))},gY=new Xf("stacks"),Ai=new Xf("bunfig",{showTags:!0}),LY=Ci(On.cwd(),"config"),sY=Ci(On.cwd(),"src/generated"),Qu=mf.env.CLARITY_LOG_DIR||CE(TY(),"logs"),Bf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Qu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Gc=await EY(),ri={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},M=ri,xY=ri.red,Mu=ri.green,kY=ri.yellow,Ou=ri.blue,VY=ri.magenta,dY=ri.cyan,Fc=ri.white,DY=ri.gray,Gu=ri.bgRed,Hu=ri.bgYellow,bY=ri.bgGray,Ic=ri.bold,PY=ri.dim,ZY=ri.italic,vY=ri.underline,oY=ri.strikethrough,pY=ri.reset,Cf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rh={debug:"\uD83D\uDD0D",info:Ou("ℹ"),success:Mu("✓"),warning:Hu(Fc(Ic(" WARN "))),error:Gu(Fc(Ic(" ERROR ")))},iB=new Sf("stacks"),Si=class extends Error{timestamp;context;constructor(t,n={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},af=class extends Si{code="CONFIG_NOT_FOUND";constructor(t,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:r,searchPaths:n,searchPathCount:n.length})}},Gn=class extends Si{code="CONFIG_LOAD_ERROR";constructor(t,n,r){super(`Failed to load configuration from "${t}": ${n.message}`,{configPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Hc=class extends Si{code="CONFIG_VALIDATION_ERROR";constructor(t,n,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:n,errorCount:n.length})}},qc=class extends Si{code="CONFIG_MERGE_ERROR";constructor(t,n,r,f){super(`Failed to merge configuration from "${t}" with "${n}": ${r.message}`,{sourcePath:t,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},Jf=class extends Si{code="ENV_VAR_ERROR";constructor(t,n,r,f){super(`Failed to parse environment variable "${t}" with value "${n}" as ${r}`,{envKey:t,envValue:n,expectedType:r,configName:f})}},gc=class extends Si{code="FILE_SYSTEM_ERROR";constructor(t,n,r){super(`File system ${t} failed for "${n}": ${r.message}`,{operation:t,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Lc=class extends Si{code="TYPE_GENERATION_ERROR";constructor(t,n,r){super(`Failed to generate types from "${t}" to "${n}": ${r.message}`,{configDir:t,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Hn=class extends Si{code="SCHEMA_VALIDATION_ERROR";constructor(t,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:n,errorCount:n.length})}},sc=class extends Si{code="BROWSER_CONFIG_ERROR";constructor(t,n,r,f){super(`Failed to fetch configuration from "${t}": ${n} ${r}`,{endpoint:t,status:n,statusText:r,configName:f})}},xc=class extends Si{code="PLUGIN_ERROR";constructor(t,n,r){super(`Plugin "${t}" failed during ${n}: ${r.message}`,{pluginName:t,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Nt={configNotFound(i,t,n){return new af(i,t,n)},configLoad(i,t,n){return new Gn(i,t,n)},configValidation(i,t,n){return new Hc(i,t,n)},configMerge(i,t,n,r){return new qc(i,t,n,r)},envVar(i,t,n,r){return new Jf(i,t,n,r)},fileSystem(i,t,n){return new gc(i,t,n)},typeGeneration(i,t,n){return new Lc(i,t,n)},schemaValidation(i,t,n){return new Hn(i,t,n)},browserConfig(i,t,n,r){return new sc(i,t,n,r)},plugin(i,t,n){return new xc(i,t,n)}},fh={replace:"replace",concat:"concat",smart:"smart"},ch=/^https?:\/\//,Li=new Sf("bunfig",{showTags:!0}),At=new oc,lh=ei(zt.cwd(),"config"),yh=ei(zt.cwd(),"src/generated")});function rB(i,t={}){let n=Nf.cwd();while(n.includes("storage"))n=ju(n,"..");let r=ju(n,i||"");if(t?.relative)return sE(Nf.cwd(),r);return r}var fB=Nf.env.CLARITY_LOG_DIR||LE(rB(),"logs"),wh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ff={...wh},LN=(async()=>{try{let{loadConfig:i}=await nB().then(()=>Vu),t=await i({name:"clarity",alias:"logging",defaultConfig:wh,cwd:Nf.cwd()});if(t)Object.assign(Ff,t)}catch{}return Ff})();function fi(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cB(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let i=$t.type;if(i==="renderer"||i==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class uh{async format(i){let t=await cB(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Yn.pid,hostname:t(),environment:Yn.env.NODE_ENV||"development",platform:Yn.platform,version:Yn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Yn.env.NODE_ENV||Yn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var li={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},G=li,sN=li.red,lB=li.green,xN=li.yellow,yB=li.blue,kN=li.magenta,VN=li.cyan,qu=li.white,dN=li.gray,wB=li.bgRed,uB=li.bgYellow,DN=li.bgGray,gu=li.bold,bN=li.dim,PN=li.italic,ZN=li.underline,vN=li.strikethrough,oN=li.reset,Kc={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},hB={debug:"\uD83D\uDD0D",info:yB("ℹ"),success:lB("✓"),warning:uB(qu(gu(" WARN "))),error:wB(qu(gu(" ERROR ")))};class Mf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Ff},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new uh,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Kc,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Kc};return{...Kc,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Ff.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!fi()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await DE(this.config.logDirectory,Wu.F_OK|Wu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await bE(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:yt.from(i);try{if(!lf(this.currentLogFile))await Sc(this.currentLogFile,"",{mode:420});if(f=Xu(this.currentLogFile,"a",420),dE(f,w,{flag:"a"}),Ru(f),f!==void 0)Wc(f),f=void 0;if((await Tn(this.currentLogFile)).size===0){if(await Sc(this.currentLogFile,w,{flag:"w",mode:420}),(await Tn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{Wc(f)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return En(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return En(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return En(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(fi())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Xc(16).toString("hex")}generateKey(){return Xc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Xc(16),r=xE("aes-256-gcm",t,n),f=yt.isBuffer(i)?i:yt.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=yt.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=au(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(yt.from(yt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(fi())return;if(!this.shouldWriteToFile())return;let i=await Tn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await yf(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Tn(n).catch(()=>null))try{if(await Su(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await wf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await Sc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Tn(n).catch(()=>null))await Su(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await yf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await wf(En(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=Nu(i),r=VE(t),f=au();await vE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),lf(this.currentLogFile))try{let i=Xu(this.currentLogFile,"r+");Ru(i),Wc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!fi()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await yf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await wf(En(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||fi())return!1;let i=typeof z.env.NO_COLOR<"u",t=z.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof z.stderr<"u"&&z.stderr.isTTY||typeof z.stdout<"u"&&z.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=z.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${G.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=G.underline(G.blue(r)),l=this.toAbsoluteFilePath(f);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>G.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>G.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>G.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>G.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>G.strikethrough(r)),t}supportsHyperlinks(){if(fi())return!1;let i=z.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=z.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(PE(t)||t.startsWith("./")||t.startsWith("../"))t=ZE(t);else return null;return lf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":hB[i],A=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:G.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:G.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let C=y.split(`
|
|
111
|
-
`);for(let
|
|
110
|
+
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(c)=>{return{path:c.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var th,Yn,qn,nh,Ie,Ke,Iu,Ef,Oc,$i,k,_e,Ku,ze,_u,Qe,Me,Xc,Oe,zu,Qu,Jc,Ge,He,qe,se,ef,rh,ge,Ai,Le,xe,Mu,Yf,Gc,ri,M,ke,Ou,Ve,Gu,de,De,Fc,be,Hu,qu,Pe,Ic,Ze,ve,oe,pe,iY,Bf,fh,tY,nY="0.15.6",Wi,Xf,Gn,Hc,qc,Jf,sc,gc,Hn,Lc,xc,Rt,ch,lh,gi,At,yh,wh,rY=re(async()=>{th=import.meta.require,Yn=new dc,qn=new Dc,nh={createKey:fe,isEquivalent:ce,estimateMemoryUsage:le},Ie=jf(Qc.cwd(),"config"),Ke=jf(Qc.cwd(),"src/generated"),Iu=Uf.env.CLARITY_LOG_DIR||UE(ue(),"logs"),Ef={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Iu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Oc=await he(),$i={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},k=$i,_e=$i.red,Ku=$i.green,ze=$i.yellow,_u=$i.blue,Qe=$i.magenta,Me=$i.cyan,Xc=$i.white,Oe=$i.gray,zu=$i.bgRed,Qu=$i.bgYellow,Jc=$i.bold,Ge=$i.dim,He=$i.italic,qe=$i.underline,se=$i.reset,ef={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},rh={debug:"\uD83D\uDD0D",info:_u("ℹ"),success:Ku("✓"),warning:Qu(Xc(Jc(" WARN "))),error:zu(Xc(Jc(" ERROR ")))},ge=new Nf("stacks"),Ai=new Nf("bunfig",{showTags:!0}),Le=Bi(On.cwd(),"config"),xe=Bi(On.cwd(),"src/generated"),Mu=Cf.env.CLARITY_LOG_DIR||mE(Ee(),"logs"),Yf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Gc=await ee(),ri={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},M=ri,ke=ri.red,Ou=ri.green,Ve=ri.yellow,Gu=ri.blue,de=ri.magenta,De=ri.cyan,Fc=ri.white,be=ri.gray,Hu=ri.bgRed,qu=ri.bgYellow,Pe=ri.bgGray,Ic=ri.bold,Ze=ri.dim,ve=ri.italic,oe=ri.underline,pe=ri.strikethrough,iY=ri.reset,Bf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fh={debug:"\uD83D\uDD0D",info:Gu("ℹ"),success:Ou("✓"),warning:qu(Fc(Ic(" WARN "))),error:Hu(Fc(Ic(" ERROR ")))},tY=new Wf("stacks"),Wi=class extends Error{timestamp;context;constructor(t,n={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Xf=class extends Wi{code="CONFIG_NOT_FOUND";constructor(t,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:r,searchPaths:n,searchPathCount:n.length})}},Gn=class extends Wi{code="CONFIG_LOAD_ERROR";constructor(t,n,r){super(`Failed to load configuration from "${t}": ${n.message}`,{configPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Hc=class extends Wi{code="CONFIG_VALIDATION_ERROR";constructor(t,n,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:n,errorCount:n.length})}},qc=class extends Wi{code="CONFIG_MERGE_ERROR";constructor(t,n,r,f){super(`Failed to merge configuration from "${t}" with "${n}": ${r.message}`,{sourcePath:t,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},Jf=class extends Wi{code="ENV_VAR_ERROR";constructor(t,n,r,f){super(`Failed to parse environment variable "${t}" with value "${n}" as ${r}`,{envKey:t,envValue:n,expectedType:r,configName:f})}},sc=class extends Wi{code="FILE_SYSTEM_ERROR";constructor(t,n,r){super(`File system ${t} failed for "${n}": ${r.message}`,{operation:t,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},gc=class extends Wi{code="TYPE_GENERATION_ERROR";constructor(t,n,r){super(`Failed to generate types from "${t}" to "${n}": ${r.message}`,{configDir:t,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Hn=class extends Wi{code="SCHEMA_VALIDATION_ERROR";constructor(t,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Lc=class extends Wi{code="BROWSER_CONFIG_ERROR";constructor(t,n,r,f){super(`Failed to fetch configuration from "${t}": ${n} ${r}`,{endpoint:t,status:n,statusText:r,configName:f})}},xc=class extends Wi{code="PLUGIN_ERROR";constructor(t,n,r){super(`Plugin "${t}" failed during ${n}: ${r.message}`,{pluginName:t,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Rt={configNotFound(i,t,n){return new Xf(i,t,n)},configLoad(i,t,n){return new Gn(i,t,n)},configValidation(i,t,n){return new Hc(i,t,n)},configMerge(i,t,n,r){return new qc(i,t,n,r)},envVar(i,t,n,r){return new Jf(i,t,n,r)},fileSystem(i,t,n){return new sc(i,t,n)},typeGeneration(i,t,n){return new gc(i,t,n)},schemaValidation(i,t,n){return new Hn(i,t,n)},browserConfig(i,t,n,r){return new Lc(i,t,n,r)},plugin(i,t,n){return new xc(i,t,n)}},ch={replace:"replace",concat:"concat",smart:"smart"},lh=/^https?:\/\//,gi=new Wf("bunfig",{showTags:!0}),At=new oc,yh=mi(zt.cwd(),"config"),wh=mi(zt.cwd(),"src/generated")});function fY(i,t={}){let n=Rf.cwd();while(n.includes("storage"))n=Ru(n,"..");let r=Ru(n,i||"");if(t?.relative)return xE(Rf.cwd(),r);return r}var cY=Rf.env.CLARITY_LOG_DIR||LE(fY(),"logs"),uh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:cY,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ff={...uh},LR=(async()=>{try{let{loadConfig:i}=await rY().then(()=>du),t=await i({name:"clarity",alias:"logging",defaultConfig:uh,cwd:Rf.cwd()});if(t)Object.assign(Ff,t)}catch{}return Ff})();function fi(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lY(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let i=$t.type;if(i==="renderer"||i==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class hh{async format(i){let t=await lY(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:en.pid,hostname:t(),environment:en.env.NODE_ENV||"development",platform:en.platform,version:en.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:en.env.NODE_ENV||en.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var li={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},G=li,xR=li.red,yY=li.green,kR=li.yellow,wY=li.blue,VR=li.magenta,dR=li.cyan,su=li.white,DR=li.gray,uY=li.bgRed,hY=li.bgYellow,bR=li.bgGray,gu=li.bold,PR=li.dim,ZR=li.italic,vR=li.underline,oR=li.strikethrough,pR=li.reset,Kc={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},$Y={debug:"\uD83D\uDD0D",info:wY("ℹ"),success:yY("✓"),warning:hY(su(gu(" WARN "))),error:uY(su(gu(" ERROR ")))};class Mf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Ff},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new hh,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),c=this.generateKey();this.currentKeyId=f,this.keys.set(f,c),this.encryptionKeys.set(f,{key:c,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Kc,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Kc};return{...Kc,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Ff.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!fi()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,c=0,l=3,y=1000;while(c<l)try{try{try{await bE(this.config.logDirectory,Wu.F_OK|Wu.W_OK)}catch(u){if(u instanceof Error&&"code"in u)if(u.code==="ENOENT")await PE(this.config.logDirectory,{recursive:!0,mode:493});else if(u.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw u;else throw u}}catch(u){throw console.error("Debug: [writeToFile] Failed to create log directory:",u),u}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:yt.from(i);try{if(!lf(this.currentLogFile))await Wc(this.currentLogFile,"",{mode:420});if(f=Su(this.currentLogFile,"a",420),DE(f,w,{flag:"a"}),Nu(f),f!==void 0)Sc(f),f=void 0;if((await Tn(this.currentLogFile)).size===0){if(await Wc(this.currentLogFile,w,{flag:"w",mode:420}),(await Tn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(u){let h=u;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(c<l-1){let $=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${c+1}/${l}:`,$);let A=y*2**c;await new Promise((T)=>setTimeout(T,A)),c++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{Sc(f)}catch(u){console.error("Debug: [writeToFile] Error closing file descriptor:",u)}}}catch(w){if(c===l-1){let h=w,$=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),w}c++;let u=y*2**(c-1);await new Promise((h)=>setTimeout(h,u))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return En(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return En(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return En(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(fi())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,y],[,w])=>w.createdAt.getTime()-y.createdAt.getTime()),c=typeof t.maxKeys==="number"?t.maxKeys:1,l=Math.max(1,c);if(f.length>l)for(let[y]of f.slice(l))this.encryptionKeys.delete(y),this.keys.delete(y)}generateKeyId(){return Nc(16).toString("hex")}generateKey(){return Nc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Nc(16),r=kE("aes-256-gcm",t,n),f=yt.isBuffer(i)?i:yt.from(i,"utf8"),c=r.update(f),l=r.final(),y=c.length+l.length,w=r.getAuthTag(),u=yt.allocUnsafe(16+y+16);return n.copy(u,0),c.copy(u,16),l.copy(u,16+c.length),w.copy(u,16+y),{encrypted:u,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Ju(),f=[];r.on("data",(c)=>f.push(c)),r.on("end",()=>t(yt.from(yt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(fi())return;if(!this.shouldWriteToFile())return;let i=await Tn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await yf(this.config.logDirectory),c=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,u)=>{let h=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(u.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),l=c.length>0?Number.parseInt(c[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,y=`${n}.${l}`;if(await Tn(n).catch(()=>null))try{if(await Xu(n,y),t.compress)try{let w=`${y}.gz`;await this.compressLogFile(y,w),await wf(y)}catch(w){console.error("Error compressing rotated file:",w)}if(c.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await Wc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),c=n.replace(/\.log$/,`-${f}.log`);if(await Tn(n).catch(()=>null))await Xu(n,c)}if(this.currentLogFile=r,t.maxFiles){let c=(await yf(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,y)=>y.localeCompare(l));for(let l of c.slice(t.maxFiles))await wf(En(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=au(i),r=dE(t),f=Ju();await oE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),lf(this.currentLogFile))try{let i=Su(this.currentLogFile,"r+");Nu(i),Sc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!fi()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await yf(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await wf(En(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||fi())return!1;let i=typeof z.env.NO_COLOR<"u",t=z.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof z.stderr<"u"&&z.stderr.isTTY||typeof z.stdout<"u"&&z.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:c,showTimestamp:l=!0}=i,y=(T)=>T.replace(this.ANSI_PATTERN,"");if(!this.fancy){let T=[];if(l)T.push(t);if(c==="warning")T.push("WARN");else if(c==="error")T.push("ERROR");else if(n)T.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)T.push(r.replace(/[[\]]/g,""));return T.push(f),T.join(" ")}let w=z.stdout.columns||120,u="";if(c==="warning"||c==="error")u=`${n} ${f}`;else if(c==="info"||c==="success")u=`${n} ${r} ${f}`;else u=`${n} ${r} ${G.cyan(f)}`;if(!l)return u.trim();let h=y(u).trim().length,$=y(t).length,A=Math.max(1,w-2-h-$);return`${u.trim()}${" ".repeat(A)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(c,l)=>{let y=Number.parseInt(l,10);return y<t[0].length?String(t[0][y]):c});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(c,l)=>{if(l==="%")return"%";if(r>=t.length)return c;let y=t[r++];switch(l){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return c}});if(r<t.length)f+=` ${t.slice(r).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let c=G.underline(G.blue(r)),l=this.toAbsoluteFilePath(f);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let y=`file://${encodeURI(l)}`,w="\x1B]8;;",u="\x1B\\";return`\x1B]8;;${y}\x1B\\${c}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${c}\x1B]8;;\x1B\\`;return c}),t=t.replace(/`([^`]+)`/g,(n,r)=>G.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>G.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>G.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>G.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>G.strikethrough(r)),t}supportsHyperlinks(){if(fi())return!1;let i=z.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=z.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(ZE(t)||t.startsWith("./")||t.startsWith("../"))t=vE(t);else return null;return lf(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),c=this.formatFileTimestamp(r),l,y;if(t instanceof Error)l=t.message,y=t.stack;else l=this.formatMessage(t,n);let{consoleText:w,fileText:u}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":$Y[i],A=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",T;switch(i){case"debug":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:G.gray(w),level:i}),console.error(T);break;case"info":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"success":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:G.green(w),level:i}),console.error(T);break;case"warning":T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.warn(T);break;case"error":if(T=this.formatConsoleMessage({timestamp:f,icon:$,tag:A,message:w,level:i}),console.error(T),y){let B=y.split(`
|
|
111
|
+
`);for(let e of B)if(e.trim()&&!e.includes(l))console.error(this.formatConsoleMessage({timestamp:f,message:G.gray(` ${e}`),level:i,showTimestamp:!1}))}break}}else if(!fi()){if(console.error(`${c} ${this.environment}.${i.toUpperCase()}: ${l}`),y)console.error(y)}let h=`${c} ${this.environment}.${i.toUpperCase()}: ${u}
|
|
112
112
|
`;if(y)h+=`${y}
|
|
113
113
|
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let n={update:(y,w)=>{},finish:(y)=>{},interrupt:(y,w)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!fi()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(y,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,y),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!fi()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(y)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,y)},interrupt:(y,w="info")=>{if(!fi()&&z.stdout.isTTY)z.stdout.write(`
|
|
114
114
|
`);if(this[w==="warning"?"warn":w](y),this.activeProgressBar&&this.shouldStyleConsole()&&!fi()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":G.blue("◐"),tag:n,message:`${G.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),c=`${i} completed in ${f}ms`,l=new Date,y=this.formatConsoleTimestamp(l),u=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${c}`;if(n)u+=` ${JSON.stringify(n)}`;if(u+=`
|
|
115
|
-
`,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":G.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!fi())console.error(u.trim());if(this.shouldWriteToFile())await this.writeToFile(u)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Mf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(fi())throw Error("createReadStream is not supported in browser environments");if(!lf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
115
|
+
`,u=u.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:y,icon:this.options.showIcons===!1?"":G.green("✓"),tag:h,message:`${c}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!fi())console.error(u.trim());if(this.shouldWriteToFile())await this.writeToFile(u)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Mf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(fi())throw Error("createReadStream is not supported in browser environments");if(!lf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return au(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=yt.isBuffer(i)?i:yt.from(i,"base64"),f=r.subarray(0,16),c=r.subarray(r.length-16),l=r.subarray(16,r.length-16),y=VE("aes-256-gcm",n,f);y.setAuthTag(c);let w=y.update(l),u=y.final(),h=w.length+u.length,$=yt.allocUnsafe(h);return w.copy($,0),u.copy($,w.length),$.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return fi()}isServerMode(){return!fi()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:c}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let y=f.split(`
|
|
116
116
|
`),w=Math.max(...y.map((A)=>A.length))+2,u=`┌${"─".repeat(w)}┐`,h=`└${"─".repeat(w)}┘`,$=y.map((A)=>{return this.formatConsoleMessage({timestamp:n,message:G.cyan(A),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:G.cyan(u),showTimestamp:!1})),$.forEach((A)=>console.error(A)),console.error(this.formatConsoleMessage({timestamp:n,message:G.cyan(h),showTimestamp:!1}))}else if(!fi())console.error(`${r} ${this.environment}.INFO: [BOX] ${c}`);let l=`${r} ${this.environment}.INFO: [BOX] ${c}
|
|
117
117
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(i){if(fi())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${G.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();z.stdin.removeListener("data",n);try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!1)}catch{}z.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!0)}catch{}z.stdin.resume(),z.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,u=0;if(n=i.replace(w,(h,$)=>{if($==="%")return"%";if(u>=t.length)return h;let A=t[u++];switch($){case"s":return String(A);case"d":case"i":return Number(A).toString();case"j":case"o":return JSON.stringify(A,null,2);default:return h}}),u<t.length)n+=` ${t.slice(u).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${u}${w} ${G.cyan(r)}`)}let y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
118
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!z.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=G.green("━".repeat(r)),l=G.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?G.green("✓"):G.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=z.stdout.columns||80,
|
|
119
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||fi()||!z.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(fi()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await yf(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=En(this.config.logDirectory,r);if(i.before)try{if((await Tn(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await wf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var
|
|
118
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(y)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!z.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,c=G.green("━".repeat(r)),l=G.gray("━".repeat(f)),y=`[${c}${l}]`,w=`${n}%`.padStart(4),u=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||n===100?G.green("✓"):G.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",A=`\r${h}${$} ${y} ${w}${u}`,T=z.stdout.columns||80,B=" ".repeat(Math.max(0,T-A.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${A}${B}`,z.stdout.write(i.lastRenderedLine),t)z.stdout.write(`
|
|
119
|
+
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||fi()||!z.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(fi()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await yf(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let c=En(this.config.logDirectory,r);if(i.before)try{if((await Tn(c)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${c}:`,l);continue}n.push(c)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await wf(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var ia=new Mf("stacks");class Li extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class $h extends Li{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((c)=>`"${c}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class If extends Li{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class Ah extends Li{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Th extends Li{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class pc extends Li{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class Eh extends Li{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class eh extends Li{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Kf extends Li{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Yh extends Li{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class Bh extends Li{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var Bn={configNotFound(i,t,n){return new $h(i,t,n)},configLoad(i,t,n){return new If(i,t,n)},configValidation(i,t,n){return new Ah(i,t,n)},configMerge(i,t,n,r){return new Th(i,t,n,r)},envVar(i,t,n,r){return new pc(i,t,n,r)},fileSystem(i,t,n){return new Eh(i,t,n)},typeGeneration(i,t,n){return new eh(i,t,n)},schemaValidation(i,t,n){return new Kf(i,t,n)},browserConfig(i,t,n,r){return new Yh(i,t,n,r)},plugin(i,t,n){return new Bh(i,t,n)}};async function AY(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:c}=t,l=Error("Unknown error occurred");for(let y=0;y<=n;y++)try{return await i()}catch(w){if(l=w instanceof Error?w:Error(String(w)),y===n||!f(l))break;if(r>0)await new Promise((u)=>setTimeout(u,r))}if(c!==void 0)return c;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class il{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:c=!0,customParsers:l={},verbose:y=!1,trackPerformance:w=!0}=n,u=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=r||this.generateEnvPrefix(i),$={...t};return this.processObject($,[],h,{useCamelCase:f,useBackwardCompatibility:c,customParsers:l,verbose:y,configName:i}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Vc.track("applyEnvironmentVariables",u,{configName:i});return u()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=l.map((h)=>this.formatEnvKey(h,r.useCamelCase)),w=`${n}_${y.join("_")}`,u=r.useBackwardCompatibility?`${n}_${l.map((h)=>h.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.processObject(c,l,n,r);else{let h=hf.env[w]||(u?hf.env[u]:void 0);if(h!==void 0){if(r.verbose){let $=hf.env[w]?w:u}try{i[f]=this.parseEnvironmentValue(h,typeof c,w,r.customParsers,r.configName)}catch($){if($ instanceof pc)throw $;throw Bn.envVar(w,h,typeof c,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[c,l]of Object.entries(r))try{return l(i)}catch{continue}for(let c of this.defaultParsers)if(c.canParse(i,t))try{return c.parse(i)}catch{throw Bn.envVar(n,i,`${t} (via ${c.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(hf.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,c=r||this.generateEnvPrefix(i),l=[];switch(this.extractEnvVarInfo(t,[],c,l),f){case"markdown":return this.formatAsMarkdown(l,i);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,c]of Object.entries(i)){let l=[...t,f],y=`${n}_${l.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof c==="object"&&c!==null&&!Array.isArray(c))this.extractEnvVarInfo(c,l,n,r);else r.push({key:y,type:Array.isArray(c)?"array":typeof c,description:`Configuration for ${l.join(".")}`,example:this.generateExample(c)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
120
120
|
|
|
121
121
|
`;for(let r of i)n+=`${r.key}
|
|
122
122
|
`,n+=` Type: ${r.type}
|
|
@@ -128,10 +128,10 @@ export type ConfigOf = Config
|
|
|
128
128
|
`;n+=`| Variable | Type | Description | Example |
|
|
129
129
|
`,n+=`|----------|------|-------------|----------|
|
|
130
130
|
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
131
|
-
`;return n}}function AB(i,t,n={}){return Ch(i,t,n,new WeakMap)}function Ch(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return eh(i,t,f,r);if(!zi(t)||!zi(i))return t;return BB(i,t,n,r)}function eh(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return TB(i,t);case"smart":return EB(i,t,r);default:return t}return t}function TB(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>kc(f,r)))n.push(r);return n}function EB(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(zi(t[0])&&zi(i[0]))return YB(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function YB(i,t,n){let r=[...t];for(let f of i){if(!zi(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((u)=>zi(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function BB(i,t,n,r){let f=t;if(zi(f)&&r.has(f))return r.get(f);let c={...i};if(zi(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(zi(y)&&zi(w))c[l]=Ch(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=eh(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function mh(i,t,n="replace"){return AB(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function kc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!kc(i[n],t[n]))return!1;return!0}if(zi(i)&&zi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!kc(i[f],t[f]))return!1}return!0}return!1}function zi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Uh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=ef.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!$f(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new If(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new If(i,Error("Configuration must export a valid object"),"unknown");let B={config:mh(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)ef.setWithFileCheck("file",B,i,c);return B}catch(u){throw u instanceof Error?Cn.configLoad(i,u):Cn.configLoad(i,Error(String(u)))}};if(l)return Vc.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(_c(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of r){if(!c)continue;if(n.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)n.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return n.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return $B(async()=>{return $f(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!$f(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=_c(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=_c(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!$f(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var eB=/^https?:\/\//;class jh{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await Vc.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!CB(t))throw new Kf(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Kf(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(r.push({path:n,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(r.push({path:n?`${n}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,required:!c,type:this.mapTypeScriptType(l)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:eB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var wt=new Mf("bunfig",{showTags:!0});function mB(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class Nh{fileLoader=new Uh;envProcessor=new il;validator=new jh;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)wt.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){if(y instanceof Error&&y.name==="ConfigNotFoundError")throw y;let w=Date.now()-t;throw wt.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||_f.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let C=await this.loadHomeConfiguration(r,f,y,u,h,w);if(C)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(C,A,w,r,h);let E=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(E)return A.push(Ki($,"package.json")),this.finalizeResult(E,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Cn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${mB(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Af(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)wt.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)wt.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Af(i,n,f):n,y=[Ki(cn(),".config",i),Ki(cn(),".config"),cn()];for(let w of y){if(f)wt.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)wt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Af(i,r,c):r;try{let w=Ki(n,"package.json");if(!AE(w))return null;let u={};try{u=JSON.parse(TE(w,"utf8"))}catch(A){if(c)wt.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let h=u[i],$=i;if(!h&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(u[T]){h=u[T],$=T;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)wt.success(`Configuration loaded from package.json: ${$}`);return{config:mh(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)wt.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Af(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Cn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return ef.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);ef.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ki(i,"config"),Ki(i,".config"),t?Ki(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ki(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ki(cn(),".config",i),Ki(cn(),".config"),cn()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var fR=new Nh;function Af(i,t,n=!1){let r=new il,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((E)=>E.toUpperCase()).join("")}`,`${f}_${$.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,C;for(let E of A)if(T=_f.env[E],T!==void 0){C=E;break}if(T!==void 0&&C)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let E=Number(T);if(!Number.isNaN(E))w[u]=E}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((E)=>E.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}var cR=Ki(_f.cwd(),"config"),lR=Ki(_f.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",UB={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:nl(tl(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:nl(tl(),".stacks","ssl","stacks.localhost.crt"),keyPath:nl(tl(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Rh=UB;import{execSync as gn}from"node:child_process";import{homedir as XB}from"node:os";import{join as WB}from"node:path";function jB(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Qt(i){try{return vr(i)}catch{return null}}function rl(i){try{return hc(i)||null}catch{return null}}function fl(i,t){try{return t.every((n)=>Ac(i,n))}catch{return!1}}function NB(i,t,n=443){return $c(i,t,n)}function RB(i){let t=[];for(let n of i.split(`
|
|
132
|
-
`)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)t.push(r[1].toUpperCase())}return t}var bi="-d -r trustRoot -p ssl -p basic",Tt="/Library/Keychains/System.keychain",cl="rpx.localhost";function
|
|
133
|
-
`)){let c=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(c)r.push(c[1].toUpperCase())}return r}function Of(i){if(process.platform!=="darwin")return;let t=Qt(i.caPath);if(!t)return;let n=i.commonName??cl,r=i.keychains??ll();for(let f of r)for(let c of
|
|
134
|
-
`))if(c.toUpperCase().includes("SHA-256")){if(c.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return
|
|
131
|
+
`;return n}}function TY(i,t,n={}){return mh(i,t,n,new WeakMap)}function mh(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:c=!1,customMerger:l}=n;if(t===null||t===void 0)return c?i:t;if(l){let y=l(i,t);if(y!==void 0)return y}if(Array.isArray(t)||Array.isArray(i))return Ch(i,t,f,r);if(!zi(t)||!zi(i))return t;return BY(i,t,n,r)}function Ch(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return EY(i,t);case"smart":return eY(i,t,r);default:return t}return t}function EY(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>kc(f,r)))n.push(r);return n}function eY(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(zi(t[0])&&zi(i[0]))return YY(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function YY(i,t,n){let r=[...t];for(let f of i){if(!zi(f)){r.push(f);continue}let c=["id","name","key","path","type"],l=!1;for(let y of c)if(y in f){if(r.find((u)=>zi(u)&&(y in u)&&u[y]===f[y])){l=!0;break}}if(!l)r.push(f)}return r}function BY(i,t,n,r){let f=t;if(zi(f)&&r.has(f))return r.get(f);let c={...i};if(zi(f))r.set(f,c);for(let l in f){if(!Object.prototype.hasOwnProperty.call(f,l))continue;let y=f[l],w=c[l];if(n.skipNullish&&(y===null||y===void 0))continue;if(y===null||y===void 0){c[l]=y;continue}if(zi(y)&&zi(w))c[l]=mh(w,y,n,r);else if(Array.isArray(y)||Array.isArray(w))c[l]=Ch(w,y,n.arrayMergeMode||"smart",r);else c[l]=y}return c}function Uh(i,t,n="replace"){return TY(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function kc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!kc(i[n],t[n]))return!1;return!0}if(zi(i)&&zi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!kc(i[f],t[f]))return!1}return!0}return!1}function zi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class jh{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:c,trackPerformance:l=!0,verbose:y=!1}=n;if(f){let u=mf.getWithFileCheck("file",i);if(u){if(y)console.log(`Configuration loaded from cache: ${i}`);return u}}let w=async()=>{if(!$f(i))return null;try{let u=`?t=${Date.now()}`,h=await import(i+u),$=h.default||h,A="default"in h,T=Object.keys(h).length>0;if(!A&&!T)throw new If(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new If(i,Error("Configuration must export a valid object"),"unknown");let Y={config:Uh(t,$,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)mf.setWithFileCheck("file",Y,i,c);return Y}catch(u){throw u instanceof Error?Bn.configLoad(i,u):Bn.configLoad(i,Error(String(u)))}};if(l)return Vc.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let c of r)for(let l of this.extensions)f.push(_c(t,`${c}${l}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let c of r){if(!c)continue;if(n.push(c,`.${c}.config`,`${c}.config`,`.${c}`),i)n.push(`${i}.${c}.config`,`.${i}.${c}.config`)}let f=new Set;return n.filter((c)=>{if(!c||f.has(c))return!1;return f.add(c),!0})}checkFileAccess(i){return AY(async()=>{return $f(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!$f(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let c of f)for(let l of this.extensions){let y=_c(i,`${c}${l}`);if(await this.checkFileAccess(y))r.push(y)}}else try{let{readdirSync:f}=await import("fs"),c=f(i);for(let l of c)if(this.looksLikeConfigFile(l)){let y=_c(i,l);if(await this.checkFileAccess(y))r.push(y)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!$f(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),c=f(i,"utf8");JSON.parse(c)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var CY=/^https?:\/\//;class Rh{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:c=!0,customRules:l=[],trackPerformance:y=!0,verbose:w=!1}=n,u=async()=>{let h=[],$=[],A={stopOnFirstError:r,validateRequired:f,validateTypes:c,customRules:l,trackPerformance:y,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,A);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...l],A);else return this.validateWithJSONSchema(i,t,A)}catch(T){return h.push({path:"",message:`Validation failed: ${T}`,rule:"system"}),{isValid:!1,errors:h,warnings:$}}};if(y)return await Vc.track("validateConfiguration",u);return u()}async validateWithSchemaFile(i,t,n){try{if(!mY(t))throw new Kf(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Kf(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,c){if(c.validateTypes&&t.type){let l=Array.isArray(i)?"array":typeof i,y=Array.isArray(t.type)?t.type:[t.type];if(!y.includes(l)){if(r.push({path:n,message:`Expected type ${y.join(" or ")}, got ${l}`,expected:y.join(" or "),actual:l,rule:"type"}),c.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),c.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let l=0;l<i.length;l++){let y=n?`${n}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(i[l],t.items,y,r,f,c),c.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let l=i;if(c.validateRequired&&t.required){for(let y of t.required)if(!(y in l)){if(r.push({path:n?`${n}.${y}`:y,message:`Missing required property '${y}'`,expected:"required",rule:"required"}),c.stopOnFirstError)return}}if(t.properties){for(let[y,w]of Object.entries(t.properties))if(y in l){let u=n?`${n}.${y}`:y;if(this.validateObjectAgainstSchema(l[y],w,u,r,f,c),c.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let y=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(l))if(!y.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let c of t)try{let l=this.getValueByPath(i,c.path),y=this.validateWithRule(l,c,c.path);if(r.push(...y),n.stopOnFirstError&&r.length>0)break}catch(l){r.push({path:c.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,c,l]=r;t.push({path:f,required:!c,type:this.mapTypeScriptType(l)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:CY},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var wt=new Mf("bunfig",{showTags:!0});function UY(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class ah{fileLoader=new jh;envProcessor=new il;validator=new Rh;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:c,...l}=i;try{if(n?.enabled){let w=this.checkCache(l.name||"",l);if(w)return w}let y;try{y=await this.loadConfigurationStrategies(l,!0,n)}catch(w){let u=l.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(u)throw w;y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`No configuration file found for "${l.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let h=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),$=!h&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(u&&(A||h))throw w;if($&&(!u||!A))y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!u)y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else y={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||c)await this.validateConfiguration(y.config,f,c,l.name);if(n?.enabled&&y)this.cacheResult(l.name||"",y,n,l);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:l.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)wt.warn(`Slow configuration loading detected: ${w.duration}ms for ${l.name}`);y.metrics=w}return y}catch(y){if(y instanceof Error&&y.name==="ConfigNotFoundError")throw y;let w=Date.now()-t;throw wt.error(`Configuration loading failed after ${w}ms:`,[y instanceof Error?y:Error(String(y))]),y}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:c,configDir:l,defaultConfig:y,checkEnv:w=!0,arrayStrategy:u="replace",verbose:h=!1}=i,$=c||_f.cwd(),A=[],T=await this.loadLocalConfiguration(r,f,$,l,y,u,h,w,n);if(T)return A.push(...this.getLocalSearchPaths(r,f,$,l)),this.finalizeResult(T,A,w,r,h);let B=await this.loadHomeConfiguration(r,f,y,u,h,w);if(B)return A.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(B,A,w,r,h);let e=await this.loadPackageJsonConfiguration(r,f,$,y,u,h,w);if(e)return A.push(Ki($,"package.json")),this.finalizeResult(e,A,w,r,h);if(A.push(...this.getAllSearchPaths(r,f,$,l)),t)throw Bn.configNotFound(r,A,f);return{...await this.applyEnvironmentVariables(r,y,w,h),warnings:[`No configuration file found for "${r}"${UY(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,c,l,y,w){let u=y?Af(i,f,l):f,h=this.getLocalDirectories(n,r);for(let $ of h){if(l)wt.info(`Searching for configuration in: ${$}`);let A=this.fileLoader.generateConfigPaths(i,$,t),T=await this.fileLoader.tryLoadFromPaths(A,u,{arrayStrategy:c,verbose:l,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(T){if(l)wt.success(`Configuration loaded from: ${T.source.path}`);return T}}return null}async loadHomeConfiguration(i,t,n,r,f,c){if(!i)return null;let l=c?Af(i,n,f):n,y=[Ki(cn(),".config",i),Ki(cn(),".config"),cn()];for(let w of y){if(f)wt.info(`Checking home directory: ${w}`);let u=this.fileLoader.generateConfigPaths(i,w,t),h=await this.fileLoader.tryLoadFromPaths(u,l,{arrayStrategy:r,verbose:f});if(h){if(f)wt.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,c,l){let y=l?Af(i,r,c):r;try{let w=Ki(n,"package.json");if(!TE(w))return null;let u={};try{u=JSON.parse(EE(w,"utf8"))}catch(A){if(c)wt.warn("Failed to parse package.json:",[A instanceof Error?A:Error(String(A))]);return null}let h=u[i],$=i;if(!h&&t){let A=Array.isArray(t)?t:[t];for(let T of A){if(!T)continue;if(u[T]){h=u[T],$=T;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(c)wt.success(`Configuration loaded from package.json: ${$}`);return{config:Uh(y,h,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(c)wt.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Af(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let c=n(i);if(c)f.push(...c)}if(t){let c=await this.validator.validateConfiguration(i,t);if(!c.isValid)f.push(...c.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(f.length>0)throw Bn.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return mf.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);mf.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ki(i,"config"),Ki(i,".config"),t?Ki(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ki(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),c=[];for(let l of f)c.push(...this.fileLoader.generateConfigPaths(i,l,t));return c}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ki(cn(),".config",i),Ki(cn(),".config"),cn()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var ca=new ah;function Af(i,t,n=!1){let r=new il,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function c(l,y=[]){let w={...l};for(let[u,h]of Object.entries(l)){let $=[...y,u],A=[`${f}_${$.join("_").toUpperCase()}`,`${f}_${$.map((e)=>e.toUpperCase()).join("")}`,`${f}_${$.map((e)=>e.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],T,B;for(let e of A)if(T=_f.env[e],T!==void 0){B=e;break}if(T!==void 0&&B)if(typeof h==="boolean")w[u]=["true","1","yes"].includes(T.toLowerCase());else if(typeof h==="number"){let e=Number(T);if(!Number.isNaN(e))w[u]=e}else if(Array.isArray(h))try{w[u]=JSON.parse(T)}catch{w[u]=T.split(",").map((e)=>e.trim())}else w[u]=T;else if(h&&typeof h==="object"&&!Array.isArray(h))w[u]=c(h,$)}return w}return c(t)}var la=Ki(_f.cwd(),"config"),ya=Ki(_f.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",jY={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:nl(tl(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:nl(tl(),".stacks","ssl","stacks.localhost.crt"),keyPath:nl(tl(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Nh=jY;import{execSync as sn}from"node:child_process";import{homedir as SY}from"node:os";import{join as WY}from"node:path";function RY(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Qt(i){try{return vr(i)}catch{return null}}function rl(i){try{return hc(i)||null}catch{return null}}function fl(i,t){try{return t.every((n)=>Ac(i,n))}catch{return!1}}function aY(i,t,n=443){return $c(i,t,n)}function NY(i){let t=[];for(let n of i.split(`
|
|
132
|
+
`)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)t.push(r[1].toUpperCase())}return t}var bi="-d -r trustRoot -p ssl -p basic",Tt="/Library/Keychains/System.keychain",cl="rpx.localhost";function gn(){return WY(SY(),"Library/Keychains/login.keychain-db")}function ll(){return[Tt,gn()]}function Sh(i,t=cl){let n=sn(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let f of n.split(`
|
|
133
|
+
`)){let c=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(c)r.push(c[1].toUpperCase())}return r}function Of(i){if(process.platform!=="darwin")return;let t=Qt(i.caPath);if(!t)return;let n=i.commonName??cl,r=i.keychains??ll();for(let f of r)for(let c of Sh(f,n)){if(c===t)continue;try{if(f.startsWith("/Library"))at(`security delete-certificate -Z ${c} "${f}"`);else sn(`security delete-certificate -Z ${c} "${f}"`,{stdio:"ignore"});E("ssl",`Removed stale Root CA ${c} from ${f}`,i.verbose)}catch{}}}function Ln(i,t,n){if(process.platform!=="darwin")return xn(i,n);try{let f=sn(`security verify-cert -c "${i}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return E("ssl",`verify-cert ${t}: ${f?"trusted":"not trusted"}`,n?.verbose),f}catch{return!1}}function xn(i,t){let n=Qt(i);if(!n)return!1;for(let r of ll())try{let f=sn(`security find-certificate -a -Z "${r}" 2>/dev/null || true`,{encoding:"utf8"});for(let c of f.split(`
|
|
134
|
+
`))if(c.toUpperCase().includes("SHA-256")){if(c.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return E("ssl",`Root CA fingerprint found in ${r}`,t?.verbose),!0}}catch{}return!1}function yl(i,t){if(process.platform!=="darwin")return!1;let n=t.serverName;Of({caPath:i,commonName:t.commonName,verbose:t.verbose});let r=gn();try{sn(`security add-trusted-cert ${bi} -k "${r}" "${i}"`,{stdio:"ignore"})}catch{}try{at(`security add-trusted-cert ${bi} -k ${Tt} "${i}"`)}catch{return!1}return Ln(i,n,{verbose:t.verbose})||xn(i,{verbose:t.verbose})}var Nt=null,$l=D(mn(),".stacks","ssl","rpx.localhost.crt");function _h(i,t){return[...new Set(i.filter(Boolean))].map((n)=>({serverName:n,cert:t.cert,key:t.key}))}function zh(i,t,n){let r=D(mn(),".stacks","ssl"),f=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:$l,keyPath:D(r,"rpx.localhost.key"),caCertPath:D(r,"rpx.localhost.ca.crt"),commonName:t},verbose:n,regenerateUntrustedCerts:!0,proxies:f.map((c)=>({from:"localhost:1",to:c,cleanUrls:!1}))}}var XY="rpx-root-ca.crt",JY="rpx-root-ca.key";function Al(i){return{caCertPath:D(i,XY),caKeyPath:D(i,JY)}}function Qa(i){return{certPath:D(i,"rpx.localhost.crt"),keyPath:D(i,"rpx.localhost.key"),caCertPath:D(i,"rpx.localhost.ca.crt"),rootCA:Al(i)}}async function FY(i,t){try{let[n,r]=await Promise.all([Z.readFile(i.caCertPath,"utf8"),Z.readFile(i.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return E("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:n,privateKey:r}}catch(n){return E("ssl",`No existing Root CA at ${i.caCertPath} (${n.code||n}), will create one`,t),null}}function Wh(i){let t=new Set;t.add(i);let n=i.split(".");if(n.length>=3){let r=n[n.length-1],f=n[n.length-2],c=new Set(["co","com","org","net","ac","gov","edu"]);if(!(n.length===3&&r.length===2&&c.has(f)))t.add(`*.${n.slice(1).join(".")}`)}return Array.from(t)}function Qh(i){let n=hl(i).replace(/\*/g,"wildcard"),r=D(mn(),".stacks","ssl"),f=r;if(typeof i?.https==="object")return f=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:r,{caCertPath:i.https.caCertPath||D(f,`${n}.ca.crt`),certPath:i.https.certPath||D(f,`${n}.crt`),keyPath:i.https.keyPath||D(f,`${n}.key`)};return{caCertPath:D(f,`${n}.ca.crt`),certPath:D(f,`${n}.crt`),keyPath:D(f,`${n}.key`)}}function Xh(i){let t=new Set;if(Gf(i))i.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";Wh(r).forEach((f)=>t.add(f))});else if(Fh(i)){let n=i.to||"rpx.localhost";Wh(n).forEach((r)=>t.add(r))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function Ma(i){E("ssl","Loading SSL configuration",i.verbose);let t={...Nh,...i};if(i.https=el(t),!i.https?.keyPath&&!i.https?.certPath)return E("ssl","No SSL configuration provided",i.verbose),null;if(i.https?.keyPath&&!i.https?.certPath||!i.https?.keyPath&&i.https?.certPath){let n=!i.https?.keyPath?"keyPath":"certPath";throw E("ssl",`Invalid SSL configuration - missing ${n}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{E("ssl","Reading SSL certificate files",i.verbose);let n=await Z.readFile(i.https?.keyPath,"utf8"),r=await Z.readFile(i.https?.certPath,"utf8");return E("ssl","SSL configuration loaded successfully",i.verbose),{key:n,cert:r}}catch(n){return E("ssl",`Failed to read certificates: ${n}`,i.verbose),null}}catch(n){throw E("ssl",`SSL configuration error: ${n}`,i.verbose),n}}async function Oa(i,t){if(xi.platform==="darwin")return IY(i,t);if(xi.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((r)=>{n(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)r(!0);else n(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(c)=>{r(!c)})})})}catch{return!1}return!1}async function IY(i,t){if(xi.platform!=="darwin")return!1;let n=t?.serverName??"rpx.localhost",r=t?.verbose??!1;try{if(Ln(i,n,{verbose:r}))return E("ssl","Root CA already trusted for SSL, skipping trust operation",r),!0;return E("ssl","Trusting Root CA for browsers (login + system keychains)",r),yl(i,{serverName:n,verbose:r})}catch{return!1}}async function Mh(i){if(Nt&&!i.forceRegenerate){E("ssl","Using cached SSL configuration",i.verbose);return}Tl();let t=Gf(i)?i.proxies.map((h)=>h.to):[i.to];E("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let n=el(i,i.verbose),r=n.basePath||D(mn(),".stacks","ssl");await Z.mkdir(r,{recursive:!0});let f=Al(r),c=await FY(f,i.verbose),l=!1;if(!c){if(i.verbose)W.info("Generating Root CA certificate (one-time)...");c=await wc(n);try{await Promise.all([Z.writeFile(f.caCertPath,c.certificate),Z.writeFile(f.caKeyPath,c.privateKey,{mode:384})]),l=!0,E("ssl",`Persisted Root CA at ${f.caCertPath}`,i.verbose)}catch(h){throw E("ssl",`Error saving Root CA files: ${h}`,i.verbose),Error(`Failed to save Root CA files: ${h}`)}}else E("ssl",`Reusing existing Root CA from ${f.caCertPath}`,i.verbose);if(i.verbose)W.info(`Generating host certificate for: ${t.join(", ")}`);let y=await uc({...n,rootCA:{certificate:c.certificate,privateKey:c.privateKey}});try{await Promise.all([Z.writeFile(n.certPath,y.certificate),Z.writeFile(n.keyPath,y.privateKey),Z.writeFile(n.caCertPath,c.certificate)]),E("ssl","Certificate files saved successfully",i.verbose)}catch(h){throw E("ssl",`Error saving certificate files: ${h}`,i.verbose),Error(`Failed to save certificate files: ${h}`)}if(l?!1:await Oh(f.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(E("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)W.success("Root CA is already trusted in system trust store");if(Nt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)W.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)W.info("Adding certificate to system trust store (may require sudo permission)...");let u=!1;if(xi.platform==="darwin")try{Of({caPath:f.caCertPath,verbose:i.verbose});let h=gn();try{wl(`security add-trusted-cert ${bi} -k "${h}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(at(`security add-trusted-cert ${bi} -k ${Tt} "${f.caCertPath}"`),i.verbose)W.success("Successfully added Root CA to system trust store");u=!0;let $=D(r,"trust-rpx-cert.sh"),A=`#!/bin/bash
|
|
135
135
|
echo "Trusting RPX Root CA"
|
|
136
136
|
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
137
137
|
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
@@ -144,7 +144,7 @@ else
|
|
|
144
144
|
fi
|
|
145
145
|
echo "Root CA trusted! Please restart your browser."
|
|
146
146
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
147
|
-
`;await Z.writeFile($,A,{mode:493})}catch(h){if(i.verbose)
|
|
147
|
+
`;await Z.writeFile($,A,{mode:493})}catch(h){if(i.verbose)W.warn(`Could not add Root CA to trust store automatically: ${h}`);let $=D(r,"trust-rpx-cert.sh"),A=`#!/bin/bash
|
|
148
148
|
echo "Trusting RPX Root CA"
|
|
149
149
|
# SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
|
|
150
150
|
# non-interactive. Without it, fall back to a normal sudo prompt.
|
|
@@ -157,34 +157,34 @@ else
|
|
|
157
157
|
fi
|
|
158
158
|
echo "Root CA trusted! Please restart your browser."
|
|
159
159
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
160
|
-
`;if(await Z.writeFile($,A,{mode:493}),i.verbose)
|
|
160
|
+
`;if(await Z.writeFile($,A,{mode:493}),i.verbose)W.info(`Created a trust helper script at: ${$}`),W.info(`If you're still having certificate issues, run: sh ${$}`)}else if(xi.platform==="linux")try{let{exec:h}=await import("node:child_process"),$="/usr/local/share/ca-certificates/rpx",A=`
|
|
161
161
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
162
162
|
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
163
163
|
update-ca-certificates
|
|
164
164
|
echo "RPX Root CA installed. Please restart your browser."
|
|
165
|
-
`,T=D(ul.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Z.writeFile(T,A,{mode:493}),await new Promise((
|
|
165
|
+
`,T=D(ul.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Z.writeFile(T,A,{mode:493}),await new Promise((B)=>{h(`sudo bash "${T}"`,(e)=>{if(e){if(i.verbose)W.warn(`Could not trust certificates: ${e}`);B(!1)}else{if(i.verbose)W.success("Successfully added certificates to system trust store");B(!0)}})}),await Z.unlink(T).catch(()=>{}),u=!0}catch(h){if(i.verbose)W.warn(`Failed to trust certificates: ${h}`)}else if(xi.platform==="win32")try{let h=`
|
|
166
166
|
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
|
|
167
167
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
168
168
|
$store.Open("ReadWrite")
|
|
169
169
|
$store.Add($cert)
|
|
170
170
|
$store.Close()
|
|
171
171
|
Write-Host "Root CA trusted successfully!"
|
|
172
|
-
`,$=D(ul.tmpdir(),"rpx-trust.ps1");if(await Z.writeFile($,h),wl(`powershell -ExecutionPolicy Bypass -File "${$}"`),i.verbose)
|
|
173
|
-
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let f=r.indexOf(":");if(f<=0)continue;t.set(r.slice(0,f),r.slice(f+1))}return t}function
|
|
174
|
-
`),c=f===-1?r:r.slice(0,f),l=c.indexOf(" "),y=Number.parseInt(c.slice(l+1,l+5),10),w=c.startsWith("HTTP/1.0"),u=[],h=-1,$=!1,A=w,T=!1,
|
|
175
|
-
`,
|
|
172
|
+
`,$=D(ul.tmpdir(),"rpx-trust.ps1");if(await Z.writeFile($,h),wl(`powershell -ExecutionPolicy Bypass -File "${$}"`),i.verbose)W.success("Successfully added certificate to Windows trust store");u=!0}catch(h){if(i.verbose)W.warn(`Could not trust certificate: ${h}`)}else try{await Tc(y,c.certificate,n),u=!0}catch(h){if(i.verbose)W.warn(`Could not add certificate to trust store: ${h}`)}if(Nt={key:y.privateKey,cert:y.certificate,ca:c.certificate},i.verbose)W.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!u&&i.verbose)W.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),W.warn("This will bypass the warning and you should only need to do it once")}function Tl(){Nt=null}async function El(i){if(!i)return null;if(Nt)return Nt;let t=el(i);try{let[n,r,f]=await Promise.all([Z.access(t.keyPath).then(()=>!0).catch(()=>!1),Z.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?Z.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!n||!r)return E("ssl",`Certificate files don't exist: key=${n}, cert=${r}, paths: ${t.keyPath}, ${t.certPath}`,i.verbose),null;let c="regenerateUntrustedCerts"in i,l=i.regenerateUntrustedCerts,y=c?l!==!1:!0;E("ssl",`Trust check: hasFlag=${c}, flagValue=${l}, shouldCheckTrust=${y}`,i.verbose);let w=t.basePath||D(mn(),".stacks","ssl"),u=Al(w);if(!(y?await Oh(u.caCertPath,i):!0))return E("ssl","Root CA exists but is not trusted, will regenerate",i.verbose),null;let[$,A,T]=await Promise.all([Z.readFile(t.keyPath,"utf8"),Z.readFile(t.certPath,"utf8"),f&&t.caCertPath?Z.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(T&&!T.includes("-----BEGIN CERTIFICATE-----"))return E("ssl","Invalid root CA certificate content, will regenerate",i.verbose),null;if(Gf(i))try{let{X509Certificate:B}=await import("node:crypto"),Y=new B(A).subjectAltName||"",j=i.proxies.map((N)=>N.to).filter((N)=>!Y.includes(`DNS:${N}`));if(j.length>0)return E("ssl",`Certificate missing SANs for: ${j.join(", ")}, will regenerate`,i.verbose),null}catch(B){E("ssl",`Could not verify cert SANs: ${B}`,i.verbose)}return E("ssl","Successfully loaded existing certificates",i.verbose),Nt={key:$,cert:A,ca:T},Nt}catch(n){return E("ssl",`Error checking existing certificates: ${n}`,i.verbose),null}}function el(i,t){let n=hl(i);E("ssl",`Primary domain: ${n}`,t);let r=Qh(i),f=D(mn(),".stacks","ssl");if(typeof i.https==="object"){let c=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:f,l={domain:n,hostCertCN:n,basePath:c,caCertPath:i.https.caCertPath||r.caCertPath,certPath:i.https.certPath||r.certPath,keyPath:i.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:i.https.commonName||n,organizationName:i.https.organizationName||"Local Development",countryName:i.https.countryName||"US",stateName:i.https.stateName||"California",localityName:i.https.localityName||"Playa Vista",validityDays:i.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(Xh(i)).map((y)=>({type:2,value:y}))};if(Jh(i.https.rootCA))l.rootCA=i.https.rootCA;return l}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(Xh(i)).map((c)=>({type:2,value:c}))}}async function Ga(i,t){let n=Qh({to:i,verbose:t}),r=[n.caCertPath,n.certPath,n.keyPath];E("certificates","Attempting to clean up relating certificates",t),await Promise.all(r.map((f)=>Ih(f,t)))}async function Oh(i,t){try{if(E("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),xi.platform==="darwin"){if(t?.serverName)return Ln(i,t.serverName,{verbose:t?.verbose});return xn(i,{verbose:t?.verbose})}else if(xi.platform==="win32")try{let n=rl(i)||"";if(!n)return E("ssl","Could not extract certificate subject",t?.verbose),!1;let r=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(wl(r).toString().includes(n))return E("ssl","Certificate found in trusted root store",t?.verbose),!0;return E("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(n){return E("ssl",`Error checking certificate trust on Windows: ${n}`,t?.verbose),!1}else if(xi.platform==="linux")try{let n=Qt(i);if(!n)return E("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let r=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of r){let c;try{c=await Z.readdir(f)}catch{continue}for(let l of c){let y=Qt(Kh.join(f,l));if(y&&y===n)return E("ssl",`Certificate fingerprint found in ${f}`,t?.verbose),!0}}return E("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(n){return E("ssl",`Error checking certificate trust on Linux: ${n}`,t?.verbose),!1}return E("ssl",`Platform ${xi.platform} not supported for certificate trust check`,t?.verbose),!1}catch(n){return E("ssl",`Error checking if certificate is trusted: ${n}`,t?.verbose),!1}}function KY(i){return{enabled:i?.enabled??!1,path:i?.path??"/",interval:i?.interval??1e4,timeout:i?.timeout??2000,healthyThreshold:i?.healthyThreshold??2,unhealthyThreshold:i?.unhealthyThreshold??3}}function _Y(i){return(Array.isArray(i)?i:[i]).map((n)=>{let r=typeof n==="string"?{url:n}:n;return{url:r.url,weight:r.weight&&r.weight>0?r.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function Gh(i){return(Array.isArray(i)?i:[i]).map((n)=>typeof n==="string"?n:n.url)}function Hh(i){if(!i)return"localhost:5173";let t=Array.isArray(i)?i[0]:i;if(!t)return"localhost:5173";return typeof t==="string"?t:t.url}function qh(i,t){return{upstreams:_Y(i),strategy:t?.strategy??"round-robin",healthCheck:KY(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function zY(i){let t=i.upstreams.filter((n)=>n.healthy);if(t.length===0&&i.upstreams.length===1)return i.upstreams;return t}function QY(i,t){let n=i.cursor%t.length;return i.cursor=(i.cursor+1)%t.length,t[n]}function MY(i,t){if(i.wrrCurrentWeights.length!==t.length)i.wrrCurrentWeights=t.map(()=>0);let n=t.reduce((f,c)=>f+c.weight,0),r=0;for(let f=0;f<t.length;f++)if(i.wrrCurrentWeights[f]+=t[f].weight,i.wrrCurrentWeights[f]>i.wrrCurrentWeights[r])r=f;return i.wrrCurrentWeights[r]-=n,t[r]}function OY(i){let t=i[0];for(let n=1;n<i.length;n++)if(i[n].activeConnections<t.activeConnections)t=i[n];return t}function sh(i){let t=zY(i);if(t.length===0)return;if(t.length===1)return t[0];switch(i.strategy){case"weighted-round-robin":return MY(i,t);case"least-connections":return OY(t);case"round-robin":default:return QY(i,t)}}function Hf(i,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=i.healthCheck.healthyThreshold)t.healthy=!0}function kn(i,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=i.healthCheck.unhealthyThreshold)t.healthy=!1}function GY(i){let t=i.lastIndexOf(":");if(t===-1)return{hostname:i,port:80};let n=Number(i.slice(t+1));return{hostname:i.slice(0,t),port:Number.isFinite(n)?n:80}}async function HY(i,t){let{hostname:n,port:r}=GY(t.url),f=new AbortController,c=setTimeout(()=>f.abort(),i.healthCheck.timeout);try{(await fetch(`http://${n}:${r}${i.healthCheck.path}`,{signal:f.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),Hf(i,t)}catch{kn(i,t)}finally{clearTimeout(c)}}function gh(i){if(!i.healthCheck.enabled||i.healthCheckTimer||i.upstreams.length<2)return;let t=setInterval(()=>{for(let n of i.upstreams)HY(i,n)},i.healthCheck.interval);t.unref?.(),i.healthCheckTimer=t}function Yl(i){if(i.healthCheckTimer)clearInterval(i.healthCheckTimer),i.healthCheckTimer=null}import{createHash as xh,timingSafeEqual as Lh}from"node:crypto";import{readFileSync as qY}from"node:fs";var sY="/.well-known/acme-challenge/";function Vn(i,t){let n=Buffer.from(i,"utf8"),r=Buffer.from(t,"utf8");if(n.length!==r.length)return Lh(n,n),!1;return Lh(n,r)}function gY(i,t){let n=(A)=>xh("md5").update(A).digest(),r=Buffer.from(i,"utf8"),f=Buffer.from(t,"utf8"),c=n(Buffer.concat([r,f,r])),l=[r,Buffer.from("$apr1$","utf8"),f];for(let A=r.length;A>0;A-=16)l.push(c.subarray(0,Math.min(A,16)));for(let A=r.length;A>0;A>>=1)l.push(A&1?Buffer.from([0]):r.subarray(0,1));let y=n(Buffer.concat(l));for(let A=0;A<1000;A++){let T=[];if(T.push(A&1?r:y.subarray(0,16)),A%3)T.push(f);if(A%7)T.push(r);T.push(A&1?y.subarray(0,16):r),y=n(Buffer.concat(T))}let w="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",u=(A,T)=>{let B="",e=A;for(let Y=0;Y<T;Y++)B+=w[e&63],e>>=6;return B},h=y,$="";return $+=u(h[0]<<16|h[6]<<8|h[12],4),$+=u(h[1]<<16|h[7]<<8|h[13],4),$+=u(h[2]<<16|h[8]<<8|h[14],4),$+=u(h[3]<<16|h[9]<<8|h[15],4),$+=u(h[4]<<16|h[10]<<8|h[5],4),$+=u(h[11],2),`$apr1$${t}$${$}`}function LY(i,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(i,t)}catch{return!1}if(t.startsWith("$apr1$")){let r=t.split("$")[2]??"";return Vn(gY(i,r),t)}if(t.startsWith("{SHA}")){let n=xh("sha1").update(i,"utf8").digest("base64");return Vn(`{SHA}${n}`,t)}return Vn(i,t)}function xY(i){let t=new Map;for(let n of i.split(`
|
|
173
|
+
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let f=r.indexOf(":");if(f<=0)continue;t.set(r.slice(0,f),r.slice(f+1))}return t}function kh(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",n=[];if(i.username)n.push({username:i.username,password:i.password??""});for(let c of i.users??[])if(c?.username)n.push({username:c.username,password:c.password??""});let r;if(i.htpasswdFile)try{r=xY(qY(i.htpasswdFile,"utf8"))}catch{r=void 0}if(n.length===0&&(!r||r.size===0))return;return{realm:t,verify:(c,l)=>{let y=!1;for(let w of n)if(Vn(c,w.username)&&Vn(l,w.password))y=!0;if(r){let w=r.get(c);if(w&&LY(l,w))y=!0}return y}}}function Vh(i,t,n){if(t.startsWith(sY))return;let r=i.headers.get("authorization")??"",f=r.indexOf(" "),c=f===-1?r:r.slice(0,f),l=f===-1?"":r.slice(f+1).trim();if(c.toLowerCase()==="basic"&&l){let w="";try{w=Buffer.from(l,"base64").toString("utf8")}catch{w=""}let u=w.indexOf(":");if(u>=0&&n.verify(w.slice(0,u),w.slice(u+1)))return}let y=n.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${y}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:kY}=Bun,dn=Symbol("rpx.pool.fallback"),qf=Symbol("rpx.pool.stale");var VY=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function dY(i){return VY.has(i.toUpperCase())}var ml=Symbol("rpx.pool.timeout"),Mt=Symbol("rpx.pool.busy");function DY(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function bY(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function PY(){let i=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(i)&&i>0?i:0}function ZY(){let i=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(i)&&i>0?i:0}var Dh=1048576;function vY(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var Bl=30000,oY=16384,bh=262144,pY=2097152,iB=524288,tB=8192,nB=4096,rB=new TextEncoder,Ph=new TextDecoder,fB=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class Zh{socket=null;buf=new Uint8Array(oY);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(i){let t=this.socket,n=t.write(i);while(n<i.length){if(this.closed)throw qf;await new Promise((r)=>{this.drainWaiter=r}),n+=t.write(i.subarray(n))}}wakeDrain(){let i=this.drainWaiter;if(i)this.drainWaiter=null,i()}push(i){if(this.bodyQueue){let t=i.length<=this.bodyRemaining?i.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(i.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<i.length)this.appendToBuf(i.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(i),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>pY)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=iB)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(i){let t=this.len+i.length;if(t>this.buf.length){let n=new Uint8Array(Math.max(this.buf.length*2,t));n.set(this.buf.subarray(0,this.len)),this.buf=n}this.buf.set(i,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let i=this.waiter;if(i)this.waiter=null,i()}waitForData(i){if(this.len>i||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((i)=>{this.waiter=i})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class vh{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=DY();maxWaiters;checkoutIdleMs=PY();inUse=new Set;constructor(i,t,n,r=""){this.host=i;this.port=t;this.maxTotal=n;this.key=r;this.maxWaiters=bY(n)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new Zh;return kY({hostname:this.host,port:this.port,socket:{data:(t,n)=>i.push(n),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let n=t;n.setNoDelay?.(!0);let r=ZY();if(r>0)n.timeout?.(r);return i.socket=t,i})}acquireIdleSync(){while(this.idle.length){let i=this.idle.pop();if(!i.closed)return i.socket?.ref(),i.pos=0,i.len=0,this.trackCheckout(i),i;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Mt;let i=await this.waitForSlot();if(i===Mt)throw Mt;if(i)return i.pos=0,i.len=0,this.trackCheckout(i),i}this.open++;try{let i=await this.dial();return this.trackCheckout(i),i}catch(i){throw this.open--,this.wakeWaiter(),i}}waitForSlot(){return new Promise((i)=>{let t=!1,n=(c)=>{if(t)return;t=!0,clearTimeout(f),i(c)},r=(c)=>n(c),f=setTimeout(()=>{let c=this.waiters.indexOf(r);if(c!==-1)this.waiters.splice(c,1);n(Mt)},this.queueWaitMs);f.unref?.(),this.waiters.push(r)})}release(i){if(this.inUse.delete(i),i.closed){this.open--,this.wakeWaiter();return}i.clearStreaming(),i.compact(),i.fresh=!1;let t=this.waiters.shift();if(t){i.socket?.ref(),this.trackCheckout(i),t(i);return}i.idleSince=Date.now(),i.socket?.unref(),this.idle.push(i),this.ensureSweeper()}destroy(i){this.inUse.delete(i),i.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let i=this.waiters.shift();if(i)i(null)}ensureSweeper(){if(this.sweeper)return;let i=this.checkoutIdleMs>0?Math.min(Bl,this.checkoutIdleMs):Bl;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-Bl;if(this.idle.length){let n=[];for(let r of this.idle)if(r.closed||r.idleSince<=t)r.destroy(),this.open--;else n.push(r);this.idle=n}if(this.checkoutIdleMs>0&&this.inUse.size){let n=i-this.checkoutIdleMs;for(let r of this.inUse)if(!r.closed&&r.lastActivityAt>0&&r.lastActivityAt<=n)r.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&sf.get(this.key)===this)sf.delete(this.key)}}}var sf=new Map;function cB(i,t){let n=sf.get(i);if(!n){let r=i.lastIndexOf(":"),f=r===-1?i:i.slice(0,r),c=r===-1?80:Number(i.slice(r+1));n=new vh(f,c,t,i),sf.set(i,n)}return n}function dh(i,t,n){for(let r=n+3;r<t;r++)if(i[r]===10&&i[r-1]===13&&i[r-2]===10&&i[r-3]===13)return r-3;return-1}function lB(i,t,n){let r=Ph.decode(i.subarray(t,n)),f=r.indexOf(`\r
|
|
174
|
+
`),c=f===-1?r:r.slice(0,f),l=c.indexOf(" "),y=Number.parseInt(c.slice(l+1,l+5),10),w=c.startsWith("HTTP/1.0"),u=[],h=-1,$=!1,A=w,T=!1,B=!1,e=f===-1?r.length:f+2;while(e<r.length){let Y=r.indexOf(`\r
|
|
175
|
+
`,e);if(Y===-1)Y=r.length;let m=r.slice(e,Y);if(e=Y+2,m==="")continue;let j=m.indexOf(":");if(j===-1)continue;let N=m.slice(0,j),S=m.slice(j+1).trim(),F=N.charCodeAt(0)|32;if(F===99||F===116||F===107){let X=N.toLowerCase();if(X==="content-length"){let J=/^\d+$/.test(S)?Number(S):Number.NaN;if(!Number.isSafeInteger(J)||h>=0&&h!==J)B=!0;else h=J;continue}if(X==="transfer-encoding"){if(S.toLowerCase().includes("chunked"))$=!0;continue}if(X==="connection"){let J=S.toLowerCase();if(J.includes("close"))A=!0;if(J.includes("keep-alive"))T=!0;continue}if(X==="keep-alive")continue}u.push([N,S])}if(w&&T)A=!1;if($&&h>=0)h=-1;return{status:y,headerEnd:n,headers:u,contentLength:h,chunked:$,closeConn:A,malformed:B}}function yB(i,t){return t||i===204||i===304}async function oh(i){let{hostPort:t,method:n,path:r,reqHeaders:f,forwardedHost:c,originOverride:l,body:y}=i,w=n==="HEAD";if(f.get("expect")||f.get("upgrade"))throw dn;let u=null;if(y){let T=f.get("content-length"),B=T?Number.parseInt(T,10):Number.NaN;if(Number.isNaN(B)||B>Dh)throw dn;if(u=await EB(y),u===null)throw dn}let h=TB(n,r,f,t,c,l,u),$=h;if(u&&u.length)$=new Uint8Array(h.length+u.length),$.set(h),$.set(u,h.length);let A=cB(t,i.maxPerHost??vY());for(let T=0;;T++){if(T>0)await new Promise((e)=>{setTimeout(e,T)});let B;try{B=A.acquireIdleSync()??await A.acquireOrDial()}catch(e){if(e!==Mt&&T<4)continue;throw e}try{let e=B.socket.write($);if(e<$.length)await B.writeAll($.subarray(e));return await uB(A,B,w)}catch(e){let Y=e===qf&&T<4&&(B.fresh||dY(n));if(A.destroy(B),Y)continue;if(e===qf)throw Error("upstream closed connection");throw e}}}async function wB(i){let t=dh(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw ml;if(i.len===i.pos)throw qf;throw Error("upstream closed mid-header")}if(i.len-i.pos>bh)throw Error("upstream header block too large");await i.waitForData(i.len),t=dh(i.buf,i.len,i.pos)}return t}async function uB(i,t,n){let r;for(;;){let c=await wB(t);if(r=lB(t.buf,t.pos,c),t.pos=c+4,r.status>=100&&r.status<200)continue;break}if(r.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let f=r.headers;if(yB(r.status,n))return ph(i,t,r.closeConn),new Response(null,{status:r.status,headers:f});if(r.chunked)return new Response(AB(i,t,r.closeConn),{status:r.status,headers:f});if(r.contentLength>=0){if(t.len-t.pos>=r.contentLength){let l=t.pos+r.contentLength,y=t.len>l,w=null;if(r.contentLength>=tB)w=t.buf.subarray(t.pos,l),t.buf=new Uint8Array(nB);else if(r.contentLength>0)w=t.buf.slice(t.pos,l);if(t.pos=0,t.len=0,r.closeConn||y)i.destroy(t);else i.release(t);return new Response(w,{status:r.status,headers:f})}return new Response(hB(i,t,r.contentLength,r.closeConn),{status:r.status,headers:f})}return new Response($B(t),{status:r.status,headers:f})}function ph(i,t,n){if(n||t.pos!==t.len)i.destroy(t);else i.release(t)}function hB(i,t,n,r){let f=t.len-t.pos,c=f>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=n-f,t.queuedBytes=0,t.streamingBody=!0;let l=(y)=>{if(t.bodyQueue=null,r||t.len>0)i.destroy(t);else i.release(t);y.close()};return new ReadableStream({start(y){if(c)y.enqueue(c);if(t.bodyRemaining===0&&t.bodyQueue.length===0)l(y)},async pull(y){for(;;){let w=t.bodyQueue;if(w&&w.length>0){let u=w.shift();if(t.queuedBytes-=u.length,t.resumeIfDrained(),y.enqueue(u),t.bodyRemaining===0&&w.length===0)l(y);return}if(t.bodyRemaining===0){if(t.bodyQueue)l(y);return}if(t.closed){t.bodyQueue=null,i.destroy(t),y.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,i.destroy(t)}})}function $B(i){return i.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(i.len>i.pos){t.enqueue(i.buf.slice(i.pos,i.len)),i.pos=i.len,i.resumeIfDrained();return}if(i.closed){i.destroy(),t.close();return}await i.waitForData(i.len)}},cancel(){i.destroy()}})}function AB(i,t,n){t.streamingBody=!0;let r=0,f=!1,c=!1;async function l(){for(;;){for(let y=t.pos;y+1<t.len;y++)if(t.buf[y]===13&&t.buf[y+1]===10){let w=Ph.decode(t.buf.subarray(t.pos,y));return t.pos=y+2,w}if(t.closed)throw Error("upstream closed mid-chunk-header");if(t.len-t.pos>bh)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({async pull(y){try{for(;;){if(r>0){if(t.len===t.pos){if(t.closed){i.destroy(t),y.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let $=Math.min(r,t.len-t.pos);if(y.enqueue(t.buf.slice(t.pos,t.pos+$)),t.pos+=$,r-=$,t.resumeIfDrained(),r===0)f=!0;return}if(f)await l(),f=!1;let w=await l(),u=w.indexOf(";"),h=Number.parseInt(u===-1?w:w.slice(0,u),16);if(!Number.isInteger(h)||h<0){i.destroy(t),y.error(Error("upstream sent malformed chunk size"));return}if(h===0){for(;;)if(await l()==="")break;ph(i,t,n),y.close();return}r=h}}catch(w){if(i.destroy(t),!c)y.error(w)}},cancel(){c=!0,i.destroy(t)}})}function TB(i,t,n,r,f,c,l){let y=`${i} ${t} HTTP/1.1\r
|
|
176
176
|
host: ${r}\r
|
|
177
177
|
x-forwarded-for: 127.0.0.1\r
|
|
178
178
|
x-forwarded-proto: https\r
|
|
179
179
|
x-forwarded-host: ${f}\r
|
|
180
180
|
`;if(c!==void 0)y+=`origin: ${c}\r
|
|
181
|
-
`;let w=!1;for(let[u,h]of n){let $=u.toLowerCase();if(
|
|
181
|
+
`;let w=!1;for(let[u,h]of n){let $=u.toLowerCase();if(fB.has($))continue;if(c!==void 0&&$==="origin")continue;if($==="content-length")w=!0;y+=`${u}: ${h}\r
|
|
182
182
|
`}if(y+=`connection: keep-alive\r
|
|
183
183
|
`,l&&!w)y+=`content-length: ${l.length}\r
|
|
184
184
|
`;return y+=`\r
|
|
185
|
-
`,nC.encode(y)}async function TC(i){let t=i.getReader(),n=[],r=0;for(;;){let{done:l,value:y}=await t.read();if(l)break;if(y){if(r+=y.length,r>dh)return t.cancel().catch(()=>{}),null;n.push(y)}}if(n.length===1)return n[0];let f=new Uint8Array(r),c=0;for(let l of n)f.set(l,c),c+=l.length;return f}function VR(i){let t=typeof i==="string"?{to:i}:i,n=(t.to??"").trim();if(n&&!/^[a-z][\w+.-]*:\/\//i.test(n))n=`https://${n}`;return n=n.replace(/\/+$/,""),{to:n,status:t.status??301,preservePath:t.preservePath??!0}}function ph(i,t,n){if(!i.preservePath)return i.to||"/";let r=`${t}${n}`;return r==="/"?`${i.to}/`:`${i.to}${r}`}import*as Qi from"node:path";function i$(i,t){if(typeof i==="string")return{dir:i,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:i.dir,spa:i.spa??!1,pathRewriteStyle:i.pathRewriteStyle??"directory",maxAge:i.maxAge??0,cleanUrls:t}}var EC={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"};function YC(i){let t=Qi.extname(i).toLowerCase();return EC[t]??"application/octet-stream"}function BC(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let n=Qi.posix.normalize(`/${t}`);if(n.split("/").includes(".."))return null;return n.replace(/^\/+/,"")}function CC(i,t){let n=BC(i);if(n===null)return null;let r=Qi.posix.extname(n);if(t.cleanUrls&&r===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Qi.join(t.dir,n),redirectTo:f||"/"}}if(n===""||i.endsWith("/"))return{filePath:Qi.join(t.dir,n,"index.html")};if(r!=="")return{filePath:Qi.join(t.dir,n)};if(t.pathRewriteStyle==="flat")return{filePath:Qi.join(t.dir,`${n}.html`)};return{filePath:Qi.join(t.dir,n,"index.html")}}async function t$(i,t){let n=CC(i,t);if(!n)return new Response("Forbidden",{status:403});if(n.redirectTo)return new Response(null,{status:301,headers:{Location:n.redirectTo}});let r=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(n.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":YC(n.filePath),"Cache-Control":r}});if(t.spa){let c=Qi.join(t.dir,"index.html"),l=Bun.file(c);if(await l.exists())return new Response(l,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}function eC(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var mC=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function UC(i){let t=i.headers.get("host")||"",n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function c$(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let n=i.slice(t.length);return n===""?"/":n}return i}function n$(i){if(i.upstreamPool)return qh(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function r$(i,t,n,r){let f=n?.url??t.sourceHost??"",l=t.stripBasePathPrefix??!1?c$(i,t.basePath):i,y=f$(l,t.pathRewrites);if(y)f=y.targetHost,l=y.targetPath,Y("request",`Path rewrite: ${i} → ${f}${l}`,r);return{targetHost:f,targetPath:l}}function jC(i){let t=i.indexOf("://"),n=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(n===-1)return{pathname:"/",search:""};let r=i.indexOf("?",n);if(r===-1)return{pathname:i.slice(n),search:""};return{pathname:i.slice(n,r),search:i.slice(r)}}function ml(i,t,n){let r=async(f,c)=>{let{pathname:l,search:y}=jC(f.url),w=UC(f),u=i(w,l);if(!u&&n){let B=await n(w,l,f);if(B instanceof Response)return B;if(B&&B.retry)u=i(w,l)}if(!u)return Y("request",`No route found for host: ${w}`,t),new Response(`No proxy configured for ${w}`,{status:404});if(u.auth){let B=kh(f,l,u.auth);if(B)return Y("request",`401 challenge for ${w}${l}`,t),B}if(u.redirect){let B=ph(u.redirect,l,y);return Y("request",`${u.redirect.status} redirect ${w}${l} → ${B}`,t),new Response(null,{status:u.redirect.status,headers:{location:B}})}if(u.static){let e=u.stripBasePathPrefix??!0?c$(l,u.basePath):l;return t$(e,u.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){let B=n$(u);if(!c||!B)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:e,targetPath:j}=r$(l,u,B,t),X=`ws://${e}${j}${y}`,W={};for(let[J,v]of f.headers)if(!mC.has(J.toLowerCase())&&J.toLowerCase()!=="host")W[J]=v;W.host=e,W["x-forwarded-for"]="127.0.0.1",W["x-forwarded-proto"]="https",W["x-forwarded-host"]=w;let F={targetUrl:X,forwardHeaders:W};if(c.upgrade(f,{data:F})){Y("ws",`upgraded ${w}${j} → ${X}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let h=n$(u);if(!h)return new Response(`No upstream configured for ${w}`,{status:502});if(u.cleanUrls&&l.endsWith(".html")){let B=l.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:B}})}let{targetHost:$,targetPath:A}=r$(l,u,h,t),T=u.changeOrigin?`http://${$}`:void 0,C=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD",E=u.upstreamPool;if(E)h.activeConnections++;try{let B=await vh({hostPort:$,method:f.method,path:`${A}${y}`,reqHeaders:f.headers,forwardedHost:w,originOverride:T,body:f.body});if(E)Hf(E,h);return B}catch(B){if(B===el){if(Y("request",`Upstream timeout for ${w}`,t),E)kn(E,h);return new Response("Gateway Timeout",{status:504})}if(B===Mt)return Y("request",`Upstream pool saturated for ${w}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(B===dn||!C)try{let e=new Headers(f.headers);if(e.set("host",$),e.set("x-forwarded-for","127.0.0.1"),e.set("x-forwarded-proto","https"),e.set("x-forwarded-host",w),T!==void 0)e.set("origin",T);let j=await fetch(`http://${$}${A}${y}`,{method:f.method,headers:e,body:f.body,redirect:"manual"});if(E)Hf(E,h);return j}catch(e){if(Y("request",`Proxy error for ${w}: ${e}`,t),E)kn(E,h);return new Response(`Proxy Error: ${e}`,{status:502})}if(Y("request",`Proxy error for ${w}: ${B}`,t),E)kn(E,h);return new Response(`Proxy Error: ${B}`,{status:502})}finally{if(E)h.activeConnections--}};return async(f,c)=>{try{return await r(f,c)}catch(l){return Y("request",`Unhandled proxy handler error: ${l}`,t),new Response("Bad Gateway",{status:502})}}}function Ul(i){let t=new WeakMap,n=eC();return{open(r){let{targetUrl:f,forwardHeaders:c}=r.data,l;try{l=new WebSocket(f,{headers:c})}catch(w){Y("ws",`failed to open upstream ${f}: ${w}`,i),r.close(1011,"upstream connect failed");return}l.binaryType="arraybuffer";let y={upstream:l,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(r,y),l.addEventListener("open",()=>{y.upstreamOpen=!0;for(let w of y.pending)l.send(w);y.pending=[],y.pendingBytes=0}),l.addEventListener("message",(w)=>{r.send(w.data)}),l.addEventListener("close",(w)=>{try{r.close(w.code||1000,w.reason||"")}catch{}}),l.addEventListener("error",()=>{Y("ws",`upstream error for ${f}`,i);try{r.close(1011,"upstream error")}catch{}})},message(r,f){let c=t.get(r);if(!c)return;let l=typeof f==="string"?f:new Uint8Array(f);if(c.upstreamOpen){c.upstream.send(l);return}let y=typeof l==="string"?Buffer.byteLength(l):l.byteLength;if(c.pendingBytes+y>n){Y("ws",`pending buffer would exceed ${n}B before upstream open; closing socket`,i);try{r.close(1009,"buffer limit")}catch{}try{c.upstream.close(1011,"client buffer overflow")}catch{}t.delete(r);return}c.pending.push(l),c.pendingBytes+=y},close(r,f,c){let l=t.get(r);if(!l)return;t.delete(r);try{l.upstream.close(f||1000,c||"")}catch{}}}}import*as y$ from"node:fs";import*as w$ from"node:path";var l$="/.well-known/acme-challenge/";function u$(i,t){if(!i||!t.startsWith(l$))return null;let n=t.slice(l$.length);if(!n||!/^[A-Za-z0-9_-]+$/.test(n))return null;try{return y$.readFileSync(w$.join(i,n),"utf8")}catch{return null}}function Lf(i){return i.startsWith("*.")}function jl(i,t){if(!Lf(t))return!1;let n=t.slice(1);return i.length>n.length&&i.endsWith(n)}function h$(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[c,l]of i){if(!Lf(c))continue;if(jl(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Ot(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function NC(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function Nl(i){let t=new Map;for(let r of i){let f=Ot(r.path),c=t.get(r.host);if(!c)c=new Map,t.set(r.host,c);c.set(f,r.route)}let n=new Map;for(let[r,f]of t){let c=[];for(let[l,y]of f)c.push({path:l,route:y});c.sort((l,y)=>y.path.length-l.path.length),n.set(r,c)}return n}function Rl(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[c,l]of i){if(!Lf(c))continue;if(jl(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Xl(i,t,n){let r=Rl(i,t);if(!r)return;for(let f of r)if(NC(n,f.path))return f.route;return}import*as Dn from"node:fs/promises";import*as Wl from"node:path";function bn(i){if(Array.isArray(i))return i.map((t)=>({...t,lowMemoryMode:!0}));return{...i,lowMemoryMode:!0}}function RC(i){if(!i.endsWith(".crt"))return null;let t=i.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function XC(i,t,n,r){try{let[f,c]=await Promise.all([Dn.readFile(t,"utf8"),Dn.readFile(n,"utf8")]);return{serverName:i,cert:f,key:c}}catch(f){return Y("sni",`skipping ${i}: ${f.message}`,r),null}}async function Sl(i,t){let n=new Map;if(i.certsDir){let f=[];try{f=await Dn.readdir(i.certsDir)}catch(c){Y("sni",`certsDir read failed (${i.certsDir}): ${c.message}`,t)}for(let c of f){let l=RC(c);if(!l)continue;let y=c.slice(0,-4);n.set(l,{certPath:Wl.join(i.certsDir,c),keyPath:Wl.join(i.certsDir,`${y}.key`)})}}if(i.domains)for(let[f,c]of Object.entries(i.domains))n.set(f,c);let r=[];for(let[f,c]of n){let l=await XC(f,c.certPath,c.keyPath,t);if(l)r.push(l)}return r}import*as ki from"node:fs/promises";import*as sf from"node:path";var WC="acme-account.key",SC=60000,$$=4096;function aC(i,t){if(!t||t.length===0)return!1;return t.some((n)=>{let r=n.startsWith(".")?n.slice(1):n;return i===r||i.endsWith(`.${r}`)})}function A$(i){if(!i||i.length>253)return!1;if(i.includes("/")||i.includes(":")||i.includes(" "))return!1;if(i.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(i)}class xf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??kr,this.issuer=i.issuer??b0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??SC;for(let t of i.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(i){return this.certs.has(i)}async isApproved(i){if(!A$(i))return!1;if(aC(i,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(i)}catch(t){return Y("on-demand",`ask(${i}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(i){if(!this.config.enabled)return!1;if(this.certs.has(i))return!0;if(!A$(i))return!1;let t=this.inFlight.get(i);if(t)return t;let n=this.negativeCache.get(i);if(n!==void 0&&Date.now()<n){if(await this.loadFromDisk(i))return this.negativeCache.delete(i),!0;return Y("on-demand",`${i} negatively cached for ${n-Date.now()}ms`,this.verbose),!1}let r=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,r),r}async issue(i){if(this.certs.has(i))return!0;if(await this.loadFromDisk(i))return!0;if(!await this.isApproved(i))return Y("on-demand",`refused issuance for ${i} (not approved)`,this.verbose),this.cacheNegative(i),!1;try{Y("on-demand",`issuing cert for ${i} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(i,t.fullChainPem,t.keyPem);let n={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,n),this.negativeCache.delete(i),Y("on-demand",`issued + installed cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(i),Y("on-demand",`issuance for ${i} failed: ${t.message}`,this.verbose),!1}}cacheNegative(i){if(this.negativeCache.size>=$$){let t=Date.now();for(let[n,r]of this.negativeCache)if(r<=t)this.negativeCache.delete(n);if(this.negativeCache.size>=$$){let n=this.negativeCache.keys().next().value;if(n!==void 0)this.negativeCache.delete(n)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:n}=this.pathsFor(i);try{let[r,f]=await Promise.all([ki.readFile(t,"utf8"),ki.readFile(n,"utf8")]),c={serverName:i,cert:r,key:f};return this.certs.set(i,c),Y("on-demand",`adopted existing on-disk cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(i){return{certPath:sf.join(this.certsDir,`${i}.crt`),keyPath:sf.join(this.certsDir,`${i}.key`)}}async persist(i,t,n){await ki.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:r,keyPath:f}=this.pathsFor(i);await Promise.all([ki.writeFile(r,t,"utf8"),ki.writeFile(f,n,{encoding:"utf8",mode:384})])}get accountKeyPath(){return sf.join(this.certsDir,WC)}async loadAccountKey(){try{return await ki.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(i){if(!i||this.accountKeyPem===i)return;this.accountKeyPem=i,await ki.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await ki.writeFile(this.accountKeyPath,i,{encoding:"utf8",mode:384}).catch(()=>{})}}import{existsSync as JC,readdirSync as FC,readFileSync as IC,statSync as KC}from"node:fs";import{homedir as Y$}from"node:os";import{isAbsolute as _C,join as mn}from"node:path";var B$=["~/Code"],C$=["localhost","test"],zC=1800000,al={dirExists:(i)=>{try{return KC(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return JC(i)}catch{return!1}},readText:(i)=>{try{return IC(i,"utf8")}catch{return null}}};function Jl(i,t){if(i==="~")return t;if(i.startsWith("~/"))return mn(t,i.slice(2));return i}function QC(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function T$(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function MC(i,t){for(let n of t){let r=`.${n}`;if(i.endsWith(r)){let f=i.slice(0,-r.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function OC(i,t){let n=t.readText(mn(i,"rpx.site.json"));if(n)try{let f=JSON.parse(n);if(f&&typeof f==="object")return f}catch{}let r=t.readText(mn(i,"package.json"));if(r)try{let f=JSON.parse(r);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function GC(i){let t=i.selfRegisters??!1;return{command:i.command,env:i.env,urlEnv:i.urlEnv,selfRegisters:t,routes:i.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function HC(i,t){let n=OC(i,t);if(n?.command)return GC(n);let r=t.fileExists(mn(i,"buddy")),f=t.readText(mn(i,"package.json")),c=null;if(f)try{c=JSON.parse(f)}catch{c=null}let l={...c?.dependencies??{},...c?.devDependencies??{}};if(r||Object.keys(l).some((w)=>w==="stacks"||w.startsWith("@stacksjs/")))return{command:r?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(c?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function Fl(i,t={}){let n={dirExists:t.dirExists??al.dirExists,fileExists:t.fileExists??al.fileExists,readText:t.readText??al.readText},r=t.detect??HC,f=t.homeDir??Y$(),c=i.tlds??C$,l=(i.roots??B$).map((A)=>Jl(A,f)),y=i.idleTimeoutMs??zC,w=new Map;for(let A of i.sites??[])w.set(A.to,A);let u=(A)=>A.idleTimeoutMs??y;function h(A){let T=h$(w,A);if(!T)return null;let C=_C(T.dir)?T.dir:Jl(T.dir,f),E=T.selfRegisters??!1,B=T.routes??[];if(!E&&B.length===0)B=r(C,n)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let e=E$({...T.env??{}},void 0,A);return{host:A,id:T$(A),dir:C,command:T.command,env:e,routes:B,selfRegisters:E,idleTimeoutMs:u(T),source:"config"}}function $(A){let T=MC(A,c);if(!T)return null;for(let C of l){let E=mn(C,T);if(!n.dirExists(E))continue;let B=r(E,n);if(!B)continue;let e=B.selfRegisters??!1;return{host:A,id:T$(A),dir:E,command:B.command,env:E$({...B.env??{}},B.urlEnv,A),routes:e?[]:B.routes??[],selfRegisters:e,idleTimeoutMs:y,source:"discovered"}}return null}return{resolve(A){let T=QC(A);if(!T)return null;return h(T)??$(T)}}}function qC(i){try{return FC(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function EX(i,t={}){let n=t.homeDir??Y$(),r=i.tlds??C$,f=(i.roots??B$).map(($)=>Jl($,n)),c=t.readdir??qC,l=Fl(i,t),y=[],w=new Set,u=($)=>{if($&&!w.has($.host))w.add($.host),y.push($)};for(let $ of i.sites??[])if(!$.to.includes("*"))u(l.resolve($.to));let h=r[0]??"localhost";for(let $ of f)for(let A of c($))u(l.resolve(`${A}.${h}`));return y}function E$(i,t,n){if(!t)return i;let r=`https://${n}`;for(let f of t)if(i[f]===void 0)i[f]=r;return i}import{closeSync as R$,openSync as kC,readFileSync as VC}from"node:fs";import*as X$ from"node:fs/promises";import{spawn as dC}from"node:child_process";import{homedir as DC}from"node:os";import*as Zn from"node:path";import*as Vi from"node:process";import*as kf from"node:net";function m$(i,t,n){return Y("port",`Checking if port ${i} is in use on ${t}`,n),new Promise((r)=>{let f=kf.createServer(),c=setTimeout(()=>{Y("port",`Checking port ${i} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(l)=>{if(clearTimeout(c),l.code==="EADDRINUSE")Y("port",`Port ${i} is in use`,n),r(!0);else Y("port",`Error checking port ${i}: ${l.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(c),Y("port",`Port ${i} is available`,n),f.close(),r(!1)});try{f.listen(i,t)}catch(l){clearTimeout(c),Y("port",`Exception checking port ${i}: ${l}`,n),r(!0)}})}async function Il(i,t,n,r=50){Y("port",`Finding available port starting from ${i} (max attempts: ${r})`,n);let f=i,c=0;while(c<r){if(c++,!await m$(f,t,n))return Y("port",`Found available port: ${f} after ${c} attempts`,n),f;Y("port",`Port ${f} is in use, trying ${f+1} (attempt ${c}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${i}`)}function e$(i,t,n=5000,r){return Y("port",`Testing connection to ${t}:${i}`,r),new Promise((f)=>{let c=kf.connect({host:t,port:i,timeout:n});c.once("connect",()=>{Y("port",`Successfully connected to ${t}:${i}`,r),c.end(),f(!0)}),c.once("timeout",()=>{Y("port",`Connection to ${t}:${i} timed out`,r),c.destroy(),f(!1)}),c.once("error",(l)=>{Y("port",`Failed to connect to ${t}:${i}: ${l.message}`,r),c.destroy(),f(!1)})})}class U${usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,n=50){this.hostname=i,this.verbose=t,this.maxRetries=n}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await m$(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await e$(i,this.hostname,3000,this.verbose))return Y("port",`Port ${i} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(i+1,t)}return this.usedPorts.add(i),i}async findNextAvailablePort(i,t=!1){let n=await Il(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await e$(n,this.hostname,3000,this.verbose))if(n<i+this.maxRetries)return this.findNextAvailablePort(n+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(i){Y("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var CX=new U$;import*as Vf from"node:fs";import*as mi from"node:fs/promises";import{homedir as gC}from"node:os";import*as Kl from"node:path";import*as df from"node:process";var LC=/^[a-zA-Z0-9._-]+$/;function Wt(){return Kl.join(gC(),".stacks","rpx","registry.d")}function _l(i){return typeof i==="string"&&i.length>0&&i.length<=128&&LC.test(i)}function zl(i,t){if(!_l(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return Kl.join(i,`${t}.json`)}function Ui(i){if(!Number.isInteger(i)||i<=0)return!1;try{return df.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function j$(i){if(!i||typeof i!=="object")return!1;let t=i,n=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,r=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,f=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",c=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&_l(t.id)&&(r||f)&&typeof t.to==="string"&&t.to.length>0&&c&&n&&typeof t.createdAt==="string"}async function sC(i){await mi.mkdir(i,{recursive:!0})}async function N$(i,t=Wt(),n){if(!j$(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await sC(t);let r=zl(t,i.id),f=`${r}.tmp.${df.pid}.${Date.now()}`,c=JSON.stringify(i,null,2);try{await mi.writeFile(f,c,{encoding:"utf8",mode:420}),await mi.rename(f,r),Y("registry",`wrote entry ${i.id} → ${r}`,n)}catch(l){throw await mi.unlink(f).catch(()=>{}),l}}async function Ql(i,t=Wt(),n){let r=zl(t,i);try{await mi.unlink(r),Y("registry",`removed entry ${i}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function xC(i,t=Wt(),n){let r=zl(t,i);try{let f=await mi.readFile(r,"utf8"),c=JSON.parse(f);if(!j$(c))return Y("registry",`entry ${i} failed validation, removing`,n),await mi.unlink(r).catch(()=>{}),null;return c}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return Y("registry",`entry ${i} has invalid JSON, removing`,n),await mi.unlink(r).catch(()=>{}),null;throw f}}async function Et(i=Wt(),t){let n;try{n=await mi.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let c=f.slice(0,-5);if(!_l(c))continue;let l=await xC(c,i,t);if(l)r.push(l)}return r}async function Pn(i=Wt(),t){let n=await Et(i,t),r=0;for(let f of n){if(f.pid===void 0)continue;if(!Ui(f.pid))Y("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await Ql(f.id,i,t).catch(()=>{}),r++}return r}function Df(i,t={}){let n=t.dir??Wt(),r=t.debounceMs??100,f=t.pollMs??Math.max(r*2,250),c=t.verbose;Vf.mkdirSync(n,{recursive:!0});let l=null,y=!1,w=null,u=!1,h=(B)=>{return JSON.stringify(B.map((e)=>({id:e.id,from:e.from,to:e.to,path:e.path,pid:e.pid,pathRewrites:e.pathRewrites,cleanUrls:e.cleanUrls,changeOrigin:e.changeOrigin,static:e.static,loadBalancer:e.loadBalancer})).sort((e,j)=>e.id.localeCompare(j.id)))},$=()=>{if(l=null,y)return;Et(n,c).then((B)=>{return w=h(B),i(B)}).catch((B)=>{Y("registry",`watcher onChange failed: ${B}`,c)})},A=()=>{if(y)return;if(l)clearTimeout(l);l=setTimeout($,r)},C=setInterval(()=>{if(y||u)return;u=!0,Et(n,c).then((B)=>{if(h(B)!==w)A()}).catch((B)=>{Y("registry",`watcher poll failed: ${B}`,c)}).finally(()=>{u=!1})},f),E=Vf.watch(n,{persistent:!0},(B,e)=>{if(e&&/\.tmp\.\d+\.\d+$/.test(e))return;A()});return E.on("error",(B)=>{Y("registry",`watcher error: ${B}`,c)}),A(),{close:()=>{if(y=!0,l)clearTimeout(l);clearInterval(C),E.close()}}}var bC=120000,PC=200,ZC=30000,vC=3000,oC=4000;class Ol{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(i){this.resolver=i.resolver,this.registryDir=i.registryDir??Wt(),this.rpxDir=i.rpxDir??Zn.join(DC(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??bC,this.pollIntervalMs=i.pollIntervalMs??PC,this.restartDelayMs=i.restartDelayMs??vC,this.killGraceMs=i.killGraceMs??oC,this.launch=i.launcher??ie(this.verbose),this.probePort=i.probePort??pC,this.pickPort=i.pickPort??((n)=>Il(n,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??N$,this.removeEntry=i.removeEntry??Ql;let t=i.reapIntervalMs??ZC;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(i){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(i);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(i),t=void 0;if(!t){let n=this.resolver.resolve(i);if(!n)return{kind:"unknown"};t=await this.start(n)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:i};if(t.status==="failed")return{kind:"failed",host:i,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:i,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(i){try{this.onSiteActivating?.(i.host)}catch{}let t=new Map;if(!i.selfRegisters)for(let y of i.routes){if(t.has(y.portEnv))continue;let w=await this.pickPort(y.defaultPort??3000);t.set(y.portEnv,w)}let n=Zn.join(this.rpxDir,"sites",`${i.id}.log`);await X$.mkdir(Zn.dirname(n),{recursive:!0}).catch(()=>{});let r=this.buildEnv(i,t),f=null,c;try{f=this.launch({command:i.command,cwd:i.dir,env:r,logPath:n})}catch(y){c=`failed to spawn: ${y.message}`}let l={site:i,status:c?"failed":"starting",handle:f,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:c?this.now():0,error:c,logPath:n,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,l),c)return S.warn(`rpx: site ${i.host} ${c}`),l;return S.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),f.exited.then((y)=>this.onProcessExit(l,y)).catch(()=>{}),l.ready=this.driveReadiness(l).catch((y)=>{Y("sites",`readiness loop for ${i.host} threw: ${y}`,this.verbose)}),l}async onProcessExit(i,t){if(i.exited=!0,this.stopped||this.sites.get(i.site.host)!==i)return;if(i.status==="ready"){S.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let n of i.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{})}else if(i.status==="starting")this.fail(i,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(i){let{site:t}=i,n=this.now()+this.startupTimeoutMs,r=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<n&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await r()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",S.success(`rpx: ${t.host} ready`);return}await Ml(this.pollIntervalMs)}if(i.status==="starting")this.fail(i,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(i,t){let n=i.routes.filter((f)=>f.readyGate??Ot(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),r=n.length>0?n:[...t.values()];return async()=>{for(let f of r)if(!await this.probePort(f))return!1;return r.length>0}}async publishRoutes(i){let{site:t,ports:n}=i;if(t.selfRegisters||t.routes.length===0)return;let r=t.routes.find((w)=>Ot(w.path)==="/")??t.routes[0],f=n.get(r.portEnv);if(f===void 0)return;let c=[];for(let w of t.routes){if(w===r)continue;let u=n.get(w.portEnv);if(u===void 0)continue;c.push({from:Ot(w.path),to:`localhost:${u}`,stripPrefix:w.stripPrefix??!1})}let l={id:t.id,from:`localhost:${f}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:c.length>0?c:void 0,pid:i.handle?.pid};await this.writeEntry(l,this.registryDir,this.verbose),i.routeIds=[t.id];let y=this.now()+2000;while(this.now()<y&&!this.isHostRoutable(t.host))await Ml(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),S.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let n={};for(let[r,f]of Object.entries(Vi.env))if(typeof f==="string")n[r]=f;Object.assign(n,i.env);for(let[r,f]of t)n[r]=String(f);return n.RPX_SITE_HOST=i.host,n.RPX_SITE_URL=`https://${i.host}`,n}readLogTail(i,t=40){try{return VC(i.logPath,"utf8").split(`
|
|
185
|
+
`,rB.encode(y)}async function EB(i){let t=i.getReader(),n=[],r=0;for(;;){let{done:l,value:y}=await t.read();if(l)break;if(y){if(r+=y.length,r>Dh)return t.cancel().catch(()=>{}),null;n.push(y)}}if(n.length===1)return n[0];let f=new Uint8Array(r),c=0;for(let l of n)f.set(l,c),c+=l.length;return f}function da(i){let t=typeof i==="string"?{to:i}:i,n=(t.to??"").trim();if(n&&!/^[a-z][\w+.-]*:\/\//i.test(n))n=`https://${n}`;return n=n.replace(/\/+$/,""),{to:n,status:t.status??301,preservePath:t.preservePath??!0}}function i$(i,t,n){if(!i.preservePath)return i.to||"/";let r=`${t}${n}`;return r==="/"?`${i.to}/`:`${i.to}${r}`}import*as Qi from"node:path";function t$(i,t){if(typeof i==="string")return{dir:i,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:i.dir,spa:i.spa??!1,pathRewriteStyle:i.pathRewriteStyle??"directory",maxAge:i.maxAge??0,cleanUrls:t}}var eB={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"};function YB(i){let t=Qi.extname(i).toLowerCase();return eB[t]??"application/octet-stream"}function BB(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let n=Qi.posix.normalize(`/${t}`);if(n.split("/").includes(".."))return null;return n.replace(/^\/+/,"")}function mB(i,t){let n=BB(i);if(n===null)return null;let r=Qi.posix.extname(n);if(t.cleanUrls&&r===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Qi.join(t.dir,n),redirectTo:f||"/"}}if(n===""||i.endsWith("/"))return{filePath:Qi.join(t.dir,n,"index.html")};if(r!=="")return{filePath:Qi.join(t.dir,n)};if(t.pathRewriteStyle==="flat")return{filePath:Qi.join(t.dir,`${n}.html`)};return{filePath:Qi.join(t.dir,n,"index.html")}}async function n$(i,t){let n=mB(i,t);if(!n)return new Response("Forbidden",{status:403});if(n.redirectTo)return new Response(null,{status:301,headers:{Location:n.redirectTo}});let r=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(n.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":YB(n.filePath),"Cache-Control":r}});if(t.spa){let c=Qi.join(t.dir,"index.html"),l=Bun.file(c);if(await l.exists())return new Response(l,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}function CB(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var UB=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function jB(i){let t=i.headers.get("host")||"",n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function l$(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let n=i.slice(t.length);return n===""?"/":n}return i}function r$(i){if(i.upstreamPool)return sh(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function f$(i,t,n,r){let f=n?.url??t.sourceHost??"",l=t.stripBasePathPrefix??!1?l$(i,t.basePath):i,y=c$(l,t.pathRewrites);if(y)f=y.targetHost,l=y.targetPath,E("request",`Path rewrite: ${i} → ${f}${l}`,r);return{targetHost:f,targetPath:l}}function RB(i){let t=i.indexOf("://"),n=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(n===-1)return{pathname:"/",search:""};let r=i.indexOf("?",n);if(r===-1)return{pathname:i.slice(n),search:""};return{pathname:i.slice(n,r),search:i.slice(r)}}function Cl(i,t,n){let r=async(f,c)=>{let{pathname:l,search:y}=RB(f.url),w=jB(f),u=i(w,l);if(!u&&n){let Y=await n(w,l,f);if(Y instanceof Response)return Y;if(Y&&Y.retry)u=i(w,l)}if(!u)return E("request",`No route found for host: ${w}`,t),new Response(`No proxy configured for ${w}`,{status:404});if(u.auth){let Y=Vh(f,l,u.auth);if(Y)return E("request",`401 challenge for ${w}${l}`,t),Y}if(u.redirect){let Y=i$(u.redirect,l,y);return E("request",`${u.redirect.status} redirect ${w}${l} → ${Y}`,t),new Response(null,{status:u.redirect.status,headers:{location:Y}})}if(u.static){let m=u.stripBasePathPrefix??!0?l$(l,u.basePath):l;return n$(m,u.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){let Y=r$(u);if(!c||!Y)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:m,targetPath:j}=f$(l,u,Y,t),N=`ws://${m}${j}${y}`,S={};for(let[J,v]of f.headers)if(!UB.has(J.toLowerCase())&&J.toLowerCase()!=="host")S[J]=v;S.host=m,S["x-forwarded-for"]="127.0.0.1",S["x-forwarded-proto"]="https",S["x-forwarded-host"]=w;let F={targetUrl:N,forwardHeaders:S};if(c.upgrade(f,{data:F})){E("ws",`upgraded ${w}${j} → ${N}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let h=r$(u);if(!h)return new Response(`No upstream configured for ${w}`,{status:502});if(u.cleanUrls&&l.endsWith(".html")){let Y=l.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:Y}})}let{targetHost:$,targetPath:A}=f$(l,u,h,t),T=u.changeOrigin?`http://${$}`:void 0,B=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD",e=u.upstreamPool;if(e)h.activeConnections++;try{let Y=await oh({hostPort:$,method:f.method,path:`${A}${y}`,reqHeaders:f.headers,forwardedHost:w,originOverride:T,body:f.body});if(e)Hf(e,h);return Y}catch(Y){if(Y===ml){if(E("request",`Upstream timeout for ${w}`,t),e)kn(e,h);return new Response("Gateway Timeout",{status:504})}if(Y===Mt)return E("request",`Upstream pool saturated for ${w}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(Y===dn||!B)try{let m=new Headers(f.headers);if(m.set("host",$),m.set("x-forwarded-for","127.0.0.1"),m.set("x-forwarded-proto","https"),m.set("x-forwarded-host",w),T!==void 0)m.set("origin",T);let j=await fetch(`http://${$}${A}${y}`,{method:f.method,headers:m,body:f.body,redirect:"manual"});if(e)Hf(e,h);return j}catch(m){if(E("request",`Proxy error for ${w}: ${m}`,t),e)kn(e,h);return new Response(`Proxy Error: ${m}`,{status:502})}if(E("request",`Proxy error for ${w}: ${Y}`,t),e)kn(e,h);return new Response(`Proxy Error: ${Y}`,{status:502})}finally{if(e)h.activeConnections--}};return async(f,c)=>{try{return await r(f,c)}catch(l){return E("request",`Unhandled proxy handler error: ${l}`,t),new Response("Bad Gateway",{status:502})}}}function Ul(i){let t=new WeakMap,n=CB();return{open(r){let{targetUrl:f,forwardHeaders:c}=r.data,l;try{l=new WebSocket(f,{headers:c})}catch(w){E("ws",`failed to open upstream ${f}: ${w}`,i),r.close(1011,"upstream connect failed");return}l.binaryType="arraybuffer";let y={upstream:l,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(r,y),l.addEventListener("open",()=>{y.upstreamOpen=!0;for(let w of y.pending)l.send(w);y.pending=[],y.pendingBytes=0}),l.addEventListener("message",(w)=>{r.send(w.data)}),l.addEventListener("close",(w)=>{try{r.close(w.code||1000,w.reason||"")}catch{}}),l.addEventListener("error",()=>{E("ws",`upstream error for ${f}`,i);try{r.close(1011,"upstream error")}catch{}})},message(r,f){let c=t.get(r);if(!c)return;let l=typeof f==="string"?f:new Uint8Array(f);if(c.upstreamOpen){c.upstream.send(l);return}let y=typeof l==="string"?Buffer.byteLength(l):l.byteLength;if(c.pendingBytes+y>n){E("ws",`pending buffer would exceed ${n}B before upstream open; closing socket`,i);try{r.close(1009,"buffer limit")}catch{}try{c.upstream.close(1011,"client buffer overflow")}catch{}t.delete(r);return}c.pending.push(l),c.pendingBytes+=y},close(r,f,c){let l=t.get(r);if(!l)return;t.delete(r);try{l.upstream.close(f||1000,c||"")}catch{}}}}import*as w$ from"node:fs";import*as u$ from"node:path";var y$="/.well-known/acme-challenge/";function h$(i,t){if(!i||!t.startsWith(y$))return null;let n=t.slice(y$.length);if(!n||!/^[A-Za-z0-9_-]+$/.test(n))return null;try{return w$.readFileSync(u$.join(i,n),"utf8")}catch{return null}}function gf(i){return i.startsWith("*.")}function jl(i,t){if(!gf(t))return!1;let n=t.slice(1);return i.length>n.length&&i.endsWith(n)}function $$(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[c,l]of i){if(!gf(c))continue;if(jl(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Ot(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function aB(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function Rl(i){let t=new Map;for(let r of i){let f=Ot(r.path),c=t.get(r.host);if(!c)c=new Map,t.set(r.host,c);c.set(f,r.route)}let n=new Map;for(let[r,f]of t){let c=[];for(let[l,y]of f)c.push({path:l,route:y});c.sort((l,y)=>y.path.length-l.path.length),n.set(r,c)}return n}function al(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[c,l]of i){if(!gf(c))continue;if(jl(t,c)){let y=c.length-1;if(y>f)f=y,r=l}}return r}function Nl(i,t,n){let r=al(i,t);if(!r)return;for(let f of r)if(aB(n,f.path))return f.route;return}import*as Dn from"node:fs/promises";import*as Sl from"node:path";function bn(i){if(Array.isArray(i))return i.map((t)=>({...t,lowMemoryMode:!0}));return{...i,lowMemoryMode:!0}}function NB(i){if(!i.endsWith(".crt"))return null;let t=i.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function SB(i,t,n,r){try{let[f,c]=await Promise.all([Dn.readFile(t,"utf8"),Dn.readFile(n,"utf8")]);return{serverName:i,cert:f,key:c}}catch(f){return E("sni",`skipping ${i}: ${f.message}`,r),null}}async function Wl(i,t){let n=new Map;if(i.certsDir){let f=[];try{f=await Dn.readdir(i.certsDir)}catch(c){E("sni",`certsDir read failed (${i.certsDir}): ${c.message}`,t)}for(let c of f){let l=NB(c);if(!l)continue;let y=c.slice(0,-4);n.set(l,{certPath:Sl.join(i.certsDir,c),keyPath:Sl.join(i.certsDir,`${y}.key`)})}}if(i.domains)for(let[f,c]of Object.entries(i.domains))n.set(f,c);let r=[];for(let[f,c]of n){let l=await SB(f,c.certPath,c.keyPath,t);if(l)r.push(l)}return r}import*as ki from"node:fs/promises";import*as Lf from"node:path";function Xl(i=process.env){let t=i.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return i.INVOCATION_ID?"restart":"rebind"}var WB="acme-account.key",XB=60000,A$=4096;function JB(i,t){if(!t||t.length===0)return!1;return t.some((n)=>{let r=n.startsWith(".")?n.slice(1):n;return i===r||i.endsWith(`.${r}`)})}function T$(i){if(!i||i.length>253)return!1;if(i.includes("/")||i.includes(":")||i.includes(" "))return!1;if(i.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(i)}class xf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??kr,this.issuer=i.issuer??b0,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??XB;for(let t of i.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(i){return this.certs.has(i)}async isApproved(i){if(!T$(i))return!1;if(JB(i,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(i)}catch(t){return E("on-demand",`ask(${i}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(i){if(!this.config.enabled)return!1;if(this.certs.has(i))return!0;if(!T$(i))return!1;let t=this.inFlight.get(i);if(t)return t;let n=this.negativeCache.get(i);if(n!==void 0&&Date.now()<n){if(await this.loadFromDisk(i))return this.negativeCache.delete(i),!0;return E("on-demand",`${i} negatively cached for ${n-Date.now()}ms`,this.verbose),!1}let r=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,r),r}async issue(i){if(this.certs.has(i))return!0;if(await this.loadFromDisk(i))return!0;if(!await this.isApproved(i))return E("on-demand",`refused issuance for ${i} (not approved)`,this.verbose),this.cacheNegative(i),!1;try{E("on-demand",`issuing cert for ${i} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(i,t.fullChainPem,t.keyPem);let n={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,n),this.negativeCache.delete(i),E("on-demand",`issued + installed cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(i),E("on-demand",`issuance for ${i} failed: ${t.message}`,this.verbose),!1}}cacheNegative(i){if(this.negativeCache.size>=A$){let t=Date.now();for(let[n,r]of this.negativeCache)if(r<=t)this.negativeCache.delete(n);if(this.negativeCache.size>=A$){let n=this.negativeCache.keys().next().value;if(n!==void 0)this.negativeCache.delete(n)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:n}=this.pathsFor(i);try{let[r,f]=await Promise.all([ki.readFile(t,"utf8"),ki.readFile(n,"utf8")]),c={serverName:i,cert:r,key:f};return this.certs.set(i,c),E("on-demand",`adopted existing on-disk cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(i){return{certPath:Lf.join(this.certsDir,`${i}.crt`),keyPath:Lf.join(this.certsDir,`${i}.key`)}}async persist(i,t,n){await ki.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:r,keyPath:f}=this.pathsFor(i);await Promise.all([ki.writeFile(r,t,"utf8"),ki.writeFile(f,n,{encoding:"utf8",mode:384})])}get accountKeyPath(){return Lf.join(this.certsDir,WB)}async loadAccountKey(){try{return await ki.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(i){if(!i||this.accountKeyPem===i)return;this.accountKeyPem=i,await ki.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await ki.writeFile(this.accountKeyPath,i,{encoding:"utf8",mode:384}).catch(()=>{})}}import{existsSync as FB,readdirSync as IB,readFileSync as KB,statSync as _B}from"node:fs";import{homedir as Y$}from"node:os";import{isAbsolute as zB,join as Cn}from"node:path";var B$=["~/Code"],m$=["localhost","test"],QB=1800000,Jl={dirExists:(i)=>{try{return _B(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return FB(i)}catch{return!1}},readText:(i)=>{try{return KB(i,"utf8")}catch{return null}}};function Fl(i,t){if(i==="~")return t;if(i.startsWith("~/"))return Cn(t,i.slice(2));return i}function MB(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function E$(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function OB(i,t){for(let n of t){let r=`.${n}`;if(i.endsWith(r)){let f=i.slice(0,-r.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function GB(i,t){let n=t.readText(Cn(i,"rpx.site.json"));if(n)try{let f=JSON.parse(n);if(f&&typeof f==="object")return f}catch{}let r=t.readText(Cn(i,"package.json"));if(r)try{let f=JSON.parse(r);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function HB(i){let t=i.selfRegisters??!1;return{command:i.command,env:i.env,urlEnv:i.urlEnv,selfRegisters:t,routes:i.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function qB(i,t){let n=GB(i,t);if(n?.command)return HB(n);let r=t.fileExists(Cn(i,"buddy")),f=t.readText(Cn(i,"package.json")),c=null;if(f)try{c=JSON.parse(f)}catch{c=null}let l={...c?.dependencies??{},...c?.devDependencies??{}};if(r||Object.keys(l).some((w)=>w==="stacks"||w.startsWith("@stacksjs/")))return{command:r?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(c?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function Il(i,t={}){let n={dirExists:t.dirExists??Jl.dirExists,fileExists:t.fileExists??Jl.fileExists,readText:t.readText??Jl.readText},r=t.detect??qB,f=t.homeDir??Y$(),c=i.tlds??m$,l=(i.roots??B$).map((A)=>Fl(A,f)),y=i.idleTimeoutMs??QB,w=new Map;for(let A of i.sites??[])w.set(A.to,A);let u=(A)=>A.idleTimeoutMs??y;function h(A){let T=$$(w,A);if(!T)return null;let B=zB(T.dir)?T.dir:Fl(T.dir,f),e=T.selfRegisters??!1,Y=T.routes??[];if(!e&&Y.length===0)Y=r(B,n)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let m=e$({...T.env??{}},void 0,A);return{host:A,id:E$(A),dir:B,command:T.command,env:m,routes:Y,selfRegisters:e,idleTimeoutMs:u(T),source:"config"}}function $(A){let T=OB(A,c);if(!T)return null;for(let B of l){let e=Cn(B,T);if(!n.dirExists(e))continue;let Y=r(e,n);if(!Y)continue;let m=Y.selfRegisters??!1;return{host:A,id:E$(A),dir:e,command:Y.command,env:e$({...Y.env??{}},Y.urlEnv,A),routes:m?[]:Y.routes??[],selfRegisters:m,idleTimeoutMs:y,source:"discovered"}}return null}return{resolve(A){let T=MB(A);if(!T)return null;return h(T)??$(T)}}}function sB(i){try{return IB(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function eN(i,t={}){let n=t.homeDir??Y$(),r=i.tlds??m$,f=(i.roots??B$).map(($)=>Fl($,n)),c=t.readdir??sB,l=Il(i,t),y=[],w=new Set,u=($)=>{if($&&!w.has($.host))w.add($.host),y.push($)};for(let $ of i.sites??[])if(!$.to.includes("*"))u(l.resolve($.to));let h=r[0]??"localhost";for(let $ of f)for(let A of c($))u(l.resolve(`${A}.${h}`));return y}function e$(i,t,n){if(!t)return i;let r=`https://${n}`;for(let f of t)if(i[f]===void 0)i[f]=r;return i}import{closeSync as N$,openSync as VB,readFileSync as dB}from"node:fs";import*as S$ from"node:fs/promises";import{spawn as DB}from"node:child_process";import{homedir as bB}from"node:os";import*as Zn from"node:path";import*as Vi from"node:process";import*as kf from"node:net";function U$(i,t,n){return E("port",`Checking if port ${i} is in use on ${t}`,n),new Promise((r)=>{let f=kf.createServer(),c=setTimeout(()=>{E("port",`Checking port ${i} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(l)=>{if(clearTimeout(c),l.code==="EADDRINUSE")E("port",`Port ${i} is in use`,n),r(!0);else E("port",`Error checking port ${i}: ${l.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(c),E("port",`Port ${i} is available`,n),f.close(),r(!1)});try{f.listen(i,t)}catch(l){clearTimeout(c),E("port",`Exception checking port ${i}: ${l}`,n),r(!0)}})}async function Kl(i,t,n,r=50){E("port",`Finding available port starting from ${i} (max attempts: ${r})`,n);let f=i,c=0;while(c<r){if(c++,!await U$(f,t,n))return E("port",`Found available port: ${f} after ${c} attempts`,n),f;E("port",`Port ${f} is in use, trying ${f+1} (attempt ${c}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${i}`)}function C$(i,t,n=5000,r){return E("port",`Testing connection to ${t}:${i}`,r),new Promise((f)=>{let c=kf.connect({host:t,port:i,timeout:n});c.once("connect",()=>{E("port",`Successfully connected to ${t}:${i}`,r),c.end(),f(!0)}),c.once("timeout",()=>{E("port",`Connection to ${t}:${i} timed out`,r),c.destroy(),f(!1)}),c.once("error",(l)=>{E("port",`Failed to connect to ${t}:${i}: ${l.message}`,r),c.destroy(),f(!1)})})}class j${usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,n=50){this.hostname=i,this.verbose=t,this.maxRetries=n}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await U$(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await C$(i,this.hostname,3000,this.verbose))return E("port",`Port ${i} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(i+1,t)}return this.usedPorts.add(i),i}async findNextAvailablePort(i,t=!1){let n=await Kl(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await C$(n,this.hostname,3000,this.verbose))if(n<i+this.maxRetries)return this.findNextAvailablePort(n+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(i){E("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var mN=new j$;import*as Vf from"node:fs";import*as Ci from"node:fs/promises";import{homedir as gB}from"node:os";import*as _l from"node:path";import*as df from"node:process";var LB=/^[a-zA-Z0-9._-]+$/;function St(){return _l.join(gB(),".stacks","rpx","registry.d")}function zl(i){return typeof i==="string"&&i.length>0&&i.length<=128&&LB.test(i)}function Ql(i,t){if(!zl(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return _l.join(i,`${t}.json`)}function Ui(i){if(!Number.isInteger(i)||i<=0)return!1;try{return df.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function R$(i){if(!i||typeof i!=="object")return!1;let t=i,n=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,r=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,f=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",c=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&zl(t.id)&&(r||f)&&typeof t.to==="string"&&t.to.length>0&&c&&n&&typeof t.createdAt==="string"}async function xB(i){await Ci.mkdir(i,{recursive:!0})}async function a$(i,t=St(),n){if(!R$(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await xB(t);let r=Ql(t,i.id),f=`${r}.tmp.${df.pid}.${Date.now()}`,c=JSON.stringify(i,null,2);try{await Ci.writeFile(f,c,{encoding:"utf8",mode:420}),await Ci.rename(f,r),E("registry",`wrote entry ${i.id} → ${r}`,n)}catch(l){throw await Ci.unlink(f).catch(()=>{}),l}}async function Ml(i,t=St(),n){let r=Ql(t,i);try{await Ci.unlink(r),E("registry",`removed entry ${i}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function kB(i,t=St(),n){let r=Ql(t,i);try{let f=await Ci.readFile(r,"utf8"),c=JSON.parse(f);if(!R$(c))return E("registry",`entry ${i} failed validation, removing`,n),await Ci.unlink(r).catch(()=>{}),null;return c}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return E("registry",`entry ${i} has invalid JSON, removing`,n),await Ci.unlink(r).catch(()=>{}),null;throw f}}async function Et(i=St(),t){let n;try{n=await Ci.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let c=f.slice(0,-5);if(!zl(c))continue;let l=await kB(c,i,t);if(l)r.push(l)}return r}async function Pn(i=St(),t){let n=await Et(i,t),r=0;for(let f of n){if(f.pid===void 0)continue;if(!Ui(f.pid))E("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await Ml(f.id,i,t).catch(()=>{}),r++}return r}function Df(i,t={}){let n=t.dir??St(),r=t.debounceMs??100,f=t.pollMs??Math.max(r*2,250),c=t.verbose;Vf.mkdirSync(n,{recursive:!0});let l=null,y=!1,w=null,u=!1,h=(Y)=>{return JSON.stringify(Y.map((m)=>({id:m.id,from:m.from,to:m.to,path:m.path,pid:m.pid,pathRewrites:m.pathRewrites,cleanUrls:m.cleanUrls,changeOrigin:m.changeOrigin,static:m.static,loadBalancer:m.loadBalancer})).sort((m,j)=>m.id.localeCompare(j.id)))},$=()=>{if(l=null,y)return;Et(n,c).then((Y)=>{return w=h(Y),i(Y)}).catch((Y)=>{E("registry",`watcher onChange failed: ${Y}`,c)})},A=()=>{if(y)return;if(l)clearTimeout(l);l=setTimeout($,r)},B=setInterval(()=>{if(y||u)return;u=!0,Et(n,c).then((Y)=>{if(h(Y)!==w)A()}).catch((Y)=>{E("registry",`watcher poll failed: ${Y}`,c)}).finally(()=>{u=!1})},f),e=Vf.watch(n,{persistent:!0},(Y,m)=>{if(m&&/\.tmp\.\d+\.\d+$/.test(m))return;A()});return e.on("error",(Y)=>{E("registry",`watcher error: ${Y}`,c)}),A(),{close:()=>{if(y=!0,l)clearTimeout(l);clearInterval(B),e.close()}}}var PB=120000,ZB=200,vB=30000,oB=3000,pB=4000;class Gl{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(i){this.resolver=i.resolver,this.registryDir=i.registryDir??St(),this.rpxDir=i.rpxDir??Zn.join(bB(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??PB,this.pollIntervalMs=i.pollIntervalMs??ZB,this.restartDelayMs=i.restartDelayMs??oB,this.killGraceMs=i.killGraceMs??pB,this.launch=i.launcher??tm(this.verbose),this.probePort=i.probePort??im,this.pickPort=i.pickPort??((n)=>Kl(n,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??a$,this.removeEntry=i.removeEntry??Ml;let t=i.reapIntervalMs??vB;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(i){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(i);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(i),t=void 0;if(!t){let n=this.resolver.resolve(i);if(!n)return{kind:"unknown"};t=await this.start(n)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:i};if(t.status==="failed")return{kind:"failed",host:i,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:i,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(i){try{this.onSiteActivating?.(i.host)}catch{}let t=new Map;if(!i.selfRegisters)for(let y of i.routes){if(t.has(y.portEnv))continue;let w=await this.pickPort(y.defaultPort??3000);t.set(y.portEnv,w)}let n=Zn.join(this.rpxDir,"sites",`${i.id}.log`);await S$.mkdir(Zn.dirname(n),{recursive:!0}).catch(()=>{});let r=this.buildEnv(i,t),f=null,c;try{f=this.launch({command:i.command,cwd:i.dir,env:r,logPath:n})}catch(y){c=`failed to spawn: ${y.message}`}let l={site:i,status:c?"failed":"starting",handle:f,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:c?this.now():0,error:c,logPath:n,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,l),c)return W.warn(`rpx: site ${i.host} ${c}`),l;return W.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),f.exited.then((y)=>this.onProcessExit(l,y)).catch(()=>{}),l.ready=this.driveReadiness(l).catch((y)=>{E("sites",`readiness loop for ${i.host} threw: ${y}`,this.verbose)}),l}async onProcessExit(i,t){if(i.exited=!0,this.stopped||this.sites.get(i.site.host)!==i)return;if(i.status==="ready"){W.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let n of i.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{})}else if(i.status==="starting")this.fail(i,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(i){let{site:t}=i,n=this.now()+this.startupTimeoutMs,r=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<n&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await r()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",W.success(`rpx: ${t.host} ready`);return}await Ol(this.pollIntervalMs)}if(i.status==="starting")this.fail(i,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(i,t){let n=i.routes.filter((f)=>f.readyGate??Ot(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),r=n.length>0?n:[...t.values()];return async()=>{for(let f of r)if(!await this.probePort(f))return!1;return r.length>0}}async publishRoutes(i){let{site:t,ports:n}=i;if(t.selfRegisters||t.routes.length===0)return;let r=t.routes.find((w)=>Ot(w.path)==="/")??t.routes[0],f=n.get(r.portEnv);if(f===void 0)return;let c=[];for(let w of t.routes){if(w===r)continue;let u=n.get(w.portEnv);if(u===void 0)continue;c.push({from:Ot(w.path),to:`localhost:${u}`,stripPrefix:w.stripPrefix??!1})}let l={id:t.id,from:`localhost:${f}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:c.length>0?c:void 0,pid:i.handle?.pid};await this.writeEntry(l,this.registryDir,this.verbose),i.routeIds=[t.id];let y=this.now()+2000;while(this.now()<y&&!this.isHostRoutable(t.host))await Ol(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),W.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let n={};for(let[r,f]of Object.entries(Vi.env))if(typeof f==="string")n[r]=f;Object.assign(n,i.env);for(let[r,f]of t)n[r]=String(f);return n.RPX_SITE_HOST=i.host,n.RPX_SITE_URL=`https://${i.host}`,n}readLogTail(i,t=40){try{return dB(i.logPath,"utf8").split(`
|
|
186
186
|
`).slice(-t).join(`
|
|
187
|
-
`).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let n of t.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),
|
|
187
|
+
`).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let n of t.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),W.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let n=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof n.unref==="function")n.unref();await Promise.race([t.exited.catch(()=>{}),Ol(this.killGraceMs+500)]),clearTimeout(n)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,n]of this.sites){let r=n.site.idleTimeoutMs;if(r<=0)continue;let f=i-n.lastAccess;if((n.status==="ready"||i-n.startedAt>this.startupTimeoutMs)&&f>r)E("sites",`reaping ${t} (idle ${Math.round(f/1000)}s)`,this.verbose),await this.stop(t)}}list(){let i=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:i-t.startedAt,idleMs:i-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((i)=>this.stop(i)))}}function Ol(i){return new Promise((t)=>setTimeout(t,i))}async function im(i){let t=new AbortController,n=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${i}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(n)}}function tm(i){let t=nm();return({command:n,cwd:r,env:f,logPath:c})=>{let l=VB(c,"a");try{let y=DB("sh",["-c",n],{cwd:r,env:f,detached:!0,stdio:["ignore",l,l],...t?{uid:t.uid,gid:t.gid}:{}}),w=y.pid;if(w===void 0)throw Error("spawn returned no pid");let u=new Promise((h)=>{y.once("exit",($)=>{h($)}),y.once("error",()=>{h(null)})}).finally(()=>{try{N$(l)}catch{}});return E("sites",`spawned pid ${w}: sh -c ${n} (cwd ${r})`,i),{pid:w,exited:u,stop:(h="SIGTERM")=>{try{Vi.kill(-w,h)}catch{try{y.kill(h)}catch{}}}}}catch(y){try{N$(l)}catch{}throw y}}}function nm(){if(Vi.platform==="win32")return null;if(!(typeof Vi.getuid==="function"&&Vi.getuid()===0))return null;let t=Number.parseInt(Vi.env.SUDO_UID??"",10),n=Number.parseInt(Vi.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(n)||n<=0)return null;return{uid:t,gid:n}}function Un(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var rm=`
|
|
188
188
|
:root { color-scheme: light dark }
|
|
189
189
|
* { box-sizing: border-box }
|
|
190
190
|
body {
|
|
@@ -217,36 +217,36 @@ x-forwarded-host: ${f}\r
|
|
|
217
217
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
218
218
|
${n>0?`<meta http-equiv="refresh" content="${n}">`:""}
|
|
219
219
|
<title>${Un(i)}</title>
|
|
220
|
-
<style>${
|
|
220
|
+
<style>${rm}</style>
|
|
221
221
|
</head>
|
|
222
222
|
<body><main class="card">${t}</main></body>
|
|
223
|
-
</html>`}function
|
|
223
|
+
</html>`}function X$(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),n=i.logTail?`<pre>${Un(i.logTail)}</pre>`:"",r=`
|
|
224
224
|
<div class="row"><div class="spinner"></div><h1>Starting ${Un(i.host)}…</h1></div>
|
|
225
225
|
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
226
226
|
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
227
227
|
<p>Booting for ${t}s.</p>
|
|
228
|
-
${n}`;return new Response(W$(`Starting ${i.host}`,r,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function
|
|
228
|
+
${n}`;return new Response(W$(`Starting ${i.host}`,r,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function J$(i){let t=i.logTail?`<pre>${Un(i.logTail)}</pre>`:"<p>No output was captured.</p>",n=`
|
|
229
229
|
<div class="row"><div class="dot"></div><h1>${Un(i.host)} failed to start</h1></div>
|
|
230
230
|
<p>${Un(i.error)}</p>
|
|
231
231
|
${t}
|
|
232
|
-
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(W$(`${i.host} failed`,n,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as
|
|
233
|
-
`),c=[],l=0;while(l<f.length){let y=f[l];if(y.trim()===
|
|
232
|
+
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(W$(`${i.host} failed`,n,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as fm}from"node:child_process";import on from"node:fs";import cm from"node:os";import _$ from"node:path";import*as Gt from"node:process";import{promisify as lm}from"node:util";var vn=lm(fm);function F$(i){let t=i.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}var Pi=Gt.platform==="win32"?_$.join(Gt.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",I$="# rpx",ym="# Added by rpx",pn=new Set(["127.0.0.1","::1"]),Hl=!1;async function z$(i){if(Gt.platform==="win32")throw Error("Administrator privileges required on Windows");if(K$()){let{stdout:r}=await vn(i);return r}let t=ql(),n=i.replace(/'/g,"'\\''");try{if(t){let{stdout:r}=await vn(`echo '${t}' | sudo -S sh -c '${n}' 2>/dev/null`);return Hl=!0,r}if(Hl)try{let{stdout:r}=await vn(`sudo -n sh -c '${n}'`);return r}catch(r){E("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:r}=await vn(`sudo -n sh -c '${n}'`);return Hl=!0,r}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(r){throw Error(`Failed to execute sudo command: ${r.message}`)}}function ir(i){let t=i.indexOf("#"),n=(t===-1?i:i.slice(0,t)).trim();if(!n)return null;let r=t===-1?"":i.slice(t+1).trim(),[f,...c]=n.split(/\s+/);if(!f||c.length===0)return null;let l=/^rpx(?::pid=(\d+))?$/.exec(r);return{address:f,names:c,comment:r,rpxPid:l?.[1]?Number.parseInt(l[1],10):null,rpxManaged:l!==null}}function Q$(i,t){let n=ir(i);return n!==null&&pn.has(n.address)&&n.names.includes(t)}function wm(i,t){let n=new Set(t),r=new Set,f=i.split(`
|
|
233
|
+
`),c=[],l=0;while(l<f.length){let y=f[l];if(y.trim()===ym){let u=[],h=l+1;while(h<f.length){let A=f[h];if(A.trim()===""||A.trim().startsWith("#"))break;u.push(A),h++}let $=u.filter((A)=>{let T=ir(A),B=T!==null&&pn.has(T.address)&&T.names.some((e)=>n.has(e));if(B){for(let e of T.names)if(n.has(e))r.add(e)}return!B});if($.length>0||u.length===0)c.push(y,...$);l=h;continue}let w=ir(y);if(w?.rpxManaged&&pn.has(w.address)&&w.names.some((u)=>n.has(u))){for(let u of w.names)if(n.has(u))r.add(u);l++;continue}c.push(y),l++}while(c.length>0&&c[c.length-1].trim()==="")c.pop();return{content:`${c.join(`
|
|
234
234
|
`)}
|
|
235
|
-
`,removed:[...r]}}function
|
|
235
|
+
`,removed:[...r]}}function um(i,t){let n=[],r=new Set,f=[];for(let c of i.split(`
|
|
236
236
|
`)){let l=ir(c);if(l?.rpxManaged&&l.rpxPid!==null&&pn.has(l.address)&&!t(l.rpxPid)){n.push(...l.names),r.add(l.rpxPid);continue}f.push(c)}while(f.length>0&&f[f.length-1].trim()==="")f.pop();return{content:`${f.join(`
|
|
237
237
|
`)}
|
|
238
|
-
`,removed:n,stalePids:[...r]}}async function
|
|
239
|
-
`),l=n.filter((u)=>!c.some((h)=>
|
|
240
|
-
127.0.0.1 ${u} ${
|
|
241
|
-
::1 ${u} ${
|
|
242
|
-
`);try{await gl(f+w,t),console.log(` Hosts updated: ${l.join(", ")}`)}catch(u){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),l.forEach((h)=>{console.log(` 127.0.0.1 ${h}`),console.log(` ::1 ${h}`)}),console.log(` Or run: sudo nano ${Pi}`)}}catch(f){
|
|
243
|
-
`);return i.map((f)=>r.some((c)=>
|
|
244
|
-
`)){let f=ir(r);if(f?.rpxManaged&&f.rpxPid!==null&&pn.has(f.address)&&!i(f.rpxPid))n.push(...f.names)}return[...new Set(n)]}async function tr(i={}){let t=i.isAlive??Ui,n;try{n=await
|
|
245
|
-
`)}finally{await r.close()}return t}catch(r){if(r.code!=="EEXIST")throw r}let n=await
|
|
246
|
-
`),u.stdin.end();u.unref();let A=vf(i),T=Date.now()+15000;while(Date.now()<T){if(h)throw h;let
|
|
247
|
-
`):A.ca}:null,
|
|
248
|
-
`,"utf8")}async function
|
|
238
|
+
`,removed:n,stalePids:[...r]}}async function sl(i){try{return await on.promises.readFile(Pi,"utf-8")}catch{return E("hosts","Reading hosts file requires elevated permissions, using sudo",i),z$(`cat "${Pi}"`)}}async function gl(i,t){let n=_$.join(cm.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await on.promises.writeFile(n,i,"utf8"),await z$(`cat "${n}" | tee "${Pi}" > /dev/null`)}finally{await on.promises.unlink(n).catch((r)=>{E("hosts",`Failed to remove temporary file: ${r}`,t)})}}async function sN(i,t){let n=i.filter((f)=>!F$(f)),r=i.filter((f)=>F$(f));if(r.length>0)E("hosts",`Skipping /etc/hosts for loopback dev names: ${r.join(", ")}`,t);if(n.length===0)return;E("hosts",`Adding hosts: ${n.join(", ")}`,t),E("hosts",`Using hosts file at: ${Pi}`,t);try{let f;try{f=await sl(t)}catch(u){throw console.log(" Could not read hosts file — skipping hosts setup"),E("hosts",`sudo read also failed: ${u}`,t),Error(`Cannot read hosts file: ${u}`)}let c=f.split(`
|
|
239
|
+
`),l=n.filter((u)=>!c.some((h)=>Q$(h,u)));if(l.length===0){E("hosts","All hosts already exist in hosts file",t);return}let y=Gt.pid,w=l.map((u)=>`
|
|
240
|
+
127.0.0.1 ${u} ${I$}:pid=${y}
|
|
241
|
+
::1 ${u} ${I$}:pid=${y}`).join(`
|
|
242
|
+
`);try{await gl(f+w,t),console.log(` Hosts updated: ${l.join(", ")}`)}catch(u){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),l.forEach((h)=>{console.log(` 127.0.0.1 ${h}`),console.log(` ::1 ${h}`)}),console.log(` Or run: sudo nano ${Pi}`)}}catch(f){E("hosts",`Failed to manage hosts file: ${f.message}`,t)}}async function gN(i,t){E("hosts",`Removing hosts: ${i.join(", ")}`,t);try{let n;try{n=await sl(t)}catch(c){throw E("hosts",`sudo read also failed: ${c}`,t),Error(`Cannot read hosts file: ${c}`)}let{content:r,removed:f}=wm(n,i);if(f.length===0){E("hosts","No matching rpx-managed hosts found to remove",t);return}try{await gl(r,t),E("hosts",`Hosts removed successfully: ${f.join(", ")}`,t)}catch(c){E("hosts","Could not clean up hosts file automatically",t)}}catch(n){E("hosts",`Failed to clean up hosts file: ${n.message}`,t)}}async function LN(i,t){E("hosts",`Checking hosts: ${i}`,t);let n;try{n=await on.promises.readFile(Pi,"utf-8")}catch(f){E("hosts",`Error reading hosts file: ${f}`,t);try{let c=ql(),l;if(c)l=`echo '${c}' | sudo -S cat "${Pi}" 2>/dev/null`;else l=`sudo -n cat "${Pi}" 2>/dev/null || cat "${Pi}" 2>/dev/null || echo ""`;let{stdout:y}=await vn(l);n=y}catch(c){return E("hosts",`Cannot read hosts file, assuming entries don't exist: ${c}`,t),i.map(()=>!1)}}let r=n.split(`
|
|
243
|
+
`);return i.map((f)=>r.some((c)=>Q$(c,f)))}async function xN(i=Ui){let t;try{t=await on.promises.readFile(Pi,"utf-8")}catch{return[]}let n=[];for(let r of t.split(`
|
|
244
|
+
`)){let f=ir(r);if(f?.rpxManaged&&f.rpxPid!==null&&pn.has(f.address)&&!i(f.rpxPid))n.push(...f.names)}return[...new Set(n)]}async function tr(i={}){let t=i.isAlive??Ui,n;try{n=await sl(i.verbose)}catch(l){return E("hosts",`stale hosts GC: cannot read hosts file: ${l}`,i.verbose),[]}let{content:r,removed:f,stalePids:c}=um(n,t);if(f.length===0)return[];try{return await gl(r,i.verbose),E("hosts",`stale hosts GC: removed ${f.join(", ")} (dead pid(s): ${c.join(", ")})`,i.verbose),[...new Set(f)]}catch(l){return E("hosts",`stale hosts GC: write failed: ${l}`,i.verbose),[]}}var hm=5000;function ji(){return Zi.join(s$(),".stacks","rpx")}function vf(i=ji()){return Zi.join(i,"daemon.pid")}async function Rn(i=ji()){try{let t=await Ti.readFile(vf(i),"utf8"),n=Number.parseInt(t.trim(),10);if(!Number.isFinite(n)||n<=0)return null;return n}catch(t){if(t.code==="ENOENT")return null;throw t}}async function $m(i=ji()){let t=await Rn(i);return t!==null&&Ui(t)}async function g$(i=ji()){await Ti.mkdir(i,{recursive:!0});let t=vf(i);while(!0){try{let r=await Ti.open(t,"wx");try{await r.write(`${C.pid}
|
|
245
|
+
`)}finally{await r.close()}return t}catch(r){if(r.code!=="EEXIST")throw r}let n=await Rn(i);if(n!==null&&Ui(n))throw Error(`rpx daemon already running (pid=${n})`);await Ti.unlink(t).catch(()=>{})}}async function jn(i=ji()){await Ti.unlink(vf(i)).catch(()=>{})}var Pf=new Map;function Zf(i){for(let[t,n]of Pf)if(!i.has(t))Yl(n),Pf.delete(t)}function Am(i,t){let n=Gh(t??"localhost:1");if(i.upstreams.length!==n.length)return!1;return i.upstreams.every((r,f)=>r.url===n[f])}function L$(i){let t=i.cleanUrls??!1,n=Ot(i.path),r=kh(i.auth);if(i.static)return{static:t$(i.static,t),cleanUrls:t,basePath:n,auth:r};let f=i.from??"localhost:1",c=Hh(f),l=new URL(c.startsWith("http")?c:`http://${c}`),y=Pf.get(i.id);if(y&&!Am(y,f))Yl(y),y=void 0;if(!y)y=qh(f,i.loadBalancer),gh(y),Pf.set(i.id,y);return{sourceHost:l.host,upstreamPool:y,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:n,auth:r}}function Tm(i){return i.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??i[0]??"rpx.localhost"}async function bf(i,t,n=[],r=!1){let f=await Et(t,i.verbose),c=[...new Set([...f.map((h)=>h.to).filter(Boolean),...n])],l=Tm(c),y=[...new Set([l,...c,"rpx.localhost"])],w=zh(c,l,i.verbose);if(typeof i.https==="object"&&typeof w.https==="object")w.https={...w.https,...i.https};let u=await El(w);if(u&&(r||!fl($l,y)))E("daemon",`regenerating shared cert for host(s): ${y.join(", ")}`,i.verbose),Tl(),u=null;if(!u)E("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await Mh({...w,forceRegenerate:!0}),u=await El(w);if(!u)throw Error("failed to bootstrap TLS for rpx daemon");return u}async function Em(i,t,n,r){let f=C.env.SUDO_PASSWORD,c=C.env.HOME??s$(),l=[C.execPath,...C.argv.slice(1)],y=[`HOME=${c}`,`PATH=${C.env.PATH??""}`];if(r)y.push("RPX_VERBOSE=1");for(let[B,e]of Object.entries(C.env))if(e!==void 0&&B!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(B))y.push(`${B}=${e}`);let w=f?["-S","-p","","env",...y,...l]:["-n","env",...y,...l];E("daemon",`elevating daemon via sudo for privileged ports ${t}/${n}`,r);let u=q$("sudo",w,{detached:!0,stdio:["pipe","ignore","ignore"]}),h=null,$=null;if(u.once("error",(B)=>{h=B}),u.once("exit",(B)=>{$=B??0}),f&&u.stdin)u.stdin.write(`${f}
|
|
246
|
+
`),u.stdin.end();u.unref();let A=vf(i),T=Date.now()+15000;while(Date.now()<T){if(h)throw h;let B=await Rn(i);if(B!==null&&Ui(B)){if(r)W.success(`rpx daemon elevated to root (pid=${B}, https on :${t})`);return{httpsPort:t,httpPort:n,pidPath:A,done:Promise.resolve(),stop:async()=>{try{C.kill(B,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if($!==null&&$!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${$}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((e)=>setTimeout(e,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${i})`)}var M$=!1;function Ll(){if(M$)return;M$=!0,C.on("uncaughtException",(i)=>{W.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),C.on("unhandledRejection",(i)=>{W.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function x$(i,t,n){let r;try{r=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let f=(i.headers.get("host")??r.hostname).split(":")[0];if(r.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let c=t.challengeStore.handlePath(r.pathname);if(c!==void 0)return new Response(c,{status:200,headers:{"content-type":"text/plain"}})}if(n){let c=h$(n,r.pathname);if(c!=null)return new Response(c,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(f))t.ensureCert(f).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${f}${r.pathname}${r.search}`}})}async function $S(i={}){Ll();let t=i.verbose??!1,n=i.rpxDir??ji(),r=i.registryDir??Zi.join(n,"registry.d"),f=i.httpsPort??443,c=i.httpPort??80,l=i.hostname??"0.0.0.0",y=i.gcIntervalMs??hm;if(C.env.RPX_DAEMON_WORKER==="1")return Bm({rpxDir:C.env.RPX_WORKER_RPXDIR??n,registryDir:C.env.RPX_WORKER_REGISTRYDIR??r,httpsPort:Number.parseInt(C.env.RPX_WORKER_HTTPSPORT??"",10)||f,hostname:C.env.RPX_WORKER_HOSTNAME??l,verbose:C.env.RPX_WORKER_VERBOSE==="1"||t});let w=f>0&&f<1024||c>0&&c<1024,u=typeof C.getuid==="function"&&C.getuid()===0;if(C.platform!=="win32"&&w&&!u)return Em(n,f,c,t);let h=Math.max(1,i.workers??(Number.parseInt(C.env.RPX_WORKERS??"",10)||1));if(h>1){if(i.onDemandSites?.enabled)W.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return mm(i,{rpxDir:n,registryDir:r,httpsPort:f,httpPort:c,hostname:l,verbose:t,gcIntervalMs:y,workers:h})}let $=await g$(n),A=new Map,T=(U,I)=>Nl(A,U,I);function B(U){A=Rl(U.map((Di)=>({host:Di.to,path:Di.path,route:L$(Di)}))),Zf(new Set(U.map((Di)=>Di.id)));let I=Array.from(A.keys());E("daemon",`routing table now covers ${I.length} host(s): ${I.join(", ")||"<empty>"}`,t)}await Pn(r,t).catch((U)=>{E("daemon",`initial gc failed: ${U}`,t)}),await tr({verbose:t}).catch((U)=>{E("daemon",`stale hosts GC on start failed: ${U}`,t)});let e=await Et(r,t);B(e),await Nn({rpxDir:n,verbose:t}).catch((U)=>{E("daemon",`DNS reconcile on start failed: ${U}`,t)}),await nr(e,{rpxDir:n,verbose:t,ownerPid:C.pid}).catch((U)=>{E("daemon",`DNS setup on start failed: ${U}`,t)});let Y=[];if(i.productionCerts){if(Y=await Wl(i.productionCerts,t),t&&Y.length>0)W.info(`SNI: serving ${Y.length} real cert(s): ${Y.map((U)=>U.serverName).join(", ")}`)}let m=new Set,j=null,N;if(i.onDemandSites?.enabled){if(j=new Gl({resolver:Il(i.onDemandSites),registryDir:r,rpxDir:n,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(U)=>al(A,U)!==void 0,onSiteActivating:(U)=>{It(U)}}),N=async(U)=>{let I=await j.onRequest(U);switch(I.kind){case"ready":return{retry:!0};case"starting":return X$({host:I.host,sinceMs:I.sinceMs,logTail:I.logTail});case"failed":return J$({host:I.host,error:I.error,logTail:I.logTail});case"unknown":default:return}},t)W.info("rpx: on-demand sites enabled")}let S=Cl(T,t,N),F=Ul(t),X=null;if(Y.length===0)X=await bf(i,r);let J=i.onDemandTls,v=J?.enabled?new xf({config:J,certsDir:J.certsDir??i.productionCerts?.certsDir??Zi.join(n,"on-demand-certs"),initial:Y,verbose:t,onCertAdded:(U)=>{if(Xl()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",t),setTimeout(()=>C.kill(C.pid,"SIGTERM"),10).unref();else st(U)}}):null;function Mi(U){if(U.length>0)return bn(U.map((I)=>({serverName:I.serverName,cert:I.cert,key:I.key})));return bn({key:X.key,cert:X.cert,ca:X.ca,requestCert:!1,rejectUnauthorized:!1})}function Ht(U){return Bun.serve({port:f,hostname:l,reusePort:H$(),tls:Mi(U),fetch(I,Di){return S(I,Di)},websocket:F,error(I){return E("daemon",`https server error: ${I}`,t),new Response(`Server Error: ${I.message}`,{status:500})}})}let Xt=(U)=>[...new Set(U.map((I)=>I.to).filter(Boolean))],qt=(U)=>{if(!X)return Y;return _h([...Xt(U),...m,"rpx.localhost"],X)},Yt=Ht(v?v.sniEntries():Y.length>0?Y:qt(e)),Jt=null,Ft=!1;async function st(U){if(di)return;if(Jt=U,Ft)return;Ft=!0;try{while(!di&&Jt){let I=Jt;Jt=null,E("daemon",`rebuilding :443 with ${I.length} SNI cert(s)`,t),Yt.stop(!1);let Di,f0=!1,ol=60,f1=500;for(let c0=0;!di&&!f0;c0++)try{Yt=Ht(I),f0=!0;break}catch(c1){if(Di=c1,c0>=ol)break;await new Promise((l1)=>setTimeout(l1,Math.min(25*2**Math.min(c0,4),f1)))}if(!f0)W.error(`rpx: CRITICAL — could not rebind :443 after ${ol} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Di?.message}`)}}finally{Ft=!1}}let vi=null;if(c>0)vi=Bun.serve({port:c,hostname:l,fetch(U){return x$(U,v,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)W.success(`rpx daemon listening on https://${l}:${f}${vi?` (http→https on :${c})`:""}`),W.info(`pid file: ${$}`),W.info(`registry: ${r}`);async function K(U){if(di||Y.length>0||v||!X)return;try{X=await bf(i,r,[...m]),await st(qt(U))}catch(I){E("daemon",`TLS sync on registry change failed: ${I}`,t)}}async function It(U){if(di||Y.length>0||v||!X||!U)return;if(m.has(U))return;m.add(U);try{X=await bf(i,r,[...m],!0);let I=await Et(r,t);await st(qt(I))}catch(I){E("daemon",`dev cert refresh for ${U} failed: ${I}`,t)}}let n0=Df((U)=>{B(U),K(U),nr(U,{rpxDir:n,verbose:t,ownerPid:C.pid}).catch((I)=>{E("daemon",`DNS sync on registry change failed: ${I}`,t)})},{dir:r,verbose:t}),gt=setInterval(()=>{Pn(r,t).then((U)=>{if(U>0)E("daemon",`gc reaped ${U} stale entries`,t)}).catch((U)=>{E("daemon",`periodic gc failed: ${U}`,t)}),tr({verbose:t}).then((U)=>{if(U.length>0)E("daemon",`gc reaped stale hosts entries: ${U.join(", ")}`,t)}).catch((U)=>{E("daemon",`periodic hosts gc failed: ${U}`,t)})},y);if(typeof gt.unref==="function")gt.unref();let di=!1,Sn,Lt=new Promise((U)=>{Sn=U});async function r0(){if(di)return Lt;if(di=!0,clearInterval(gt),n0.close(),await j?.stopAll().catch((U)=>{E("daemon",`site supervisor stopAll failed: ${U}`,t)}),Yt.stop(!1),vi?.stop(!1),await an({rpxDir:n,verbose:t}).catch((U)=>{E("daemon",`DNS teardown failed: ${U}`,t)}),Zf(new Set),await jn(n),t)W.info("rpx daemon stopped");return Sn(),Lt}let vl=(U)=>{E("daemon",`received ${U}, shutting down`,t),r0().catch(()=>{})};return C.once("SIGINT",vl),C.once("SIGTERM",vl),{stop:r0,done:Lt,httpsPort:typeof Yt.port==="number"?Yt.port:f,httpPort:vi&&typeof vi.port==="number"?vi.port:c,pidPath:$,ensureCert:(U)=>v?v.ensureCert(U):Promise.resolve(!1),listSites:()=>j?.list()??[]}}function xl(i){return Zi.join(i,"cluster-sni.json")}async function O$(i,t,n){let r=xl(i),f=`${r}.${C.pid}.tmp`;await Ti.writeFile(f,JSON.stringify({sni:t,dev:n}),"utf8"),await Ti.rename(f,r)}async function G$(i){try{return JSON.parse(await Ti.readFile(xl(i),"utf8"))}catch{return{sni:[],dev:null}}}function em(i){if(i.sni.length>0)return bn(i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key})));if(i.dev)return bn({key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function Ym(){let i=C.execPath,t=C.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let n=Zi.basename(i).toLowerCase();if((n==="bun"||n==="node"||n.startsWith("bun-"))&&C.argv[1])return[i,C.argv[1],"daemon:start"];return[i,"daemon:start"]}async function Bm(i){Ll();let{rpxDir:t,registryDir:n,httpsPort:r,hostname:f,verbose:c}=i,l=new Map,y=(X,J)=>Nl(l,X,J),w=(X)=>{l=Rl(X.map((J)=>({host:J.to,path:J.path,route:L$(J)}))),Zf(new Set(X.map((J)=>J.id)))};w(await Et(n,c));let u=Cl(y,c),h=Ul(c),$=!1,A=(X)=>Bun.serve({port:r,hostname:f,reusePort:!0,tls:em(X),fetch(J,v){return u(J,v)},websocket:h,error(J){return E("daemon",`worker https error: ${J}`,c),new Response(`Server Error: ${J.message}`,{status:500})}}),T=A(await G$(t));async function B(){if($)return;let X=await G$(t),J=null;for(let Mi=0;Mi<20&&!$;Mi++)try{J=A(X);break}catch{await new Promise((Ht)=>setTimeout(Ht,25))}if(!J){E("daemon","worker reloadTls: could not bind new listener; keeping current",c);return}let v=T;T=J,v.stop(!1)}let e=Df((X)=>w(X),{dir:n,verbose:c}),Y=()=>{B().catch(()=>{})};C.on("SIGHUP",Y);let m=()=>{let X=C.removeListener??C.off;if(typeof X==="function")X.call(C,"SIGHUP",Y)},j,N=new Promise((X)=>{j=X});async function S(){if($)return N;return $=!0,m(),e.close(),T.stop(!1),Zf(new Set),j(),N}let F=()=>{S().then(()=>C.exit(0)).catch(()=>C.exit(0))};if(C.once("SIGTERM",F),C.once("SIGINT",F),c)W.success(`rpx worker (pid ${C.pid}) serving :${r}`);return{stop:S,done:N,httpsPort:typeof T.port==="number"?T.port:r,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function mm(i,t){Ll();let{rpxDir:n,registryDir:r,httpsPort:f,httpPort:c,hostname:l,verbose:y,gcIntervalMs:w,workers:u}=t,h=await g$(n),$=[];if(i.productionCerts)$=await Wl(i.productionCerts,y);let A=null;if($.length===0)A=await bf(i,r);let T=A?{key:A.key,cert:A.cert,ca:Array.isArray(A.ca)?A.ca.join(`
|
|
247
|
+
`):A.ca}:null,B=!1,e=[];function Y(K){for(let It of e)try{It.kill(K)}catch{}}async function m(K){await O$(n,K,T),Y("SIGHUP")}let j=i.onDemandTls,N=j?.enabled?new xf({config:j,certsDir:j.certsDir??i.productionCerts?.certsDir??Zi.join(n,"on-demand-certs"),initial:$,verbose:y,onCertAdded:(K)=>{if(Xl()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",y),setTimeout(()=>C.kill(C.pid,"SIGTERM"),10).unref();else m(K)}}):null;await O$(n,N?N.sniEntries():$,T);let S=await Et(r,y);await Nn({rpxDir:n,verbose:y}).catch((K)=>{E("daemon",`DNS reconcile on start failed: ${K}`,y)}),await nr(S,{rpxDir:n,verbose:y,ownerPid:C.pid}).catch((K)=>{E("daemon",`DNS setup on start failed: ${K}`,y)}),await Pn(r,y).catch(()=>{}),await tr({verbose:y}).catch(()=>{});let F=Df((K)=>{nr(K,{rpxDir:n,verbose:y,ownerPid:C.pid}).catch((It)=>{E("daemon",`DNS sync on registry change failed: ${It}`,y)})},{dir:r,verbose:y}),X=setInterval(()=>{Pn(r,y).catch(()=>{}),tr({verbose:y}).catch(()=>{})},w);X.unref?.();let J=null;if(c>0)J=Bun.serve({port:c,hostname:l,fetch(K){return x$(K,N,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let v=10,Mi=60000,Ht=30000,Xt=0,qt=Date.now();function Yt(){if(B)return;let K={...C.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:n,RPX_WORKER_REGISTRYDIR:r,RPX_WORKER_HTTPSPORT:String(f),RPX_WORKER_HOSTNAME:l,RPX_WORKER_VERBOSE:y?"1":"0"},It=Bun.spawn(Ym(),{env:K,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(n0,gt){if(B)return;let di=e.indexOf(n0);if(di!==-1)e.splice(di,1);let Sn=Date.now();if(Sn-qt>Mi)qt=Sn,Xt=0;if(Xt++,Xt>v){W.error(`rpx: worker keeps exiting (code ${gt}); giving up after ${v} restarts in ${Math.round(Mi/1000)}s`);return}let Lt=Math.min(Ht,100*2**Math.min(Xt,8));E("daemon",`worker exited (code ${gt}); respawning in ${Lt}ms (restart ${Xt}/${v})`,y),setTimeout(Yt,Lt).unref?.()}});e.push(It)}for(let K=0;K<u;K++)Yt();if(y)W.success(`rpx coordinator listening on https://${l}:${f} via ${u} worker(s)${J?` (http→https on :${c})`:""}`),W.info(`pid file: ${h}`);let Jt,Ft=new Promise((K)=>{Jt=K});async function st(){if(B)return Ft;if(B=!0,clearInterval(X),F.close(),J?.stop(!1),Y("SIGTERM"),await Promise.race([Promise.all(e.map((K)=>K.exited)),new Promise((K)=>setTimeout(K,3000))]),Y("SIGKILL"),await an({rpxDir:n,verbose:y}).catch((K)=>{E("daemon",`DNS teardown failed: ${K}`,y)}),await jn(n),await Ti.unlink(xl(n)).catch(()=>{}),y)W.info("rpx coordinator stopped");return Jt(),Ft}let vi=(K)=>{E("daemon",`coordinator received ${K}, shutting down`,y),st().catch(()=>{})};return C.once("SIGINT",vi),C.once("SIGTERM",vi),{stop:st,done:Ft,httpsPort:f,httpPort:c,pidPath:h,ensureCert:(K)=>N?N.ensureCert(K):Promise.resolve(!1),listSites:()=>[]}}function Cm(){let i=C.execPath,t=Zi.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&C.argv[1])return[i,C.argv[1],"daemon:start"];return[i,"daemon:start"]}async function AS(i={}){let t=i.rpxDir??ji(),n=i.verbose??!1;await Nn({rpxDir:t,verbose:n}).catch((h)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${h}`,n)});let r=await Rn(t);if(r!==null&&Ui(r))return E("daemon",`ensureDaemonRunning: already running pid=${r}`,n),{pid:r,spawned:!1};if(r!==null)E("daemon",`ensureDaemonRunning: clearing stale pid=${r}`,n),await jn(t);await Ti.mkdir(t,{recursive:!0});let f=i.spawnCommand??Cm();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${f.join(" ")}`,n);let c=q$(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:i.spawnCwd??C.cwd(),env:i.spawnEnv?{...C.env,...i.spawnEnv}:C.env});c.unref();let l=null;c.once("error",(h)=>{l=h});let y=i.startupTimeoutMs??5000,w=i.pollIntervalMs??50,u=Date.now()+y;while(Date.now()<u){if(l)throw l;let h=await Rn(t);if(h!==null&&Ui(h))return E("daemon",`daemon registered with pid=${h}`,n),{pid:h,spawned:!0};await new Promise(($)=>setTimeout($,w))}if(l)throw l;throw Error(`rpx daemon failed to start within ${y}ms (rpxDir=${t})`)}async function TS(i={}){let t=i.rpxDir??ji(),n=i.verbose??!1,r=i.timeoutMs??5000,f=i.pollIntervalMs??50,c=i.forceAfterTimeout??!0,l=await Rn(t);if(l===null||!Ui(l)){if(l!==null)await jn(t);return await Nn({rpxDir:t,verbose:n}).catch(()=>{}),{stopped:!1,pid:l,forced:!1}}try{C.kill(l,"SIGTERM")}catch(w){let u=w.code;if(u==="ESRCH")return await jn(t),{stopped:!1,pid:l,forced:!1};if(u==="EPERM")at(`kill -TERM ${l}`);else throw w}let y=Date.now()+r;while(Date.now()<y){if(!Ui(l))return E("daemon",`daemon pid=${l} stopped cleanly`,n),{stopped:!0,pid:l,forced:!1};await new Promise((w)=>setTimeout(w,f))}if(!c)throw Error(`rpx daemon (pid=${l}) did not exit within ${r}ms`);E("daemon",`daemon pid=${l} did not exit, escalating to SIGKILL`,n);try{C.kill(l,"SIGKILL")}catch(w){let u=w.code;if(u==="EPERM")at(`kill -KILL ${l}`);else if(u!=="ESRCH")throw w}return await jn(t),await an({rpxDir:t,verbose:n}).catch((w)=>{E("daemon",`DNS teardown after SIGKILL: ${w}`,n)}),{stopped:!0,pid:l,forced:!0}}async function ES(i={}){let t=i.rpxDir??ji();if(await $m(t))return;await Nn({rpxDir:t,verbose:i.verbose})}import*as Wt from"node:fs/promises";import{homedir as Um}from"node:os";import*as kl from"node:path";var of=1,jm="dns-state.json",k$=["com","test","dev","app","page","local","localhost","example","invalid"];function V$(){return kl.join(Um(),".stacks","rpx")}function Vl(i=V$()){return kl.join(i,jm)}async function pf(i=V$()){try{let t=await Wt.readFile(Vl(i),"utf8"),n=JSON.parse(t);if(n.version!==of||!Array.isArray(n.resolvers))return null;return{version:of,resolvers:n.resolvers.filter((r)=>typeof r==="string"),domains:Array.isArray(n.domains)?n.domains.filter((r)=>typeof r==="string"):[],ownerPid:typeof n.ownerPid==="number"?n.ownerPid:null,updatedAt:typeof n.updatedAt==="string"?n.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function d$(i,t){await Wt.mkdir(i,{recursive:!0}),await Wt.writeFile(Vl(i),`${JSON.stringify(t,null,2)}
|
|
248
|
+
`,"utf8")}async function dl(i){await Wt.rm(Vl(i),{force:!0})}function D$(i){let t=i.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function Rm(i){let t=D$(i);if(!t)return null;let n=t.split(".");if(n.length<2)return null;return n.slice(-2).join(".")}function Dl(i){let t=new Set;for(let n of i){let r=Rm(n);if(r)t.add(r)}return Array.from(t).sort()}function bl(i){let t=new Set;for(let n of i){let r=D$(n);if(r)t.add(r)}return Array.from(t).sort()}var t0=15353,am="# managed-by: rpx",v$="/etc/resolver",Ri=null,i0=new Set;function o$(i){return{id:i.readUInt16BE(0),flags:i.readUInt16BE(2),qdcount:i.readUInt16BE(4),ancount:i.readUInt16BE(6),nscount:i.readUInt16BE(8),arcount:i.readUInt16BE(10)}}function p$(i,t,n=0){let r=[],f=t,c=0;while(!0){if(f>=i.length||++c>128)break;let l=i[f];if(l===0){f++;break}if((l&192)===192){if(f+1>=i.length||n>=10)break;let y=i.readUInt16BE(f)&16383,{name:w}=p$(i,y,n+1);if(w)r.push(w);f+=2;break}if(f++,f+l>i.length)break;r.push(i.subarray(f,f+l).toString("ascii")),f+=l}return{name:r.join("."),newOffset:f}}function Nm(i,t){let{name:n,newOffset:r}=p$(i,t),f=i.readUInt16BE(r),c=i.readUInt16BE(r+2);return{question:{name:n,type:f,class:c},newOffset:r+4}}function rr(i){let t=i.split("."),n=[];for(let r of t)n.push(Buffer.from([r.length])),n.push(Buffer.from(r,"ascii"));return n.push(Buffer.from([0])),Buffer.concat(n)}function Sm(i,t,n){let r=[],f=Buffer.alloc(12);f.writeUInt16BE(i,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),r.push(f),r.push(rr(t.name));let c=Buffer.alloc(4);c.writeUInt16BE(t.type,0),c.writeUInt16BE(t.class,2),r.push(c),r.push(rr(t.name));let l=Buffer.alloc(10);if(l.writeUInt16BE(t.type,0),l.writeUInt16BE(1,2),l.writeUInt32BE(300,4),t.type===1){l.writeUInt16BE(4,8),r.push(l);let y=n.split(".").map((w)=>Number.parseInt(w,10));r.push(Buffer.from(y))}else if(t.type===28)l.writeUInt16BE(16,8),r.push(l),r.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,rr(t.name),c]);return Buffer.concat(r)}function Wm(i,t){let n=[],r=Buffer.alloc(12);r.writeUInt16BE(i,0),r.writeUInt16BE(33155,2),r.writeUInt16BE(1,4),r.writeUInt16BE(0,6),r.writeUInt16BE(0,8),r.writeUInt16BE(0,10),n.push(r),n.push(rr(t.name));let f=Buffer.alloc(4);return f.writeUInt16BE(t.type,0),f.writeUInt16BE(t.class,2),n.push(f),Buffer.concat(n)}async function Xm(i,t){if(et.platform!=="darwin")return!1;let n=bl(i);if(n.length===0)return!1;if(Ri){for(let r of n)i0.add(r);return E("dns","DNS server already running — merged domains",t),!0}return i0=new Set(n),new Promise((r)=>{Ri=b$.createSocket("udp4"),Ri.on("error",(f)=>{E("dns",`DNS server error: ${f.message}`,t),Ri?.close(),Ri=null,r(!1)}),Ri.on("message",(f,c)=>{try{let l=o$(f),{question:y}=Nm(f,12);E("dns",`Query for ${y.name} type ${y.type} from ${c.address}`,t);let w=y.name.toLowerCase(),u=!1;for(let $ of i0)if(w===$||w.endsWith(`.${$}`)){u=!0;break}let h;if(u&&(y.type===1||y.type===28))h=Sm(l.id,y,"127.0.0.1"),E("dns",`Responding with localhost for ${y.name}`,t);else h=Wm(l.id,y),E("dns",`NXDOMAIN for ${y.name}`,t);Ri?.send(h,c.port,c.address)}catch(l){E("dns",`Error processing DNS query: ${l}`,t)}}),Ri.on("listening",()=>{let f=Ri?.address();E("dns",`DNS server listening on ${f?.address}:${f?.port}`,t),r(!0)});try{Ri.bind(t0,"127.0.0.1")}catch(f){E("dns",`Failed to bind DNS server: ${f}`,t),r(!1)}})}function i1(i){if(Ri)E("dns","Stopping DNS server",i),Ri.close(),Ri=null,i0=new Set}function aS(){return Ri!==null}async function Jm(i,t=500){let n=i.trim().toLowerCase().replace(/\.$/,"");if(!n)return!1;return new Promise((r)=>{let f=b$.createSocket("udp4"),c=setTimeout(()=>{f.close(),r(!1)},t);f.on("message",(y)=>{clearTimeout(c),f.close();try{let w=o$(y);r(w.ancount>0)}catch{r(!1)}}),f.on("error",()=>{clearTimeout(c),f.close(),r(!1)});let l=Fm(n,1);f.send(l,t0,"127.0.0.1",(y)=>{if(y)clearTimeout(c),f.close(),r(!1)})})}function Fm(i,t){let n=Buffer.alloc(12);n.writeUInt16BE(1,0),n.writeUInt16BE(256,2),n.writeUInt16BE(1,4);let r=Buffer.concat([rr(i),Buffer.from([0,t,0,1])]);return Buffer.concat([n,r])}function Im(){return`${am}
|
|
249
249
|
nameserver 127.0.0.1
|
|
250
250
|
port ${t0}
|
|
251
|
-
`}function fr(i){return
|
|
252
|
-
export{
|
|
251
|
+
`}function fr(i){return Z$.join(v$,i)}function Km(i){return i.includes("127.0.0.1")&&i.includes(String(t0))}async function _m(i){try{return await P$.readFile(fr(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function Pl(i){if(et.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:n,isProcessElevated:r}=await import("./chunk-bvq3wmhm.js");if(!r()&&!n()){E("dns","Cannot flush DNS cache without SUDO_PASSWORD",i);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),E("dns","DNS cache flushed",i)}catch(f){E("dns",`Could not flush DNS cache: ${f}`,i)}}function t1(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function zm(i,t){t1(i);let{execSudoSync:n}=await import("./chunk-bvq3wmhm.js"),r=Im().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${v$} && printf "%b" "${r}" > ${fr(i)}'`;n(f),E("dns",`Created ${fr(i)}`,t)}async function Qm(i,t){t1(i);let{execSudoSync:n}=await import("./chunk-bvq3wmhm.js");n(`rm -f ${fr(i)}`),E("dns",`Removed ${fr(i)}`,t)}async function NS(i,t){return r1({domains:t??[],verbose:i})}async function Mm(i,t){if(et.platform!=="darwin")return!0;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-bvq3wmhm.js");if(!r()&&!n())return E("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let f of i)await zm(f,t);return await Pl(t),!0}catch(f){return E("dns",`Failed to create resolver file: ${f}`,t),!1}}async function Zl(i,t){if(et.platform!=="darwin")return;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-bvq3wmhm.js");if(!r()&&!n())return;try{for(let f of i)await Qm(f,t);await Pl(t)}catch(f){E("dns",`Failed to remove resolver files: ${f}`,t)}}async function n1(i){if(et.platform!=="darwin")return[];let t=[];for(let n of k$){let r=await _m(n);if(r&&Km(r))await Zl([n],i),t.push(n)}return t}async function r1(i){let t=i.rpxDir??ji(),n=bl(i.domains);if(n.length===0)return!1;let r=Dl(n),f=await Xm(n,i.verbose);if(!f){let y=n[0];if(y&&await Jm(y))f=!0;else E("dns","Dev DNS server not available on 127.0.0.1:15353",i.verbose)}if(!f)return!1;if(!await Mm(r,i.verbose))return!1;let l={version:of,resolvers:r,domains:n,ownerPid:i.ownerPid??et.pid,updatedAt:new Date().toISOString()};return await d$(t,l),!0}async function nr(i,t={}){let n=i.map((w)=>w.to).filter(Boolean),r=t.rpxDir??ji(),f=Dl(n),y=((await pf(r))?.resolvers??[]).filter((w)=>!f.includes(w));if(y.length>0)await Zl(y,t.verbose);if(f.length===0){i1(t.verbose),await dl(r);return}await r1({domains:n,rpxDir:r,verbose:t.verbose,ownerPid:t.ownerPid??et.pid})}async function an(i={}){let t=i.rpxDir??ji();i1(i.verbose);let r=(await pf(t))?.resolvers??[];await Zl(r,i.verbose),await n1(i.verbose),await dl(t)}async function SS(i){await an({verbose:i})}async function Nn(i={}){let t=i.rpxDir??ji(),n=await pf(t),r=n?.ownerPid!=null&&Ui(n.ownerPid);if(n&&!r){E("dns",`reconcile: owner pid ${n.ownerPid} is gone — tearing down DNS`,i.verbose),await an(i);return}let f=await n1(i.verbose);if(f.length>0)E("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,i.verbose);await Pl(i.verbose)}
|
|
252
|
+
export{W as a,Nh as b,RY as c,Qt as d,rl as e,fl as f,aY as g,NY as h,bi as i,Tt as j,cl as k,gn as l,ll as m,Sh as n,Of as o,Ln as p,xn as q,yl as r,$l as s,_h as t,zh as u,Al as v,Qa as w,Ma as x,Oa as y,Mh as z,Tl as A,El as B,el as C,Ga as D,Oh as E,Hh as F,qh as G,sh as H,Hf as I,kn as J,gh as K,Yl as L,xY as M,kh as N,Vh as O,da as P,i$ as Q,t$ as R,YB as S,BB as T,mB as U,n$ as V,l$ as W,Cl as X,Ul as Y,y$ as Z,h$ as _,gf as $,jl as aa,$$ as ba,Ot as ca,aB as da,Rl as ea,al as fa,Nl as ga,bn as ha,NB as ia,Wl as ja,Xl as ka,JB as la,T$ as ma,xf as na,Fl as oa,E$ as pa,OB as qa,GB as ra,qB as sa,Il as ta,eN as ua,U$ as va,Kl as wa,j$ as xa,mN as ya,St as za,zl as Aa,Ui as Ba,a$ as Ca,Ml as Da,kB as Ea,Et as Fa,Pn as Ga,Df as Ha,Gl as Ia,Un as Ja,X$ as Ka,J$ as La,I$ as Ma,ir as Na,Q$ as Oa,wm as Pa,um as Qa,sN as Ra,gN as Sa,LN as Ta,xN as Ua,tr as Va,of as Wa,k$ as Xa,D$ as Ya,Rm as Za,Dl as _a,bl as $a,t0 as ab,am as bb,Xm as cb,i1 as db,aS as eb,Jm as fb,fr as gb,Km as hb,NS as ib,n1 as jb,r1 as kb,nr as lb,an as mb,SS as nb,Nn as ob,ji as pb,vf as qb,Rn as rb,$m as sb,g$ as tb,jn as ub,$S as vb,Cm as wb,AS as xb,TS as yb,ES as zb};
|