@stacksjs/rpx 0.11.20 → 0.11.21

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.
@@ -1,176 +0,0 @@
1
- import{Na as M,Qa as Wr,Ra as m,Sa as E0,Wa as Lu,Xa as Kl,Za as oe,_a as qu,ab as h0,bb as xu}from"./chunk-w888yhnp.js";import F0 from"node:dgram";import*as j0 from"node:fs/promises";import*as N0 from"node:path";import*as hi from"node:process";import{spawn as T0}from"node:child_process";import*as yt from"node:fs/promises";import{homedir as o0}from"node:os";import*as kt from"node:path";import*as o from"node:process";var j={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};import{execSync as _l}from"node:child_process";import Q from"node:fs/promises";import*as Il from"node:os";import{homedir as fr}from"node:os";import*as ku from"node:path";import{join as D}from"node:path";import*as Lt from"node:process";import{createRequire as M0}from"node:module";import{Resolver as Xe}from"node:dns/promises";import{createHash as H0,sign as L0}from"node:crypto";import{createHash as q0}from"node:crypto";import{sign as x0}from"node:crypto";import{generateKeyPairSync as Ts,X509Certificate as Z0}from"node:crypto";import ge from"node:os";import Je from"node:path";import{existsSync as mc,statSync as Ac}from"fs";import{existsSync as i$,mkdirSync as _1,readdirSync as I1,readFileSync as r$,writeFileSync as K1}from"fs";import{homedir as Xi}from"os";import{dirname as M1,resolve as Ft}from"path";import jn from"process";import{existsSync as Ec,statSync as Tc}from"fs";import{existsSync as ef,mkdirSync as n$,readdirSync as e$,writeFileSync as f$}from"fs";import{homedir as gi}from"os";import{dirname as oc,resolve as at}from"path";import Ri from"process";import{join as l$,relative as c$,resolve as dc}from"path";import $n from"process";import{existsSync as os,mkdirSync as P1,readdirSync as Q1,writeFileSync as p1}from"fs";import{homedir as _e}from"os";import{dirname as tE,resolve as wt}from"path";import dr from"process";import{join as s$,relative as h$,resolve as Yc}from"path";import yn from"process";import{existsSync as ds,mkdirSync as fE,readdirSync as lE,writeFileSync as cE}from"fs";import{dirname as hE,resolve as wn}from"path";import ff from"process";import{Buffer as $i}from"buffer";import{createCipheriv as u$,createDecipheriv as $$,randomBytes as Ie}from"crypto";import{closeSync as Ke,createReadStream as Bc,createWriteStream as y$,existsSync as ze,fsyncSync as Cc,openSync as Rc,writeFileSync as w$}from"fs";import{access as a$,constants as Sc,mkdir as m$,readdir as Lr,rename as Uc,stat as Ji,unlink as qr,writeFile as Oe}from"fs/promises";import{join as _i}from"path";import lt from"process";import{pipeline as A$}from"stream/promises";import{createGzip as Fc}from"zlib";import Ii from"process";import pt from"process";import{Buffer as bt}from"buffer";import{createCipheriv as E$,createDecipheriv as T$,randomBytes as Me}from"crypto";import{closeSync as Ge,createReadStream as jc,createWriteStream as o$,existsSync as xr,fsyncSync as Nc,openSync as Wc,writeFileSync as d$}from"fs";import{access as Y$,constants as Xc,mkdir as B$,readdir as kr,rename as gc,stat as Ki,unlink as Vr,writeFile as He}from"fs/promises";import{isAbsolute as C$,join as zi,resolve as R$}from"path";import K from"process";import{pipeline as S$}from"stream/promises";import{createGzip as Jc}from"zlib";import Oi from"process";import vt from"process";import Dr from"process";import{existsSync as br}from"fs";import{resolve as Le}from"path";import{existsSync as U$}from"fs";import{existsSync as F$,readdirSync as j$}from"fs";import{extname as qe,resolve as _c}from"path";import N$ from"process";import{join as W$,relative as X$,resolve as Ic}from"path";import an from"process";import{Buffer as Pt}from"buffer";import{createCipheriv as g$,createDecipheriv as J$,randomBytes as xe}from"crypto";import{closeSync as ke,createReadStream as Kc,createWriteStream as _$,existsSync as Pr,fsyncSync as zc,openSync as Oc,writeFileSync as I$}from"fs";import{access as K$,constants as Mc,mkdir as z$,readdir as Qr,rename as Gc,stat as Mi,unlink as pr,writeFile as Ve}from"fs/promises";import{isAbsolute as O$,join as Gi,resolve as M$}from"path";import z from"process";import{pipeline as G$}from"stream/promises";import{createGzip as Hc}from"zlib";import Hi from"process";import Zt from"process";import vr from"process";import{existsSync as Zr}from"fs";import{resolve as De}from"path";import{existsSync as H$}from"fs";import{exec as hw}from"node:child_process";import Af from"node:fs";import uw from"node:os";import It from"node:path";import rh from"node:process";import{promisify as $w}from"node:util";import ki from"node:crypto";import ti from"node:fs";import of from"node:path";import _w from"node:crypto";import Iw from"node:fs";import Kw from"node:tls";import{execSync as Mw}from"node:child_process";import Un from"node:os";var G0=M0(import.meta.url);async function fs(t,i,r={}){let n=r.timeoutMs??120000,e=r.intervalMs??3000,f=t.split(".").slice(-2).join("."),l;try{let h=new Xe,u=await h.resolveNs(f),$=(await Promise.all(u.map((w)=>h.resolve4(w).catch(()=>[])))).flat();if($.length>0)l=new Xe,l.setServers($)}catch{}let c=Date.now()+n,s=l??new Xe;for(;;){try{if((await s.resolveTxt(t)).some((h)=>h.join("")===i))return!0}catch{}if(Date.now()>=c)return!1;await new Promise((h)=>setTimeout(h,e))}}class or{tokens=new Map;add(t,i){this.tokens.set(t,i)}get(t){return this.tokens.get(t)}remove(t){this.tokens.delete(t)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(t){let i=t.indexOf(or.PATH_PREFIX);if(i===-1)return;let r=t.slice(i+or.PATH_PREFIX.length);return this.get(r)}}var Fn=new or;function nn(t){return(typeof t==="string"?Buffer.from(t,"utf8"):Buffer.from(t)).toString("base64url")}function Ze(t){return Buffer.from(t,"base64url")}function ls(t){let i=t.export({format:"jwk"});if(i.kty!=="EC"||i.crv!=="P-256"||!i.x||!i.y)throw Error(`Expected a P-256 EC public key, got kty=${i.kty} crv=${i.crv}`);return{crv:"P-256",kty:"EC",x:i.x,y:i.y}}function cs(t){let i=`{"crv":"${t.crv}","kty":"${t.kty}","x":"${t.x}","y":"${t.y}"}`;return H0("sha256").update(i).digest("base64url")}function ss(t){let{protectedHeader:i,payload:r,privateKey:n}=t,e=nn(JSON.stringify(i)),f=r===""?"":nn(JSON.stringify(r)),l=`${e}.${f}`,c=L0("sha256",Buffer.from(l),{key:n,dsaEncoding:"ieee-p1363"});return{protected:e,payload:f,signature:nn(c)}}var hs="https://acme-staging-v02.api.letsencrypt.org/directory",us="https://acme-v02.api.letsencrypt.org/directory";class hn extends Error{problem;httpStatus;constructor(t,i,r){super(t);this.name="AcmeError",this.problem=i,this.httpStatus=r}}class un{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor(t){this.directoryUrl=t.directoryUrl,this.accountKey=t.accountKey,this.jwk=ls(t.accountPublicKey),this.thumbprint=cs(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let t=await fetch(this.directoryUrl);if(!t.ok)throw Error(`Failed to fetch ACME directory: HTTP ${t.status}`);return this.directoryCache=await t.json(),this.directoryCache}async newNonce(){let t=await this.directory(),i=(await fetch(t.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!i)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=i,i}async ensureNonce(){if(this.nonce){let t=this.nonce;return this.nonce=void 0,t}return this.newNonce()}async signedPost(t){let{url:i,payload:r,useJwk:n}=t,e={alg:"ES256",nonce:await this.ensureNonce(),url:i};if(n)e.jwk=this.jwk;else e.kid=this.requireKid();let f=ss({protectedHeader:e,payload:r,privateKey:this.accountKey}),l=await fetch(i,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(f)}),c=l.headers.get("replay-nonce");if(c)this.nonce=c;let s=l.headers.get("content-type")??"",h;if(s.includes("application/pem-certificate-chain")||s.startsWith("text/"))h=await l.text();else{let u=await l.text();h=u?JSON.parse(u):{}}if(l.status>=400){let u=h??{};throw new hn(`ACME request to ${i} failed (HTTP ${l.status}): ${u.type??""} ${u.detail??""}`.trim(),u,l.status)}return{status:l.status,headers:l.headers,body:h,location:l.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(t={}){let i=await this.directory(),r={termsOfServiceAgreed:!0};if(t.email)r.contact=[`mailto:${t.email}`];let n=await this.signedPost({url:i.newAccount,payload:r,useJwk:!0});if(!n.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=n.location,this.accountKid}async newOrder(t){let i=await this.directory(),r={identifiers:t.map((e)=>({type:"dns",value:e}))},n=await this.signedPost({url:i.newOrder,payload:r});if(!n.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:n.body,orderUrl:n.location}}async getAuthorization(t){return(await this.signedPost({url:t,payload:""})).body}keyAuthorization(t){return`${t}.${this.thumbprint}`}dns01TxtValue(t){return q0("sha256").update(this.keyAuthorization(t)).digest("base64url")}async notifyChallengeReady(t){await this.signedPost({url:t,payload:{}})}async pollAuthorization(t,i={}){let r=i.timeoutMs??60000,n=i.intervalMs??2000,e=Date.now()+r;while(Date.now()<e){let f=await this.getAuthorization(t);if(f.status==="valid")return;if(f.status==="invalid"){let l=f.challenges.find((c)=>c.status==="invalid");throw new hn(`Authorization for ${f.identifier.value} became invalid: ${l?.error?.detail??"unknown reason"}`,l?.error??{},0)}await ac(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${t} to become valid`)}async finalizeOrder(t,i){return(await this.signedPost({url:t,payload:{csr:i}})).body}async getOrder(t){return(await this.signedPost({url:t,payload:""})).body}async pollOrder(t,i={}){let r=i.timeoutMs??60000,n=i.intervalMs??2000,e=Date.now()+r;while(Date.now()<e){let f=await this.getOrder(t);if(f.status==="valid"){if(!f.certificate)throw Error("ACME order is valid but has no certificate URL");return f.certificate}if(f.status==="invalid")throw Error(`ACME order ${t} became invalid`);await ac(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${t} to become valid`)}async downloadCertificate(t){let i=await this.signedPost({url:t,payload:""});return typeof i.body==="string"?i.body:String(i.body)}static selectChallenge(t,i){let r=t.challenges.find((n)=>n.type===i);if(!r)throw Error(`No ${i} challenge available for ${t.identifier.value}`);return r}}function $s(t){let i=t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=i[0];if(!r)return{certPem:`${t.trim()}
2
- `,chainPem:""};let n=`${r.trim()}
3
- `,e=i.slice(1).map((f)=>f.trim()).join(`
4
- `);return{certPem:n,chainPem:e?`${e}
5
- `:""}}function ys(t){return`_acme-challenge.${t.startsWith("*.")?t.slice(2):t}`}function ac(t){return new Promise((i)=>setTimeout(i,t))}function k0(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function ai(t,i){return Buffer.concat([Buffer.from([t]),k0(i.length),i])}function ws(t){let i;if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=[],n=t;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);i=Buffer.from(r)}else if(i=t.length===0?Buffer.from([0]):t,i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return ai(2,i)}function Ci(t){let i=t.split(".").map(Number);if(i.length<2)throw Error(`Invalid OID: ${t}`);let r=[40*i[0]+i[1]];for(let n=2;n<i.length;n++){let e=i[n],f=[e&127];e=Math.floor(e/128);while(e>0)f.unshift(e&127|128),e=Math.floor(e/128);r.push(...f)}return ai(6,Buffer.from(r))}function Ut(...t){return ai(48,Buffer.concat(t))}function tf(...t){return ai(49,Buffer.concat(t))}function rf(t){return ai(3,Buffer.concat([Buffer.from([0]),t]))}function as(t){return ai(4,t)}function ms(t){return ai(12,Buffer.from(t,"utf8"))}function nf(t,i,r){let n=128|(r?32:0)|t;return ai(n,i)}var V0="1.2.840.10045.2.1",D0="1.2.840.10045.3.1.7",b0="1.2.840.10045.4.3.2",P0="2.5.4.3",Q0="1.2.840.113549.1.9.14",p0="2.5.29.17";function v0(t){let i=t.export({format:"jwk"});if(!i.x||!i.y)throw Error("Public key JWK is missing x/y coordinates");let r=Ze(i.x),n=Ze(i.y);if(r.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),r,n])}function As(t){let{domains:i,publicKey:r,privateKey:n}=t;if(i.length===0)throw Error("At least one domain is required to build a CSR");let e=Ut(tf(Ut(Ci(P0),ms(i[0])))),f=Ut(Ut(Ci(V0),Ci(D0)),rf(v0(r))),l=i.map((a)=>nf(2,Buffer.from(a,"ascii"),!1)),c=Ut(...l),s=Ut(Ci(p0),as(c)),h=Ut(s),u=Ut(Ci(Q0),tf(h)),$=nf(0,u,!0),w=Ut(ws(0),e,f,$),y=x0("sha256",w,n),A=Ut(Ci(b0));return Ut(w,A,rf(y))}function Es(t){return As(t).toString("base64url")}function t$(t){if(t){let{createPrivateKey:e,createPublicKey:f}=G0("node:crypto"),l=e(t),c=f(l);return{privateKey:l,publicKey:c,pem:t}}let{privateKey:i,publicKey:r}=Ts("ec",{namedCurve:"P-256"}),n=i.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:i,publicKey:r,pem:n}}async function df(t){let{domains:i,method:r}=t;if(i.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!t.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(i.some(($)=>$.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=t.directoryUrl??(t.staging===!1?us:hs),e=t$(t.accountKeyPem),f=new un({directoryUrl:n,accountKey:e.privateKey,accountPublicKey:e.publicKey});await f.newAccount({email:t.email});let{order:l,orderUrl:c}=await f.newOrder(i),s=t.http01Store??Fn,h=[],u=[];try{for(let B of l.authorizations){let X=await f.getAuthorization(B);if(X.status==="valid")continue;let V=un.selectChallenge(X,r);if(r==="dns-01"){let St=ys(X.identifier.value),_t=f.dns01TxtValue(V.token);await t.dnsProvider.setTxt(St,_t),h.push({name:St,value:_t}),await fs(St,_t,{timeoutMs:t.dnsPropagationTimeoutMs??120000})}else s.add(V.token,f.keyAuthorization(V.token)),u.push(V.token);await f.notifyChallengeReady(V.url),await f.pollAuthorization(B,{timeoutMs:t.timeoutMs})}let{privateKey:$,publicKey:w}=Ts("ec",{namedCurve:"P-256"}),y=Es({domains:i,publicKey:w,privateKey:$});await f.finalizeOrder(l.finalize,y);let A=await f.pollOrder(c,{timeoutMs:t.timeoutMs}),a=await f.downloadCertificate(A),{certPem:E,chainPem:T}=$s(a),d=T?`${E}${T}`:E,Y=$.export({format:"pem",type:"pkcs8"}).toString(),U=new Date(new Z0(E).validTo);return{certPem:E,keyPem:Y,chainPem:T,fullChainPem:d,accountKeyPem:e.pem,notAfter:U}}finally{for(let{name:$,value:w}of h)await t.dnsProvider?.removeTxt($,w).catch(()=>{});for(let $ of u)s.remove($)}}class Ys{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,l=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:l}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!mc(t))return!0;return Ac(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=mc(r)?Ac(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,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:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Bs{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),l=performance.now()-n;return this.recordMetric({operation:t,duration:l,timestamp:e,...r}),f}catch(f){let l=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:l,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var mn=new Ys,Yf=new Bs,L$=Object.defineProperty,q$=(t)=>t;function x$(t,i){this[t]=q$.bind(null,i)}var k$=(t,i)=>{for(var r in i)L$(t,r,{get:i[r],enumerable:!0,configurable:!0,set:x$.bind(i,r)})},V$=(t,i)=>()=>(t&&(i=t(t=0)),i),Cs={};k$(Cs,{withErrorRecovery:()=>Us,tryLoadConfig:()=>my,loadConfigWithResult:()=>wy,loadConfig:()=>Xs,isRetryableError:()=>cy,isConfigNotFoundError:()=>ly,isBunfigError:()=>Fs,globalPerformanceMonitor:()=>Rr,globalCache:()=>qi,getEnvOrDefault:()=>sy,generateConfigTypes:()=>Ay,defaultGeneratedDir:()=>Ms,defaultConfigDir:()=>Os,deepMergeWithArrayStrategy:()=>Uf,deepMerge:()=>js,createLibraryConfig:()=>Ey,config:()=>ay,bunfigPlugin:()=>Ty,applyEnvVarsToConfig:()=>Er,TypeGenerationError:()=>yf,SchemaValidationError:()=>Br,PluginError:()=>af,PerformanceMonitor:()=>Cf,FileSystemError:()=>$f,ErrorFactory:()=>wi,EnvVarError:()=>Yn,EnvProcessor:()=>Nn,ConfigValidator:()=>Ff,ConfigValidationError:()=>hf,ConfigNotFoundError:()=>dn,ConfigMergeError:()=>uf,ConfigLoader:()=>jf,ConfigLoadError:()=>Yr,ConfigFileLoader:()=>Wn,ConfigCache:()=>Bf,CacheUtils:()=>Js,BunfigError:()=>Yt,BrowserConfigError:()=>wf,ArrayMergeStrategies:()=>Ks});class Bf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,l=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:l}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Ec(t))return!0;return Tc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Ec(r)?Tc(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,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:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Cf{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),l=performance.now()-n;return this.recordMetric({operation:t,duration:l,timestamp:e,...r}),f}catch(f){let l=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:l,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function D$(t,i={}){let r=Object.keys(i).sort().map((n)=>`${n}:${i[n]}`).join("|");return r?`${t}:${r}`:t}function b$(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function P$(t){return t.getStats().size*2}function Rf(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&x(i[0])&&"id"in i[0]&&i[0].id===3&&x(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(x(i)&&x(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(x(t)&&"arr"in t&&Array.isArray(t.arr)&&x(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&x(i[0])&&x(t[0])){let n=[...i];for(let e of t)if(x(e)&&"name"in e){if(!n.find((f)=>x(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(x(e)&&"path"in e){if(!n.find((f)=>x(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>An(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!x(i)||!x(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(x(e)&&x(r[n]))r[n]=Rf(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&x(e[0])&&x(r[n][0])){let f=[...e];for(let l of r[n])if(x(l)&&"name"in l){if(!f.find((c)=>x(c)&&("name"in c)&&c.name===l.name))f.push(l)}else if(x(l)&&"path"in l){if(!f.find((c)=>x(c)&&("path"in c)&&c.path===l.path))f.push(l)}else if(!f.some((c)=>An(c,l)))f.push(l);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let l of r[n])if(!f.includes(l))f.push(l);r[n]=f}else r[n]=e;else r[n]=e}return r}function An(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!An(t[r],i[r]))return!1;return!0}if(x(t)&&x(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!An(t[e],i[e]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Q$(t,i){if(!ds(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Rf(i,n)}catch{return null}}catch{return null}}async function p$({name:t="",cwd:i,defaultConfig:r}){let n=i||ff.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let l of f)for(let c of e){let s=wn(n,`${l}${c}`),h=await Q$(s,r);if(h!==null)return h}try{let l=wn(n,"package.json");if(ds(l)){let c=(await import(l))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return Rf(r,c)}catch{}}}catch{}return r}function v$(t,i={}){let r=yn.cwd();while(r.includes("storage"))r=Yc(r,"..");let n=Yc(r,t||"");if(i?.relative)return h$(yn.cwd(),n);return n}async function Z$(){try{let t=await p$({name:"clarity",defaultConfig:fn,cwd:yn.cwd(),endpoint:"",headers:{}});return{...fn,...t}}catch{return fn}}function b(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ty(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let t=pt.type;if(t==="renderer"||t==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class Rs{async format(t){let i=await ty(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ii.pid,hostname:i(),environment:Ii.env.NODE_ENV||"development",platform:Ii.platform,version:Ii.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ii.env.NODE_ENV||Ii.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class En{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(t,i={}){this.name=t,this.config={...cf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Rs,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??lt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...ln,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...ln};return{...ln,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:cf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,l=1000;while(e<f)try{try{try{await a$(this.config.logDirectory,Sc.F_OK|Sc.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await m$(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:$i.from(t);try{if(!ze(this.currentLogFile))await Oe(this.currentLogFile,"",{mode:420});if(n=Rc(this.currentLogFile,"a",420),w$(n,c,{flag:"a"}),Cc(n),n!==void 0)Ke(n),n=void 0;if((await Ji(this.currentLogFile)).size===0){if(await Oe(this.currentLogFile,c,{flag:"w",mode:420}),(await Ji(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let h=s;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let $=l*2**e;await new Promise((w)=>setTimeout(w,$)),e++;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(n!==void 0)try{Ke(n)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let s=l*2**(e-1);await new Promise((h)=>setTimeout(h,s))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 _i(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 _i(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return _i(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(b())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[l]of n.slice(f))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Ie(16).toString("hex")}generateKey(){return Ie(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ie(16),n=u$("aes-256-gcm",i,r),e=$i.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:$i.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Fc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i($i.from($i.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(b())return;let t=await Ji(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Lr(this.config.logDirectory),f=e.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,h)=>{let u=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),l=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${l}`;if(await Ji(r).catch(()=>null))try{if(await Uc(r,c),i.compress)try{let s=`${c}.gz`;await this.compressLogFile(c,s),await qr(c)}catch(s){console.error("Error compressing rotated file:",s)}if(f.length===0&&!e.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await Oe(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ji(r).catch(()=>null))await Uc(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await Lr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,l)=>l.localeCompare(f));for(let f of e.slice(i.maxFiles))await qr(_i(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Bc(t),n=y$(i),e=Fc();await A$(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),ze(this.currentLogFile))try{let t=Rc(this.currentLogFile,"r+");Cc(t),Ke(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!b()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Lr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await qr(_i(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?L.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:l=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(l)y.push(i);if(f==="warning")y.push("WARN");else if(f==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(e),y.join(" ")}let s=lt.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${L.cyan(e)}`;if(!l)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,s-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,l)=>{let c=Number.parseInt(l,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,l)=>{if(l==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(l){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),l,c;if(i instanceof Error)l=i.message,c=i.stack;else l=this.formatMessage(i,r);if(this.fancy&&!b()){let h=_s[t],u=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",$;switch(t){case"debug":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:L.gray(l),level:t}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:l,level:t}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:L.green(l),level:t}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:l,level:t}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:l,level:t}),console.error($),c){let w=c.split(`
6
- `);for(let y of w)if(y.trim()&&!y.includes(l))console.error(this.formatConsoleMessage({timestamp:e,message:L.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!b()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${l}`),c)console.error(c)}if(!this.shouldLog(t))return;let s=`${f} ${this.environment}.${t.toUpperCase()}: ${l}
7
- `;if(c)s+=`${c}
8
- `;s=s.replace(this.ANSI_PATTERN,""),await this.writeToFile(s)}time(t){let i=performance.now();if(this.fancy&&!b()){let r=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:L.blue("◐"),tag:r,message:`${L.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,l=new Date,c=this.formatConsoleTimestamp(l),s=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${f}`;if(r)s+=` ${JSON.stringify(r)}`;if(s+=`
9
- `,s=s.replace(this.ANSI_PATTERN,""),this.fancy&&!b()){let h=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:L.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!b())console.error(s.trim());await this.writeToFile(s)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new En(i,{...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(r),r}createReadStream(){if(b())throw Error("createReadStream is not supported in browser environments");if(!ze(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Bc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=$i.isBuffer(t)?t:$i.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),l=n.slice(16,-16),c=$$("aes-256-gcm",r,e);return c.setAuthTag(f),$i.concat([c.update(l),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!b()){let f=t.split(`
10
- `),l=Math.max(...f.map((u)=>u.length))+2,c=`┌${"─".repeat(l)}┐`,s=`└${"─".repeat(l)}┘`,h=f.map((u)=>{let $=" ".repeat(l-u.length-2);return`│ ${u}${$} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:L.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(c)})),h.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(s),showTimestamp:!1}))}else if(!b())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
11
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(b())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${L.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();lt.stdin.removeListener("data",r);try{if(typeof lt.stdin.setRawMode==="function")lt.stdin.setRawMode(!1)}catch{}lt.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof lt.stdin.setRawMode==="function")lt.stdin.setRawMode(!0)}catch{}lt.stdin.resume(),lt.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let e=/%([sdijfo%])/g,f=0;if(r=t.replace(e,(l,c)=>{if(c==="%")return"%";if(f>=i.length)return l;let s=i[f++];switch(c){case"s":return String(s);case"d":case"i":return Number(s).toString();case"j":case"o":return JSON.stringify(s,null,2);default:return l}}),f<i.length)r+=` ${i.slice(f).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!b()){let e=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",f=L.blue("◐");console.error(`${f} ${e} ${L.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
12
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(t,i=""){if(!this.enabled||!this.fancy||b()||t<=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 r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,e)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,n)),e!==void 0)this.activeProgressBar.message=e;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,e="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||b())return;lt.stdout.write(`${"\r".padEnd(lt.stdout.columns||80)}\r`),this.log(e,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||b()||!lt.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=L.green("━".repeat(n)),l=L.gray("━".repeat(e)),c=`[${f}${l}]`,s=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=i||r===100?L.green("✓"):L.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${s}${h}`,y=lt.stdout.columns||80,A=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${A}`,lt.stdout.write(t.lastRenderedLine),i)lt.stdout.write(`
13
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||b()||!lt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(b()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Lr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=_i(this.config.logDirectory,n);if(t.before)try{if((await Ji(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await qr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function en(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&O(i[0])&&"id"in i[0]&&i[0].id===3&&O(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(O(i)&&O(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(O(t)&&"arr"in t&&Array.isArray(t.arr)&&O(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&O(i[0])&&O(t[0])){let n=[...i];for(let e of t)if(O(e)&&"name"in e){if(!n.find((f)=>O(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(O(e)&&"path"in e){if(!n.find((f)=>O(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Tn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!O(i)||!O(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(O(e)&&O(r[n]))r[n]=en(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&O(e[0])&&O(r[n][0])){let f=[...e];for(let l of r[n])if(O(l)&&"name"in l){if(!f.find((c)=>O(c)&&("name"in c)&&c.name===l.name))f.push(l)}else if(O(l)&&"path"in l){if(!f.find((c)=>O(c)&&("path"in c)&&c.path===l.path))f.push(l)}else if(!f.some((c)=>Tn(c,l)))f.push(l);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let l of r[n])if(!f.includes(l))f.push(l);r[n]=f}else r[n]=e;else r[n]=e}return r}function Sf(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:en(t,i);if(Array.isArray(t))return r==="replace"?i:en(t,i);if(!O(i)||!O(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],l=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(l))if(r==="replace")n[e]=f;else n[e]=en(l,f);else if(O(f)&&O(l))n[e]=Sf(l,f,r);else n[e]=f}return n}function Tn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Tn(t[r],i[r]))return!1;return!0}if(O(t)&&O(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Tn(t[e],i[e]))return!1}return!0}return!1}function O(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function tn(t,i,r="replace"){if(!os(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Sf(i,e,r)}catch{return null}}catch{return null}}function iy(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(l,c=[]){let s={...l};for(let[h,u]of Object.entries(l)){let $=[...c,h],w=(a)=>a.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${n}_${$.map(w).join("_")}`,A=`${n}_${$.map((a)=>a.toUpperCase()).join("_")}`;if(r)st.info(`Checking environment variable ${y} for config ${t}.${$.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))s[h]=f(u,$);else{let a=dr.env[y]||dr.env[A];if(a!==void 0){if(r)st.info(`Using environment variable ${a?y:A} for config ${t}.${$.join(".")}`);if(typeof u==="number")s[h]=Number(a);else if(typeof u==="boolean")s[h]=a.toLowerCase()==="true";else if(Array.isArray(u))try{let E=JSON.parse(a);if(Array.isArray(E))s[h]=E;else s[h]=a.split(",").map((T)=>T.trim())}catch{s[h]=a.split(",").map((E)=>E.trim())}else s[h]=a}}}return s}return f(e)}async function ry({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:l=!0,arrayStrategy:c="replace"}){let s=l&&typeof e==="object"&&e!==null&&!Array.isArray(e)?iy(t,e,f):e,h=r||dr.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(f)st.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let $=[t,`.${t}`].filter(Boolean),w=[`${t}.config`,`.${t}.config`].filter(Boolean),y=i?[i,`.${i}`]:[],A=i?[`${i}.config`,`.${i}.config`]:[],a=Array.from(new Set([h,wt(h,"config"),wt(h,".config"),n?wt(h,n):void 0].filter(Boolean)));for(let E of a){if(f)st.info(`Searching for configuration in: ${E}`);let T=[wt(h,"config"),wt(h,".config")].concat(n?[wt(h,n)]:[]).includes(E)?[...$,...w,...y,...A]:[...w,...$,...A,...y];for(let d of T)for(let Y of u){let U=wt(E,`${d}${Y}`),B=await tn(U,s,c);if(B!==null){if(f)st.success(`Configuration loaded from: ${U}`);return B}}}if(t){let E=wt(_e(),".config",t),T=["config",`${t}.config`];if(i)T.push(`${i}.config`);if(f)st.info(`Checking user config directory: ${E}`);for(let d of T)for(let Y of u){let U=wt(E,`${d}${Y}`),B=await tn(U,s,c);if(B!==null){if(f)st.success(`Configuration loaded from user config directory: ${U}`);return B}}}if(t){let E=wt(_e(),".config"),T=[`.${t}.config`];if(i)T.push(`.${i}.config`);if(f)st.info(`Checking user config directory for dotfile configs: ${E}`);for(let d of T)for(let Y of u){let U=wt(E,`${d}${Y}`),B=await tn(U,s,c);if(B!==null){if(f)st.success(`Configuration loaded from user config directory dotfile: ${U}`);return B}}}if(t){let E=_e(),T=[`.${t}.config`,`.${t}`];if(i)T.push(`.${i}.config`),T.push(`.${i}`);if(f)st.info(`Checking user home directory for dotfile configs: ${E}`);for(let d of T)for(let Y of u){let U=wt(E,`${d}${Y}`),B=await tn(U,s,c);if(B!==null){if(f)st.success(`Configuration loaded from user home directory: ${U}`);return B}}}try{let E=wt(h,"package.json");if(os(E)){let T=await import(E),d=T[t];if(!d&&i){if(d=T[i],d&&f)st.success(`Using alias "${i}" configuration from package.json`)}if(d&&typeof d==="object"&&!Array.isArray(d))try{if(f)st.success(`Configuration loaded from package.json: ${d===T[t]?t:i}`);return Sf(s,d,c)}catch(Y){if(f)st.warn("Failed to merge package.json config:",Y)}}}catch(E){if(f)st.warn("Failed to load package.json:",E)}if(f)st.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return s}function ny(t,i={}){let r=$n.cwd();while(r.includes("storage"))r=dc(r,"..");let n=dc(r,t||"");if(i?.relative)return c$($n.cwd(),n);return n}async function ey(){try{let t=await ry({name:"clarity",alias:"logging",defaultConfig:cn,cwd:$n.cwd()});return{...cn,...t||{}}}catch{return cn}}function v(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fy(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let t=vt.type;if(t==="renderer"||t==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class Ss{async format(t){let i=await fy(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Oi.pid,hostname:i(),environment:Oi.env.NODE_ENV||"development",platform:Oi.platform,version:Oi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Oi.env.NODE_ENV||Oi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class on{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(t,i={}){this.name=t,this.config={...sf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Ss,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??K.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...sn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...sn};return{...sn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:sf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!v()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,l=1000;while(e<f)try{try{try{await Y$(this.config.logDirectory,Xc.F_OK|Xc.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await B$(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:bt.from(t);try{if(!xr(this.currentLogFile))await He(this.currentLogFile,"",{mode:420});if(n=Wc(this.currentLogFile,"a",420),d$(n,c,{flag:"a"}),Nc(n),n!==void 0)Ge(n),n=void 0;if((await Ki(this.currentLogFile)).size===0){if(await He(this.currentLogFile,c,{flag:"w",mode:420}),(await Ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let h=s;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let $=l*2**e;await new Promise((w)=>setTimeout(w,$)),e++;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(n!==void 0)try{Ge(n)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let s=l*2**(e-1);await new Promise((h)=>setTimeout(h,s))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 zi(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 zi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return zi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(v())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[l]of n.slice(f))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return Me(16).toString("hex")}generateKey(){return Me(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Me(16),n=E$("aes-256-gcm",i,r),e=bt.isBuffer(t)?t:bt.from(t,"utf8"),f=n.update(e),l=n.final(),c=f.length+l.length,s=n.getAuthTag(),h=bt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),l.copy(h,16+f.length),s.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Jc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(bt.from(bt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(v())return;if(!this.shouldWriteToFile())return;let t=await Ki(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await kr(this.config.logDirectory),f=e.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,h)=>{let u=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),l=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${l}`;if(await Ki(r).catch(()=>null))try{if(await gc(r,c),i.compress)try{let s=`${c}.gz`;await this.compressLogFile(c,s),await Vr(c)}catch(s){console.error("Error compressing rotated file:",s)}if(f.length===0&&!e.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await He(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ki(r).catch(()=>null))await gc(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await kr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,l)=>l.localeCompare(f));for(let f of e.slice(i.maxFiles))await Vr(zi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=jc(t),n=o$(i),e=Jc();await S$(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),xr(this.currentLogFile))try{let t=Wc(this.currentLogFile,"r+");Nc(t),Ge(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!v()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await kr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Vr(zi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?g.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||v())return!1;let t=typeof K.env.NO_COLOR<"u",i=K.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof K.stderr<"u"&&K.stderr.isTTY||typeof K.stdout<"u"&&K.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:l=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(l)y.push(i);if(f==="warning")y.push("WARN");else if(f==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(e),y.join(" ")}let s=K.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${g.cyan(e)}`;if(!l)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,s-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,l)=>{let c=Number.parseInt(l,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,l)=>{if(l==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(l){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=g.underline(g.blue(n)),l=this.toAbsoluteFilePath(e);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(l)}`,s="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>g.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>g.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>g.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>g.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>g.strikethrough(n)),i}supportsHyperlinks(){if(v())return!1;let t=K.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=K.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(C$(i)||i.startsWith("./")||i.startsWith("../"))i=R$(i);else return null;return xr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),l,c;if(i instanceof Error)l=i.message,c=i.stack;else l=this.formatMessage(i,r);let{consoleText:s,fileText:h}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":Is[t],w=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:g.gray(s),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:g.green(s),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.error(y),c){let A=c.split(`
14
- `);for(let a of A)if(a.trim()&&!a.includes(l))console.error(this.formatConsoleMessage({timestamp:e,message:g.gray(` ${a}`),level:t,showTimestamp:!1}))}break}}else if(!v()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${l}`),c)console.error(c)}if(!this.shouldLog(t))return;let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
15
- `;if(c)u+=`${c}
16
- `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!v()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!v()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!v()&&K.stdout.isTTY)K.stdout.write(`
17
- `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!v()&&K.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":g.blue("◐"),tag:r,message:`${g.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,l=new Date,c=this.formatConsoleTimestamp(l),s=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${f}`;if(r)s+=` ${JSON.stringify(r)}`;if(s+=`
18
- `,s=s.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:c,icon:this.options.showIcons===!1?"":g.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!v())console.error(s.trim());if(this.shouldWriteToFile())await this.writeToFile(s)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new on(i,{...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(r),r}createReadStream(){if(v())throw Error("createReadStream is not supported in browser environments");if(!xr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return jc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=bt.isBuffer(t)?t:bt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),l=n.subarray(16,n.length-16),c=T$("aes-256-gcm",r,e);c.setAuthTag(f);let s=c.update(l),h=c.final(),u=s.length+h.length,$=bt.allocUnsafe(u);return s.copy($,0),h.copy($,s.length),$.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return v()}isServerMode(){return!v()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
19
- `),s=Math.max(...c.map((w)=>w.length))+2,h=`┌${"─".repeat(s)}┐`,u=`└${"─".repeat(s)}┘`,$=c.map((w)=>{return this.formatConsoleMessage({timestamp:r,message:g.cyan(w),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:g.cyan(h),showTimestamp:!1})),$.forEach((w)=>console.error(w)),console.error(this.formatConsoleMessage({timestamp:r,message:g.cyan(u),showTimestamp:!1}))}else if(!v())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let l=`${n} ${this.environment}.INFO: [BOX] ${f}
20
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(t){if(v())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${g.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();K.stdin.removeListener("data",r);try{if(typeof K.stdin.setRawMode==="function")K.stdin.setRawMode(!1)}catch{}K.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof K.stdin.setRawMode==="function")K.stdin.setRawMode(!0)}catch{}K.stdin.resume(),K.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,c=0;if(r=t.replace(l,(s,h)=>{if(h==="%")return"%";if(c>=i.length)return s;let u=i[c++];switch(h){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return s}}),c<i.length)r+=` ${i.slice(c).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${g.blue("◐")} `;console.error(`${c}${l} ${g.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
21
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!K.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=g.green("━".repeat(n)),l=g.gray("━".repeat(e)),c=`[${f}${l}]`,s=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?g.green("✓"):g.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${s}${h}`,y=K.stdout.columns||80,A=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${A}`,K.stdout.write(t.lastRenderedLine),i)K.stdout.write(`
22
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||v()||!K.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(v()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await kr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=zi(this.config.logDirectory,n);if(t.before)try{if((await Ki(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Vr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Us(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,l=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(s){if(l=s instanceof Error?s:Error(String(s)),c===r||!e(l))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function Fs(t){return t instanceof Yt}function ly(t){return t instanceof dn}function cy(t){if(Fs(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((i)=>t.message.toLowerCase().includes(i.toLowerCase()))}class Nn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:l={},verbose:c=!1,trackPerformance:s=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(t),$={...i};return this.processObject($,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:l,verbose:c,configName:t}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(s)return Rr.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let l=[...i,e],c=l.map((u)=>this.formatEnvKey(u,n.useCamelCase)),s=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${l.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,l,r,n);else{let u=Dr.env[s]||(h?Dr.env[h]:void 0);if(u!==void 0){if(n.verbose){let $=Dr.env[s]?s:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,s,n.customParsers,n.configName)}catch($){if($ instanceof Yn)throw $;throw wi.envVar(s,u,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,l]of Object.entries(n))try{return l(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw wi.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Dr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),l=[];switch(this.extractEnvVarInfo(i,[],f,l),e){case"markdown":return this.formatAsMarkdown(l,t);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let l=[...i,e],c=`${r}_${l.map((s)=>this.formatEnvKey(s,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,l,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${l.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
23
-
24
- `;for(let n of t)r+=`${n.key}
25
- `,r+=` Type: ${n.type}
26
- `,r+=` Description: ${n.description}
27
- `,r+=` Example: ${n.example}
28
-
29
- `;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
30
-
31
- `;r+=`| Variable | Type | Description | Example |
32
- `,r+=`|----------|------|-------------|----------|
33
- `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
34
- `;return r}}function sy(t,i){let r=gs("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function js(t,i,r={}){return Ns(t,i,r,new WeakMap)}function Ns(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:l}=r;if(i===null||i===void 0)return f?t:i;if(l){let c=l(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Ws(t,i,e,n);if(!jt(i)||!jt(t))return i;return yy(t,i,r,n)}function Ws(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return hy(t,i);case"smart":return uy(t,i,n);default:return i}return i}function hy(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>lf(e,n)))r.push(n);return r}function uy(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(jt(i[0])&&jt(t[0]))return $y(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function $y(t,i,r){let n=[...i];for(let e of t){if(!jt(e)){n.push(e);continue}let f=["id","name","key","path","type"],l=!1;for(let c of f)if(c in e){if(n.find((s)=>jt(s)&&(c in s)&&s[c]===e[c])){l=!0;break}}if(!l)n.push(e)}return n}function yy(t,i,r,n){let e=i;if(jt(e)&&n.has(e))return n.get(e);let f={...t};if(jt(e))n.set(e,f);for(let l in e){if(!Object.prototype.hasOwnProperty.call(e,l))continue;let c=e[l],s=f[l];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[l]=c;continue}if(jt(c)&&jt(s))f[l]=Ns(s,c,r,n);else if(Array.isArray(c)||Array.isArray(s))f[l]=Ws(s,c,r.arrayMergeMode||"smart",n);else f[l]=c}return f}function Uf(t,i,r="replace"){return js(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function lf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!lf(t[r],i[r]))return!1;return!0}if(jt(t)&&jt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!lf(t[e],i[e]))return!1}return!0}return!1}function jt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Wn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:l=!0,verbose:c=!1}=r;if(e){let h=qi.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let s=async()=>{if(!br(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),$=u.default||u,w="default"in u,y=Object.keys(u).length>0;if(!w&&!y)throw new Yr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Yr(t,Error("Configuration must export a valid object"),"unknown");let A={config:Uf(i,$,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)qi.setWithFileCheck("file",A,t,f);return A}catch(h){throw h instanceof Error?wi.configLoad(t,h):wi.configLoad(t,Error(String(h)))}};if(l)return Rr.track("loadFromPath",s,{path:t});return s()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let l of this.extensions)e.push(Le(i,`${f}${l}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return Us(async()=>{return br(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!br(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let l of this.extensions){let c=Le(t,`${f}${l}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let l of f)if(this.looksLikeConfigFile(l)){let c=Le(t,l);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!br(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class Ff{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:l=[],trackPerformance:c=!0,verbose:s=!1}=r,h=async()=>{let u=[],$=[],w={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:l,trackPerformance:c,verbose:s};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,w);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...l],w);else return this.validateWithJSONSchema(t,i,w)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:$}}};if(c)return await Rr.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!U$(i))throw new Br(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new Br(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let l=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(l)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${l}`,expected:c.join(" or "),actual:l,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let l=0;l<t.length;l++){let c=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(t[l],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let l=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in l)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,s]of Object.entries(i.properties))if(c in l){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(l[c],s,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let s of Object.keys(l))if(!c.has(s))e.push({path:r?`${r}.${s}`:s,message:`Additional property '${s}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let l=this.getValueByPath(t,f.path),c=this.validateWithRule(l,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:f.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,l]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(l)})}return i}mapTypeScriptType(t){switch(t.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:zs},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class jf{fileLoader=new Wn;envProcessor=new Nn;validator=new Ff;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...l}=t;try{if(r?.enabled){let s=this.checkCache(l.name||"",l);if(s)return s}let c;try{c=await this.loadConfigurationStrategies(l,!0,r)}catch(s){let h=l.__strictErrorHandling;if(s instanceof Error&&s.name==="ConfigNotFoundError"){if(h)throw s;c={...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(s instanceof Error&&s.name==="ConfigLoadError"){let u=s.message.includes("EACCES")||s.message.includes("EPERM")||s.message.includes("permission denied"),$=!u&&(s.message.includes("syntax")||s.message.includes("Expected")||s.message.includes("Unexpected")||s.message.includes("BuildMessage")||s.message.includes("errors building")),w=s.message.includes("Configuration must export a valid object")||s.message.includes("Configuration file is empty and exports nothing");if(h&&(w||u))throw s;if($&&(!h||!w))c={...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(!h)c={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${s.message}`]};else throw s}else c={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${s instanceof Error?s.message:String(s)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,l.name);if(r?.enabled&&c)this.cacheResult(l.name||"",c,r,l);if(n?.enabled){let s={operation:"loadConfig",duration:Date.now()-i,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(s);if(n.slowThreshold&&s.duration>n.slowThreshold)Kt.warn(`Slow configuration loading detected: ${s.duration}ms for ${l.name}`);c.metrics=s}return c}catch(c){let s=Date.now()-i;throw Kt.error(`Configuration loading failed after ${s}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:l,defaultConfig:c,checkEnv:s=!0,arrayStrategy:h="replace",verbose:u=!1}=t,$=f||Ri.cwd(),w=[],y=await this.loadLocalConfiguration(n,e,$,l,c,h,u,s,r);if(y)return w.push(...this.getLocalSearchPaths(n,e,$,l)),this.finalizeResult(y,w,s,n,u);let A=await this.loadHomeConfiguration(n,e,c,h,u,s);if(A)return w.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(A,w,s,n,u);let a=await this.loadPackageJsonConfiguration(n,e,$,c,h,u,s);if(a)return w.push(at($,"package.json")),this.finalizeResult(a,w,s,n,u);if(w.push(...this.getAllSearchPaths(n,e,$,l)),i)throw wi.configNotFound(n,w,e);return{...await this.applyEnvironmentVariables(n,c,s,u),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,l,c,s){let h=c?Er(t,e,l):e,u=this.getLocalDirectories(r,n);for(let $ of u){if(l)Kt.info(`Searching for configuration in: ${$}`);let w=this.fileLoader.generateConfigPaths(t,$,i),y=await this.fileLoader.tryLoadFromPaths(w,h,{arrayStrategy:f,verbose:l,cacheTtl:s?.ttl,useCache:!s?.ttl||s.ttl>100});if(y){if(l)Kt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let l=f?Er(t,r,e):r,c=[at(gi(),".config",t),at(gi(),".config"),gi()];for(let s of c){if(e)Kt.info(`Checking home directory: ${s}`);let h=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:n,verbose:e});if(u){if(e)Kt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,l){let c=l?Er(t,n,f):n;try{let s=at(r,"package.json");if(!ef(s))return null;let h=await import(s),u=h[t],$=t;if(!u&&i)u=h[i],$=i;if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)Kt.success(`Configuration loaded from package.json: ${$}`);return{config:Uf(c,u,e),source:{type:"package.json",path:s,priority:30,timestamp:new Date}}}}catch(s){if(f)Kt.warn("Failed to load package.json:",[s instanceof Error?s:Error(String(s))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Er(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(e.length>0)throw wi.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return qi.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);qi.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,at(t,"config"),at(t,".config"),i?at(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(at(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let l of e)f.push(...this.fileLoader.generateConfigPaths(t,l,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[at(gi(),".config",t),at(gi(),".config"),gi()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function Lc(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||r}async function wy(t){return ii.loadConfig({...t,__strictErrorHandling:!0})}async function Xs(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await ii.loadConfig(t);else n=await ii.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)Kt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let l=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ii.applyEnvironmentVariables(l.name||"",i,!0,l.verbose||!1))?.config??i;return i}}async function ay(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ii.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&Lc(r)))return(await ii.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await ii.loadConfig({...t,cwd:t.cwd||Ri.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&Lc(i)))return(await ii.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function my(t,i,r="replace"){let n=new Wn;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function Er(t,i,r=!1){let n=new Nn,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(l,c=[]){let s={...l};for(let[h,u]of Object.entries(l)){let $=[...c,h],w=[`${e}_${$.join("_").toUpperCase()}`,`${e}_${$.map((a)=>a.toUpperCase()).join("")}`,`${e}_${$.map((a)=>a.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,A;for(let a of w)if(y=Ri.env[a],y!==void 0){A=a;break}if(y!==void 0&&A)if(typeof u==="boolean")s[h]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let a=Number(y);if(!Number.isNaN(a))s[h]=a}else if(Array.isArray(u))try{s[h]=JSON.parse(y)}catch{s[h]=y.split(",").map((a)=>a.trim())}else s[h]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))s[h]=f(u,$)}return s}return f(i)}function Ay(t){let i=at(Ri.cwd(),t.configDir),r=at(Ri.cwd(),t.generatedDir),n=at(r,"config-types.ts");if(!ef(oc(n)))n$(oc(n),{recursive:!0,mode:511});let e=ef(i)?e$(i).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${ky}
35
- export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
36
- `;f$(n,f,{mode:438})}function Ey(t){let i=null,r=null,n=()=>{if(!r)r=Xs(t).then((f)=>{return i=f,f},(f)=>{let l="defaultConfig"in t?t.defaultConfig:{};if(i=l,"verbose"in t&&t.verbose)Kt.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return l});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,l){if(i)return i[l];let c=e[l];return n(),c},has(f,l){return l in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,l){return Object.getOwnPropertyDescriptor(i||e,l)},set(f,l,c){if(!i)i={...e};return i[l]=c,!0}})}function Ty(t){let i=_c(N$.cwd(),t?.configDir||"./config");function r(){if(!F$(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=j$(i).filter((s)=>e.has(qe(s))).map((s)=>({base:s.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:s})),c=new Map;for(let{base:s,file:h}of l){let u=qe(h).toLowerCase(),$=c.get(s);if(!$){c.set(s,h);continue}let w=qe($).toLowerCase();if(f.indexOf(u)<f.indexOf(w))c.set(s,h)}return Array.from(c.entries()).map(([s,h])=>({base:s,file:h})).sort((s,h)=>s.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((s)=>s.base),l=f.length?f.map((s)=>`'${s}'`).join(" | "):"string",c=e.length?`{
37
- ${e.map((s)=>{let h=_c(i,s.file).replace(/\\/g,"/");return` '${s.base}': typeof import('${h}').default`}).join(`,
38
- `)}
39
- }`:"Record<string, any>";return`export type ConfigNames = ${l}
40
- export type ConfigByName = ${c}
41
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
42
- export type ConfigOf = Config
43
- `}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var gs,qi,Rr,Js,oy,dy,qc,fn,cf,ct,L,Yy,xc,By,kc,Cy,Ry,be,Sy,Vc,Dc,Pe,Uy,Fy,jy,Ny,ln,_s,Wy,st,Xy,gy,bc,cn,sf,Z,g,Jy,Pc,_y,Qc,Iy,Ky,Qe,zy,pc,vc,Oy,pe,My,Gy,Hy,Ly,qy,sn,Is,xy,ky="0.15.6",Yt,dn,Yr,hf,uf,Yn,$f,yf,Br,wf,af,wi,Ks,zs,Kt,ii,Os,Ms,Vy=V$(async()=>{gs=import.meta.require,qi=new Bf,Rr=new Cf,Js={createKey:D$,isEquivalent:b$,estimateMemoryUsage:P$},oy=wn(ff.cwd(),"config"),dy=wn(ff.cwd(),"src/generated"),qc=yn.env.CLARITY_LOG_DIR||s$(v$(),"logs"),fn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:qc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},cf=await Z$(),ct={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},L=ct,Yy=ct.red,xc=ct.green,By=ct.yellow,kc=ct.blue,Cy=ct.magenta,Ry=ct.cyan,be=ct.white,Sy=ct.gray,Vc=ct.bgRed,Dc=ct.bgYellow,Pe=ct.bold,Uy=ct.dim,Fy=ct.italic,jy=ct.underline,Ny=ct.reset,ln={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_s={debug:"\uD83D\uDD0D",info:kc("ℹ"),success:xc("✓"),warning:Dc(be(Pe(" WARN "))),error:Vc(be(Pe(" ERROR ")))},Wy=new En("stacks"),st=new En("bunfig",{showTags:!0}),Xy=wt(dr.cwd(),"config"),gy=wt(dr.cwd(),"src/generated"),bc=$n.env.CLARITY_LOG_DIR||l$(ny(),"logs"),cn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bc,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},sf=await ey(),Z={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},g=Z,Jy=Z.red,Pc=Z.green,_y=Z.yellow,Qc=Z.blue,Iy=Z.magenta,Ky=Z.cyan,Qe=Z.white,zy=Z.gray,pc=Z.bgRed,vc=Z.bgYellow,Oy=Z.bgGray,pe=Z.bold,My=Z.dim,Gy=Z.italic,Hy=Z.underline,Ly=Z.strikethrough,qy=Z.reset,sn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Is={debug:"\uD83D\uDD0D",info:Qc("ℹ"),success:Pc("✓"),warning:vc(Qe(pe(" WARN "))),error:pc(Qe(pe(" ERROR ")))},xy=new on("stacks"),Yt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,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(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},dn=class extends Yt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}},Yr=class extends Yt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},hf=class extends Yt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}},uf=class extends Yt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Yn=class extends Yt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}},$f=class extends Yt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}},yf=class extends Yt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Br=class extends Yt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}},wf=class extends Yt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}},af=class extends Yt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}},wi={configNotFound(t,i,r){return new dn(t,i,r)},configLoad(t,i,r){return new Yr(t,i,r)},configValidation(t,i,r){return new hf(t,i,r)},configMerge(t,i,r,n){return new uf(t,i,r,n)},envVar(t,i,r,n){return new Yn(t,i,r,n)},fileSystem(t,i,r){return new $f(t,i,r)},typeGeneration(t,i,r){return new yf(t,i,r)},schemaValidation(t,i,r){return new Br(t,i,r)},browserConfig(t,i,r,n){return new wf(t,i,r,n)},plugin(t,i,r){return new af(t,i,r)}},Ks={replace:"replace",concat:"concat",smart:"smart"},zs=/^https?:\/\//,Kt=new on("bunfig",{showTags:!0}),ii=new jf,Os=at(Ri.cwd(),"config"),Ms=at(Ri.cwd(),"src/generated")});function Dy(t,i={}){let r=an.cwd();while(r.includes("storage"))r=Ic(r,"..");let n=Ic(r,t||"");if(i?.relative)return X$(an.cwd(),n);return n}var by=an.env.CLARITY_LOG_DIR||W$(Dy(),"logs"),Gs={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:by,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Bn={...Gs},tT=(async()=>{try{let{loadConfig:t}=await Vy().then(()=>Cs),i=await t({name:"clarity",alias:"logging",defaultConfig:Gs,cwd:an.cwd()});if(i)Object.assign(Bn,i)}catch{}return Bn})();function tt(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Py(){if(Zt.env.NODE_ENV==="test"||Zt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Zt<"u"){let t=Zt.type;if(t==="renderer"||t==="worker")return!1;return!!(Zt.versions&&(Zt.versions.node||Zt.versions.bun))}return!1}class Hs{async format(t){let i=await Py(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Hi.pid,hostname:i(),environment:Hi.env.NODE_ENV||"development",platform:Hi.platform,version:Hi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Hi.env.NODE_ENV||Hi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var et={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},_=et,iT=et.red,Qy=et.green,rT=et.yellow,py=et.blue,nT=et.magenta,eT=et.cyan,Zc=et.white,fT=et.gray,vy=et.bgRed,Zy=et.bgYellow,lT=et.bgGray,ts=et.bold,cT=et.dim,sT=et.italic,hT=et.underline,uT=et.strikethrough,$T=et.reset,ve={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tw={debug:"\uD83D\uDD0D",info:py("ℹ"),success:Qy("✓"),warning:Zy(Zc(ts(" WARN "))),error:vy(Zc(ts(" ERROR ")))};class Xn{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(t,i={}){this.name=t,this.config={...Bn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Hs,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...ve,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...ve};return{...ve,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Bn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!tt()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,l=1000;while(e<f)try{try{try{await K$(this.config.logDirectory,Mc.F_OK|Mc.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await z$(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Pt.from(t);try{if(!Pr(this.currentLogFile))await Ve(this.currentLogFile,"",{mode:420});if(n=Oc(this.currentLogFile,"a",420),I$(n,c,{flag:"a"}),zc(n),n!==void 0)ke(n),n=void 0;if((await Mi(this.currentLogFile)).size===0){if(await Ve(this.currentLogFile,c,{flag:"w",mode:420}),(await Mi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let h=s;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let u=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,u);let $=l*2**e;await new Promise((w)=>setTimeout(w,$)),e++;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(n!==void 0)try{ke(n)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(c){if(e===f-1){let h=c,u=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}e++;let s=l*2**(e-1);await new Promise((h)=>setTimeout(h,s))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}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 Gi(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 Gi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Gi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(tt())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,l],[,c])=>c.createdAt.getTime()-l.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[l]of n.slice(f))this.encryptionKeys.delete(l),this.keys.delete(l)}generateKeyId(){return xe(16).toString("hex")}generateKey(){return xe(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=xe(16),n=g$("aes-256-gcm",i,r),e=Pt.isBuffer(t)?t:Pt.from(t,"utf8"),f=n.update(e),l=n.final(),c=f.length+l.length,s=n.getAuthTag(),h=Pt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),l.copy(h,16+f.length),s.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Hc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Pt.from(Pt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(tt())return;if(!this.shouldWriteToFile())return;let t=await Mi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Qr(this.config.logDirectory),f=e.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,h)=>{let u=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),l=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${l}`;if(await Mi(r).catch(()=>null))try{if(await Gc(r,c),i.compress)try{let s=`${c}.gz`;await this.compressLogFile(c,s),await pr(c)}catch(s){console.error("Error compressing rotated file:",s)}if(f.length===0&&!e.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await Ve(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Mi(r).catch(()=>null))await Gc(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await Qr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,l)=>l.localeCompare(f));for(let f of e.slice(i.maxFiles))await pr(Gi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Kc(t),n=_$(i),e=Hc();await G$(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Pr(this.currentLogFile))try{let t=Oc(this.currentLogFile,"r+");zc(t),ke(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!tt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Qr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await pr(Gi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?_.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||tt())return!1;let t=typeof z.env.NO_COLOR<"u",i=z.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof z.stderr<"u"&&z.stderr.isTTY||typeof z.stdout<"u"&&z.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:l=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(l)y.push(i);if(f==="warning")y.push("WARN");else if(f==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(e),y.join(" ")}let s=z.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${_.cyan(e)}`;if(!l)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,s-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,l)=>{let c=Number.parseInt(l,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,l)=>{if(l==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(l){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=_.underline(_.blue(n)),l=this.toAbsoluteFilePath(e);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(l)}`,s="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>_.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>_.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>_.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>_.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>_.strikethrough(n)),i}supportsHyperlinks(){if(tt())return!1;let t=z.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=z.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(O$(i)||i.startsWith("./")||i.startsWith("../"))i=M$(i);else return null;return Pr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),l,c;if(i instanceof Error)l=i.message,c=i.stack;else l=this.formatMessage(i,r);let{consoleText:s,fileText:h}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":tw[t],w=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:_.gray(s),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:_.green(s),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.error(y),c){let A=c.split(`
44
- `);for(let a of A)if(a.trim()&&!a.includes(l))console.error(this.formatConsoleMessage({timestamp:e,message:_.gray(` ${a}`),level:t,showTimestamp:!1}))}break}}else if(!tt()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${l}`),c)console.error(c)}let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
45
- `;if(c)u+=`${c}
46
- `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!tt()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!tt()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!tt()&&z.stdout.isTTY)z.stdout.write(`
47
- `);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!tt()&&z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":_.blue("◐"),tag:r,message:`${_.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,l=new Date,c=this.formatConsoleTimestamp(l),s=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${f}`;if(r)s+=` ${JSON.stringify(r)}`;if(s+=`
48
- `,s=s.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":_.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!tt())console.error(s.trim());if(this.shouldWriteToFile())await this.writeToFile(s)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Xn(i,{...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(r),r}createReadStream(){if(tt())throw Error("createReadStream is not supported in browser environments");if(!Pr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Kc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Pt.isBuffer(t)?t:Pt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),l=n.subarray(16,n.length-16),c=J$("aes-256-gcm",r,e);c.setAuthTag(f);let s=c.update(l),h=c.final(),u=s.length+h.length,$=Pt.allocUnsafe(u);return s.copy($,0),h.copy($,s.length),$.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return tt()}isServerMode(){return!tt()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
49
- `),s=Math.max(...c.map((w)=>w.length))+2,h=`┌${"─".repeat(s)}┐`,u=`└${"─".repeat(s)}┘`,$=c.map((w)=>{return this.formatConsoleMessage({timestamp:r,message:_.cyan(w),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:_.cyan(h),showTimestamp:!1})),$.forEach((w)=>console.error(w)),console.error(this.formatConsoleMessage({timestamp:r,message:_.cyan(u),showTimestamp:!1}))}else if(!tt())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let l=`${n} ${this.environment}.INFO: [BOX] ${f}
50
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(t){if(tt())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${_.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();z.stdin.removeListener("data",r);try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!1)}catch{}z.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof z.stdin.setRawMode==="function")z.stdin.setRawMode(!0)}catch{}z.stdin.resume(),z.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,c=0;if(r=t.replace(l,(s,h)=>{if(h==="%")return"%";if(c>=i.length)return s;let u=i[c++];switch(h){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return s}}),c<i.length)r+=` ${i.slice(c).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${_.blue("◐")} `;console.error(`${c}${l} ${_.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
51
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!z.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=_.green("━".repeat(n)),l=_.gray("━".repeat(e)),c=`[${f}${l}]`,s=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?_.green("✓"):_.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${_.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${s}${h}`,y=z.stdout.columns||80,A=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${A}`,z.stdout.write(t.lastRenderedLine),i)z.stdout.write(`
52
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||tt()||!z.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(tt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Qr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Gi(this.config.logDirectory,n);if(t.before)try{if((await Mi(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await pr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var yT=new Xn("stacks");class Mt extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,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(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class Ls extends Mt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class Cn extends Mt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class qs extends Mt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class xs extends Mt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Nf extends Mt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class ks extends Mt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Vs extends Mt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Rn extends Mt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class Ds extends Mt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class bs extends Mt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var xi={configNotFound(t,i,r){return new Ls(t,i,r)},configLoad(t,i,r){return new Cn(t,i,r)},configValidation(t,i,r){return new qs(t,i,r)},configMerge(t,i,r,n){return new xs(t,i,r,n)},envVar(t,i,r,n){return new Nf(t,i,r,n)},fileSystem(t,i,r){return new ks(t,i,r)},typeGeneration(t,i,r){return new Vs(t,i,r)},schemaValidation(t,i,r){return new Rn(t,i,r)},browserConfig(t,i,r,n){return new Ds(t,i,r,n)},plugin(t,i,r){return new bs(t,i,r)}};async function iw(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,l=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(s){if(l=s instanceof Error?s:Error(String(s)),c===r||!e(l))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class Wf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:l={},verbose:c=!1,trackPerformance:s=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(t),$={...i};return this.processObject($,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:l,verbose:c,configName:t}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(s)return Yf.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let l=[...i,e],c=l.map((u)=>this.formatEnvKey(u,n.useCamelCase)),s=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${l.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,l,r,n);else{let u=vr.env[s]||(h?vr.env[h]:void 0);if(u!==void 0){if(n.verbose){let $=vr.env[s]?s:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,s,n.customParsers,n.configName)}catch($){if($ instanceof Nf)throw $;throw xi.envVar(s,u,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,l]of Object.entries(n))try{return l(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw xi.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(vr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),l=[];switch(this.extractEnvVarInfo(i,[],f,l),e){case"markdown":return this.formatAsMarkdown(l,t);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let l=[...i,e],c=`${r}_${l.map((s)=>this.formatEnvKey(s,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,l,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${l.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
53
-
54
- `;for(let n of t)r+=`${n.key}
55
- `,r+=` Type: ${n.type}
56
- `,r+=` Description: ${n.description}
57
- `,r+=` Example: ${n.example}
58
-
59
- `;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
60
-
61
- `;r+=`| Variable | Type | Description | Example |
62
- `,r+=`|----------|------|-------------|----------|
63
- `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
64
- `;return r}}function rw(t,i,r={}){return Ps(t,i,r,new WeakMap)}function Ps(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:l}=r;if(i===null||i===void 0)return f?t:i;if(l){let c=l(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Qs(t,i,e,n);if(!Nt(i)||!Nt(t))return i;return lw(t,i,r,n)}function Qs(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return nw(t,i);case"smart":return ew(t,i,n);default:return i}return i}function nw(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>mf(e,n)))r.push(n);return r}function ew(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Nt(i[0])&&Nt(t[0]))return fw(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function fw(t,i,r){let n=[...i];for(let e of t){if(!Nt(e)){n.push(e);continue}let f=["id","name","key","path","type"],l=!1;for(let c of f)if(c in e){if(n.find((s)=>Nt(s)&&(c in s)&&s[c]===e[c])){l=!0;break}}if(!l)n.push(e)}return n}function lw(t,i,r,n){let e=i;if(Nt(e)&&n.has(e))return n.get(e);let f={...t};if(Nt(e))n.set(e,f);for(let l in e){if(!Object.prototype.hasOwnProperty.call(e,l))continue;let c=e[l],s=f[l];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[l]=c;continue}if(Nt(c)&&Nt(s))f[l]=Ps(s,c,r,n);else if(Array.isArray(c)||Array.isArray(s))f[l]=Qs(s,c,r.arrayMergeMode||"smart",n);else f[l]=c}return f}function ps(t,i,r="replace"){return rw(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function mf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!mf(t[r],i[r]))return!1;return!0}if(Nt(t)&&Nt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!mf(t[e],i[e]))return!1}return!0}return!1}function Nt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class vs{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:l=!0,verbose:c=!1}=r;if(e){let h=mn.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let s=async()=>{if(!Zr(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),$=u.default||u,w="default"in u,y=Object.keys(u).length>0;if(!w&&!y)throw new Cn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Cn(t,Error("Configuration must export a valid object"),"unknown");let A={config:ps(i,$,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)mn.setWithFileCheck("file",A,t,f);return A}catch(h){throw h instanceof Error?xi.configLoad(t,h):xi.configLoad(t,Error(String(h)))}};if(l)return Yf.track("loadFromPath",s,{path:t});return s()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let l of this.extensions)e.push(De(i,`${f}${l}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return iw(async()=>{return Zr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Zr(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let l of this.extensions){let c=De(t,`${f}${l}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let l of f)if(this.looksLikeConfigFile(l)){let c=De(t,l);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Zr(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var cw=/^https?:\/\//;class Zs{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:l=[],trackPerformance:c=!0,verbose:s=!1}=r,h=async()=>{let u=[],$=[],w={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:l,trackPerformance:c,verbose:s};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,w);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...l],w);else return this.validateWithJSONSchema(t,i,w)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:$}}};if(c)return await Yf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!H$(i))throw new Rn(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new Rn(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let l=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(l)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${l}`,expected:c.join(" or "),actual:l,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let l=0;l<t.length;l++){let c=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(t[l],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let l=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in l)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,s]of Object.entries(i.properties))if(c in l){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(l[c],s,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let s of Object.keys(l))if(!c.has(s))e.push({path:r?`${r}.${s}`:s,message:`Additional property '${s}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let l=this.getValueByPath(t,f.path),c=this.validateWithRule(l,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:f.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,l]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(l)})}return i}mapTypeScriptType(t){switch(t.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:cw},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Qt=new Xn("bunfig",{showTags:!0});function sw(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class th{fileLoader=new vs;envProcessor=new Wf;validator=new Zs;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...l}=t;try{if(r?.enabled){let s=this.checkCache(l.name||"",l);if(s)return s}let c;try{c=await this.loadConfigurationStrategies(l,!0,r)}catch(s){let h=l.__strictErrorHandling;if(s instanceof Error&&s.name==="ConfigNotFoundError"){if(h)throw s;c={...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(s instanceof Error&&s.name==="ConfigLoadError"){let u=s.message.includes("EACCES")||s.message.includes("EPERM")||s.message.includes("permission denied"),$=!u&&(s.message.includes("syntax")||s.message.includes("Expected")||s.message.includes("Unexpected")||s.message.includes("BuildMessage")||s.message.includes("errors building")),w=s.message.includes("Configuration must export a valid object")||s.message.includes("Configuration file is empty and exports nothing");if(h&&(w||u))throw s;if($&&(!h||!w))c={...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(!h)c={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${s.message}`]};else throw s}else c={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${s instanceof Error?s.message:String(s)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,l.name);if(r?.enabled&&c)this.cacheResult(l.name||"",c,r,l);if(n?.enabled){let s={operation:"loadConfig",duration:Date.now()-i,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(s);if(n.slowThreshold&&s.duration>n.slowThreshold)Qt.warn(`Slow configuration loading detected: ${s.duration}ms for ${l.name}`);c.metrics=s}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let s=Date.now()-i;throw Qt.error(`Configuration loading failed after ${s}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:l,defaultConfig:c,checkEnv:s=!0,arrayStrategy:h="replace",verbose:u=!1}=t,$=f||jn.cwd(),w=[],y=await this.loadLocalConfiguration(n,e,$,l,c,h,u,s,r);if(y)return w.push(...this.getLocalSearchPaths(n,e,$,l)),this.finalizeResult(y,w,s,n,u);let A=await this.loadHomeConfiguration(n,e,c,h,u,s);if(A)return w.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(A,w,s,n,u);let a=await this.loadPackageJsonConfiguration(n,e,$,c,h,u,s);if(a)return w.push(Ft($,"package.json")),this.finalizeResult(a,w,s,n,u);if(w.push(...this.getAllSearchPaths(n,e,$,l)),i)throw xi.configNotFound(n,w,e);return{...await this.applyEnvironmentVariables(n,c,s,u),warnings:[`No configuration file found for "${n}"${sw(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,l,c,s){let h=c?rn(t,e,l):e,u=this.getLocalDirectories(r,n);for(let $ of u){if(l)Qt.info(`Searching for configuration in: ${$}`);let w=this.fileLoader.generateConfigPaths(t,$,i),y=await this.fileLoader.tryLoadFromPaths(w,h,{arrayStrategy:f,verbose:l,cacheTtl:s?.ttl,useCache:!s?.ttl||s.ttl>100});if(y){if(l)Qt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let l=f?rn(t,r,e):r,c=[Ft(Xi(),".config",t),Ft(Xi(),".config"),Xi()];for(let s of c){if(e)Qt.info(`Checking home directory: ${s}`);let h=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:n,verbose:e});if(u){if(e)Qt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,l){let c=l?rn(t,n,f):n;try{let s=Ft(r,"package.json");if(!i$(s))return null;let h={};try{h=JSON.parse(r$(s,"utf8"))}catch(w){if(f)Qt.warn("Failed to parse package.json:",[w instanceof Error?w:Error(String(w))]);return null}let u=h[t],$=t;if(!u&&i){let w=Array.isArray(i)?i:[i];for(let y of w){if(!y)continue;if(h[y]){u=h[y],$=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)Qt.success(`Configuration loaded from package.json: ${$}`);return{config:ps(c,u,e),source:{type:"package.json",path:s,priority:30,timestamp:new Date}}}}catch(s){if(f)Qt.warn("Failed to load package.json:",[s instanceof Error?s:Error(String(s))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:rn(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(e.length>0)throw xi.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return mn.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);mn.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Ft(t,"config"),Ft(t,".config"),i?Ft(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Ft(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let l of e)f.push(...this.fileLoader.generateConfigPaths(t,l,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Ft(Xi(),".config",t),Ft(Xi(),".config"),Xi()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var wT=new th;function rn(t,i,r=!1){let n=new Wf,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(l,c=[]){let s={...l};for(let[h,u]of Object.entries(l)){let $=[...c,h],w=[`${e}_${$.join("_").toUpperCase()}`,`${e}_${$.map((a)=>a.toUpperCase()).join("")}`,`${e}_${$.map((a)=>a.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,A;for(let a of w)if(y=jn.env[a],y!==void 0){A=a;break}if(y!==void 0&&A)if(typeof u==="boolean")s[h]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let a=Number(y);if(!Number.isNaN(a))s[h]=a}else if(Array.isArray(u))try{s[h]=JSON.parse(y)}catch{s[h]=y.split(",").map((a)=>a.trim())}else s[h]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))s[h]=f(u,$)}return s}return f(i)}var aT=Ft(jn.cwd(),"config"),mT=Ft(jn.cwd(),"src/generated"),ih={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:Je.join(ge.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:Je.join(ge.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:Je.join(ge.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},p=ih,zt={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 S={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Li={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function nh(t){return Af.readFileSync(t,"utf8")}function Ef(t,i){let r=[];function n(e){let f;try{f=Af.readdirSync(e)}catch{return}for(let l of f){let c=It.join(e,l);try{if(Af.statSync(c).isDirectory())n(c);else if(l===i)r.push(e)}catch{continue}}}return n(t),r}function C(t,i,r){if(r||p.verbose)console.debug(`[tlsx:${t}] ${i}`)}var yw=$w(hw);function eh(){return rh.env.SUDO_PASSWORD}var is="[redacted]",ww=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),aw=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function mw(t){let i=t.toLowerCase();return ww.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function Sn(t){if(Array.isArray(t))return t.map((r)=>Sn(r));if(typeof t==="string")return aw.test(t)?is:t;if(!t||typeof t!=="object")return t;let i={};for(let[r,n]of Object.entries(t)){if(mw(r)){i[r]=is;continue}i[r]=Sn(n)}return i}function gn(t){return JSON.stringify(Sn(t))}function Aw(t){let i=eh();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let r=i.replace(/'/g,"'\\''"),n=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function yi(t,i={}){let r=Aw(t);try{let{stdout:n,stderr:e}=await yw(r,{cwd:i.cwd||rh.cwd(),timeout:i.timeout||30000});return{stdout:n.trim(),stderr:e.trim()}}catch(n){let e=Error(`Failed to execute command: ${t}
65
- Error: ${n.message}`);throw e.stack=n.stack,e}}function fh(t){if(t.domain)return t.domain;if(t.domains?.length)return t.domains[0];throw Error("Either domain or domains must be specified")}function Xf(t){let i=It.join(uw.homedir(),".stacks","ssl"),r=t.basePath&&t.basePath.trim()!==""?t.basePath:p.basePath&&p.basePath.trim()!==""?p.basePath:i,n=t.certPath?It.isAbsolute(t.certPath)?t.certPath:It.join(r,t.certPath):It.join(r,p.certPath),e=t.keyPath?It.isAbsolute(t.keyPath)?t.keyPath:It.join(r,t.keyPath):It.join(r,p.keyPath),f=t.caCertPath?It.isAbsolute(t.caCertPath)?t.caCertPath:It.join(r,t.caCertPath):It.join(r,p.caCertPath);return{certPath:n,keyPath:e,caCertPath:f,basePath:r}}function lh(t){let i=[],r=new Set;if(t.domain)r.add(t.domain);if(t.domains?.length)t.domains.forEach((n)=>r.add(n));for(let n of r)i.push({type:2,value:n});if(t.altNameIPs?.length)for(let n of t.altNameIPs)i.push({type:7,ip:n});if(t.altNameURIs?.length)for(let n of t.altNameURIs)i.push({type:6,value:n});if(t.subjectAltNames?.length)i.push(...t.subjectAltNames);return C(S.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function gf(t){let i=t.notBeforeDays??zt.DEFAULT_NOT_BEFORE_DAYS,r=t.validityDays??(t.validityYears?t.validityYears*365:zt.DEFAULT_VALIDITY_DAYS);C(S.CERT,"Calculating certificate validity dates",t.verbose);let n=new Date(Date.now()-86400*i*1000),e=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),e.setUTCHours(23,59,59,999),C(S.CERT,`Validity period: ${n.toISOString()} to ${e.toISOString()}`,t.verbose),{notBefore:n,notAfter:e}}var Ot={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},mt={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 Tr(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function Ct(t,i){let r=Tr(i.length);return Buffer.concat([Buffer.from([t]),r,i])}function Cr(t){let i=t.split(".").map(Number),r=[];r.push(40*i[0]+i[1]);for(let n=2;n<i.length;n++){let e=i[n],f=[];f.unshift(e&127),e>>=7;while(e>0)f.unshift(e&127|128),e>>=7;r.push(...f)}return Ct(Ot.OID,Buffer.from(r))}function Tf(t){let i;if(typeof t==="bigint"){let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else i=t;if(i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return Ct(Ot.INTEGER,i)}function ch(t,i=0){return Ct(Ot.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function sh(t){return Ct(Ot.OCTET_STRING,t)}function Bt(...t){return Ct(Ot.SEQUENCE,Buffer.concat(t))}function Ew(...t){return Ct(Ot.SET,Buffer.concat(t))}function Tw(t){return Ct(Ot.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function ow(t){return Ct(Ot.UTF8_STRING,Buffer.from(t,"utf8"))}function dw(){return Buffer.from([Ot.NULL,0])}function rs(t,i,r=!0){let n=160|t|(r?0:0),e=Tr(i.length);return Buffer.concat([Buffer.from([n]),e,i])}function ns(t){let i=t.getUTCFullYear();if(i>=2050){let r=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Ct(Ot.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(i%100).toString().padStart(2,"0"),n=(t.getUTCMonth()+1).toString().padStart(2,"0"),e=t.getUTCDate().toString().padStart(2,"0"),f=t.getUTCHours().toString().padStart(2,"0"),l=t.getUTCMinutes().toString().padStart(2,"0"),c=t.getUTCSeconds().toString().padStart(2,"0"),s=`${r}${n}${e}${f}${l}${c}Z`;return Ct(Ot.UTC_TIME,Buffer.from(s,"ascii"))}}function Yw(t,i){return Bt(ns(t),ns(i))}function es(t){let i=[];for(let r of t){let n;switch(r.shortName){case"CN":n=mt.COMMON_NAME;break;case"C":n=mt.COUNTRY;break;case"L":n=mt.LOCALITY;break;case"ST":n=mt.STATE;break;case"O":n=mt.ORGANIZATION;break;case"OU":n=mt.ORGANIZATIONAL_UNIT;break;default:continue}let e=r.shortName==="C"?Tw(r.value):ow(r.value),f=Bt(Cr(n),e);i.push(Ew(f))}return Bt(...i)}function hh(t){return Bt(Cr(t),dw())}function Bw(t){return t.export({type:"spki",format:"der"})}function Cw(t){if(t.includes(":")){let i=t;if(t.includes("::")){let e=t.split("::"),f=e[0]?e[0].split(":"):[],l=e[1]?e[1].split(":"):[],c=8-f.length-l.length,s=Array.from({length:c},()=>"0");i=[...f,...s,...l].join(":")}let r=i.split(":"),n=Buffer.alloc(16);for(let e=0;e<8;e++){let f=Number.parseInt(r[e]||"0",16);n.writeUInt16BE(f,e*2)}return n}else{let i=t.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(i)}}function Rw(t){let i=[];for(let r of t)if(r.type===2&&r.value){let n=Tr(r.value.length);i.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=Cw(r.ip),e=Tr(n.length);i.push(Buffer.concat([Buffer.from([135]),e,n]))}else if(r.type===6&&r.value){let n=Tr(r.value.length);i.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return Bt(...i)}function Sw(t,i){if(t){if(i!==void 0)return Bt(Ct(1,Buffer.from([255])),Tf(i));return Bt(Ct(1,Buffer.from([255])))}return Bt()}function Uw(t){let i=0;if(t.digitalSignature)i|=128;if(t.keyEncipherment)i|=32;if(t.keyCertSign)i|=4;if(t.cRLSign)i|=2;let r=0,n=i;while(n>0&&(n&1)===0)r++,n>>=1;if(i===0)r=7;return ch(Buffer.from([i]),r)}function Fw(t){let i=[];if(t.serverAuth)i.push(Cr(mt.SERVER_AUTH));if(t.clientAuth)i.push(Cr(mt.CLIENT_AUTH));return Bt(...i)}function Ar(t,i,r){let n=[Cr(t)];if(i)n.push(Ct(1,Buffer.from([255])));return n.push(sh(r)),Bt(...n)}function jw(t){let i=[];if(i.push(rs(0,Tf(2))),i.push(Tf(t.serialNumber)),i.push(hh(mt.SHA256_WITH_RSA)),i.push(es(t.issuer)),i.push(Yw(t.notBefore,t.notAfter)),i.push(es(t.subject)),i.push(Bw(t.publicKey)),t.extensions){let r=[];if(t.extensions.basicConstraints)r.push(Ar(mt.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,Sw(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)r.push(Ar(mt.KEY_USAGE,t.extensions.keyUsage.critical??!0,Uw(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)r.push(Ar(mt.EXTENDED_KEY_USAGE,!1,Fw(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)r.push(Ar(mt.SUBJECT_ALT_NAME,!1,Rw(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)r.push(Ar(mt.SUBJECT_KEY_IDENTIFIER,!1,sh(t.extensions.subjectKeyIdentifier)));if(r.length>0)i.push(rs(3,Bt(...r)))}return Bt(...i)}function Nw(t,i){let r=ki.createSign("SHA256");r.update(t);let n=r.sign(i);return Bt(t,hh(mt.SHA256_WITH_RSA),ch(n))}function Ww(t,i){let r=t.toString("base64"),n=[];for(let e=0;e<r.length;e+=64)n.push(r.slice(e,e+64));return`-----BEGIN ${i}-----
66
- ${n.join(`
67
- `)}
68
- -----END ${i}-----
69
- `}function Jf(){let t=ki.randomBytes(20);return t[0]=t[0]&127||1,t}function uh(t=2048){let{privateKey:i,publicKey:r}=ki.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:r}}function Xw(t){let i=t.export({type:"spki",format:"der"});return ki.createHash("sha1").update(i).digest()}function $h(t){let i={serialNumber:t.serialNumber||Jf(),notBefore:t.notBefore,notAfter:t.notAfter,subject:t.subject,issuer:t.issuer||t.subject,publicKey:t.publicKey,extensions:{basicConstraints:{isCA:t.isCA??!1,critical:!0,pathLenConstraint:t.pathLenConstraint},subjectKeyIdentifier:Xw(t.publicKey)}};if(t.keyUsage)i.extensions.keyUsage={...t.keyUsage,critical:!0};if(t.extendedKeyUsage)i.extensions.extendedKeyUsage=t.extendedKeyUsage;if(t.subjectAltName?.length)i.extensions.subjectAltName=t.subjectAltName;let r=jw(i),n=Nw(r,t.signingKey);return{certificate:Ww(n,"CERTIFICATE"),certificateDer:n}}function yh(t){return t.export({type:"pkcs8",format:"pem"})}function gw(t){return ki.createPrivateKey(t)}function Jw(t){let i=new ki.X509Certificate(t),r=i.publicKey,n=[],e=i.subject.split(`
70
- `);for(let f of e){let[l,...c]=f.split("="),s=c.join("=");if(l&&s)n.push({shortName:l.trim(),value:s.trim()})}return{publicKey:r,subject:n}}async function _f(t={}){C("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||zt.DEFAULT_KEY_SIZE;C("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:r,publicKey:n}=uh(i),e=[{shortName:"C",value:t.countryName||p.countryName},{shortName:"ST",value:t.stateName||p.stateName},{shortName:"L",value:t.localityName||p.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:f,notAfter:l}=gf({validityYears:t.validityYears||zt.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:c}=$h({serialNumber:Jf(),notBefore:f,notAfter:l,subject:e,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:yh(r),notBefore:f,notAfter:l}}async function If(t){if(C("ca","Generating new certificate",t.verbose),C("ca",`Options: ${gn(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=Jw(t.rootCA.certificate),r=gw(t.rootCA.privateKey);C("ca",`Generating ${zt.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let n=zt.DEFAULT_KEY_SIZE,{privateKey:e,publicKey:f}=uh(n),l=t.commonName||fh(t),c=t.certificateAttributes||[{shortName:"C",value:t.countryName||p.countryName},{shortName:"ST",value:t.stateName||p.stateName},{shortName:"L",value:t.localityName||p.localityName},{shortName:"O",value:t.organizationName||p.organizationName},{shortName:"CN",value:l}],{notBefore:s,notAfter:h}=gf({validityDays:t.validityDays||zt.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),u=lh(t),$=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},w=t.extKeyUsage||{serverAuth:!0},{certificate:y}=$h({serialNumber:Jf(),notBefore:s,notAfter:h,subject:c,issuer:i,publicKey:f,signingKey:r,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:$,extendedKeyUsage:w,subjectAltName:u});return{certificate:y,privateKey:yh(e),notBefore:s,notAfter:h}}function wh(t,i){C(S.STORAGE,`Storing certificate and private key with options: ${gn(i)}`,i?.verbose);let{certPath:r,keyPath:n}=Xf({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});C(S.STORAGE,`Certificate path: ${r}`,i?.verbose),C(S.STORAGE,`Private key path: ${n}`,i?.verbose);let e=of.dirname(r);if(!ti.existsSync(e))C(S.STORAGE,`Creating certificate directory: ${e}`,i?.verbose),ti.mkdirSync(e,{recursive:!0});C(S.STORAGE,"Writing certificate file",i?.verbose),ti.writeFileSync(r,t.certificate);let f=of.dirname(n);if(!ti.existsSync(f))C(S.STORAGE,`Creating private key directory: ${f}`,i?.verbose),ti.mkdirSync(f,{recursive:!0});return C(S.STORAGE,"Writing private key file",i?.verbose),ti.writeFileSync(n,t.privateKey),C(S.STORAGE,"Certificate and private key stored successfully",i?.verbose),r}function ah(t,i){C(S.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:r}=Xf({basePath:i?.basePath,caCertPath:i?.caCertPath});C(S.STORAGE,`CA certificate path: ${r}`,i?.verbose);let n=of.dirname(r);if(!ti.existsSync(n))C(S.STORAGE,`Creating CA certificate directory: ${n}`,i?.verbose),ti.mkdirSync(n,{recursive:!0});return C(S.STORAGE,"Writing CA certificate file",i?.verbose),ti.writeFileSync(r,t),C(S.STORAGE,"CA certificate stored successfully",i?.verbose),r}function Jn(t){let i;if(t.startsWith("-----BEGIN CERTIFICATE-----"))i=t;else i=nh(t);return new _w.X509Certificate(i)}function _n(t){return Jn(t).fingerprint256.replace(/:/g,"").toUpperCase()}function Kf(t){return mh(Jn(t).subject)}function zf(t,i,r=443,n=4000){let e;try{e=i.includes("-----BEGIN")?i:Iw.readFileSync(i,"utf8")}catch{return Promise.resolve(!1)}return new Promise((f)=>{let l=!1,c=(h)=>{if(l)return;l=!0,f(h)},s=Kw.connect({host:t,port:r,servername:t,ca:e,rejectUnauthorized:!0},()=>{c(s.authorized),s.end()});s.setTimeout(n,()=>{s.destroy(),c(!1)}),s.on("error",()=>c(!1))})}function zw(t){let i=[],r=t.split(`
71
- `);for(let n of r){let[e,...f]=n.split("="),l=f.join("=");if(e&&l)i.push({shortName:e.trim(),value:l.trim()})}return i}function mh(t){return zw(t).find((i)=>i.shortName==="CN")?.value||""}function Ow(t){let i=[],r=mh(t.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))i.push(r);let n=t.subjectAltName;if(n){let e=n.split(", ");for(let f of e)if(f.startsWith("DNS:"))i.push(f.slice(4))}return[...new Set(i)]}function Of(t,i){let r=Jn(t),n=Ow(r);for(let e of n){if(e===i)return!0;if(e.startsWith("*.")){let f=e.slice(2);if(i.endsWith(f)&&i.indexOf(".")===i.lastIndexOf("."))return!0}}return!1}async function Gw(t,i){if(Un.platform()!=="darwin")return!1;try{let r=_n(t);if(!r)return C(S.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(Mw("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
72
- `).some((n)=>{let e=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!e&&e[1].toUpperCase()===r}))return C(S.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return C(S.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(r){return C(S.TRUST,`Error checking certificate trust: ${r}`,i),!1}}var Hw={platform:"darwin",async addCertificate(t,i){if(await Gw(t,i?.verbose)){C(S.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),Li.success("Certificate is already trusted in system keychain");return}C(S.TRUST,"Adding certificate to macOS keychain",i?.verbose),await yi(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,r){let n=r||p.commonName;C(S.TRUST,`Removing certificate ${n} from macOS keychain`,i?.verbose);try{await yi(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),C(S.TRUST,`Removed certificate ${n} from macOS keychain`,i?.verbose)}catch(e){throw C(S.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},Lw={platform:"win32",async addCertificate(t,i){C(S.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await yi(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,r){let n=r||p.commonName;C(S.TRUST,`Removing certificate ${n} from Windows certificate store`,i?.verbose);try{await yi(`certutil -delstore -enterprise Root "${n}"`),C(S.TRUST,`Removed certificate ${n} from Windows certificate store`,i?.verbose)}catch(e){throw C(S.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},qw={platform:"linux",async addCertificate(t,i){C(S.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let r=Un.homedir(),n=zt.LINUX_CERT_DB_FILENAME,e=zt.LINUX_TRUST_ARGS;C(S.TRUST,`Searching for certificate databases in ${r}`,i?.verbose);let f=Ef(r,n);if(f.length===0){Li.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let l of f){C(S.TRUST,`Processing certificate database in ${l}`,i?.verbose);try{C(S.TRUST,`Attempting to delete existing cert for ${p.commonName}`,i?.verbose),await yi(`certutil -d sql:${l} -D -n ${p.commonName}`)}catch(c){C(S.TRUST,`Warning: Error deleting existing cert: ${c}`,i?.verbose),console.warn(`Error deleting existing cert: ${c}`)}C(S.TRUST,`Adding new certificate to ${l}`,i?.verbose),await yi(`certutil -d sql:${l} -A -t ${e} -n ${p.commonName} -i ${t}`),Li.info(`Cert added to ${l}`)}},async removeCertificate(t,i,r){let n=r||p.commonName;C(S.TRUST,`Removing certificate ${n} from Linux certificate store`,i?.verbose);let e=Un.homedir(),f=zt.LINUX_CERT_DB_FILENAME;C(S.TRUST,`Searching for certificate databases in ${e}`,i?.verbose);let l=Ef(e,f);if(l.length===0){Li.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of l){C(S.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{await yi(`certutil -d sql:${c} -D -n "${n}"`),Li.info(`Cert removed from ${c}`)}catch(s){C(S.TRUST,`Error removing cert from ${c}: ${s}`,i?.verbose),console.warn(`Error removing cert from ${c}: ${s}`)}}}},xw={darwin:Hw,win32:Lw,linux:qw};async function Mf(t,i,r){C(S.TRUST,`Adding certificate to system trust store with options: ${gn(r)}`,r?.verbose),C(S.TRUST,"Storing certificate and private key",r?.verbose);let n=wh(t,r);C(S.TRUST,"Storing CA certificate",r?.verbose);let e=ah(i,r),f=Un.platform();C(S.TRUST,`Detected platform: ${f}`,r?.verbose);let l=xw[f];if(!l){let c=`Unsupported platform: ${f}`;throw C(S.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await l.addCertificate(e,r),C(S.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as Fl}from"node:os";import{join as jl,resolve as Zd}from"node:path";import{existsSync as Ah,statSync as Eh}from"fs";import{existsSync as kw,mkdirSync as yo,readdirSync as wo,readFileSync as Vw,writeFileSync as ao}from"fs";import{homedir as Vi}from"os";import{dirname as Eo,resolve as Wt}from"path";import ae from"process";import{existsSync as Th,statSync as oh}from"fs";import{existsSync as fl,mkdirSync as Dw,readdirSync as bw,writeFileSync as Pw}from"fs";import{homedir as Di}from"os";import{dirname as dh,resolve as Et}from"path";import Si from"process";import{join as Qw,relative as pw,resolve as Yh}from"path";import ie from"process";import{existsSync as eu,mkdirSync as jo,readdirSync as No,writeFileSync as Wo}from"fs";import{homedir as Gf}from"os";import{dirname as Jo,resolve as At}from"path";import Ur from"process";import{join as vw,relative as Zw,resolve as Bh}from"path";import re from"process";import{existsSync as fu,mkdirSync as Oo,readdirSync as Mo,writeFileSync as Go}from"fs";import{dirname as Lo,resolve as ne}from"path";import ll from"process";import{Buffer as mi}from"buffer";import{createCipheriv as ta,createDecipheriv as ia,randomBytes as Hf}from"crypto";import{closeSync as Lf,createReadStream as Ch,createWriteStream as ra,existsSync as qf,fsyncSync as Rh,openSync as Sh,writeFileSync as na}from"fs";import{access as ea,constants as Uh,mkdir as fa,readdir as In,rename as Fh,stat as bi,unlink as Kn,writeFile as xf}from"fs/promises";import{join as Pi}from"path";import ht from"process";import{pipeline as la}from"stream/promises";import{createGzip as jh}from"zlib";import Qi from"process";import fi from"process";import{Buffer as ri}from"buffer";import{createCipheriv as ca,createDecipheriv as sa,randomBytes as kf}from"crypto";import{closeSync as Vf,createReadStream as Nh,createWriteStream as ha,existsSync as zn,fsyncSync as Wh,openSync as Xh,writeFileSync as ua}from"fs";import{access as $a,constants as gh,mkdir as ya,readdir as On,rename as Jh,stat as pi,unlink as Mn,writeFile as Df}from"fs/promises";import{isAbsolute as wa,join as vi,resolve as aa}from"path";import N from"process";import{pipeline as ma}from"stream/promises";import{createGzip as _h}from"zlib";import Zi from"process";import li from"process";import Gn from"process";import{existsSync as Hn}from"fs";import{resolve as bf}from"path";import{existsSync as Aa}from"fs";import{existsSync as Ea,readdirSync as Ta}from"fs";import{extname as Pf,resolve as Ih}from"path";import oa from"process";import{join as da,relative as Ya,resolve as Kh}from"path";import ee from"process";import{Buffer as ni}from"buffer";import{createCipheriv as Ba,createDecipheriv as Ca,randomBytes as Qf}from"crypto";import{closeSync as pf,createReadStream as zh,createWriteStream as Ra,existsSync as Ln,fsyncSync as Oh,openSync as Mh,writeFileSync as Sa}from"fs";import{access as Ua,constants as Gh,mkdir as Fa,readdir as qn,rename as Hh,stat as tr,unlink as xn,writeFile as vf}from"fs/promises";import{isAbsolute as ja,join as ir,resolve as Na}from"path";import W from"process";import{pipeline as Wa}from"stream/promises";import{createGzip as Lh}from"zlib";import rr from"process";import ci from"process";import Vn from"process";import{existsSync as Dn}from"fs";import{resolve as el}from"path";import{existsSync as Qm}from"fs";class ru{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,l=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:l}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Ah(t))return!0;return Eh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Ah(r)?Eh(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,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:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class nu{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),l=performance.now()-n;return this.recordMetric({operation:t,duration:l,timestamp:e,...r}),f}catch(f){let l=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:l,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var te=new ru,El=new nu;var Xa=Object.defineProperty,ga=(t)=>t;function Ja(t,i){this[t]=ga.bind(null,i)}var _a=(t,i)=>{for(var r in i)Xa(t,r,{get:i[r],enumerable:!0,configurable:!0,set:Ja.bind(i,r)})},Ia=(t,i)=>()=>(t&&(i=t(t=0)),i),lu={};_a(lu,{withErrorRecovery:()=>hu,tryLoadConfig:()=>em,loadConfigWithResult:()=>rm,loadConfig:()=>au,isRetryableError:()=>Qa,isConfigNotFoundError:()=>Pa,isBunfigError:()=>uu,globalPerformanceMonitor:()=>Nr,globalCache:()=>nr,getEnvOrDefault:()=>pa,generateConfigTypes:()=>fm,defaultGeneratedDir:()=>Bu,defaultConfigDir:()=>Yu,deepMergeWithArrayStrategy:()=>Bl,deepMerge:()=>$u,createLibraryConfig:()=>lm,config:()=>nm,bunfigPlugin:()=>cm,applyEnvVarsToConfig:()=>Sr,TypeGenerationError:()=>wl,SchemaValidationError:()=>jr,PluginError:()=>ml,PerformanceMonitor:()=>ol,FileSystemError:()=>yl,ErrorFactory:()=>Ai,EnvVarError:()=>ue,EnvProcessor:()=>me,ConfigValidator:()=>Cl,ConfigValidationError:()=>ul,ConfigNotFoundError:()=>he,ConfigMergeError:()=>$l,ConfigLoader:()=>Rl,ConfigLoadError:()=>Fr,ConfigFileLoader:()=>Ae,ConfigCache:()=>Tl,CacheUtils:()=>Au,BunfigError:()=>Rt,BrowserConfigError:()=>al,ArrayMergeStrategies:()=>ou});class Tl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,l=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:l}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Th(t))return!0;return oh(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Th(r)?oh(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,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:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ol{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),l=performance.now()-n;return this.recordMetric({operation:t,duration:l,timestamp:e,...r}),f}catch(f){let l=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:l,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function Ka(t,i={}){let n=Object.keys(i).sort().map((e)=>`${e}:${i[e]}`).join("|");return n?`${t}:${n}`:t}function za(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Oa(t){return t.getStats().size*2}function dl(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&k(i[0])&&"id"in i[0]&&i[0].id===3&&k(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(k(i)&&k(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(k(t)&&"arr"in t&&Array.isArray(t.arr)&&k(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&k(i[0])&&k(t[0])){let n=[...i];for(let e of t)if(k(e)&&"name"in e){if(!n.find((l)=>k(l)&&("name"in l)&&l.name===e.name))n.push(e)}else if(k(e)&&"path"in e){if(!n.find((l)=>k(l)&&("path"in l)&&l.path===e.path))n.push(e)}else if(!n.some((f)=>fe(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!k(i)||!k(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(k(e)&&k(r[n]))r[n]=dl(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&k(e[0])&&k(r[n][0])){let f=[...e];for(let l of r[n])if(k(l)&&"name"in l){if(!f.find((s)=>k(s)&&("name"in s)&&s.name===l.name))f.push(l)}else if(k(l)&&"path"in l){if(!f.find((s)=>k(s)&&("path"in s)&&s.path===l.path))f.push(l)}else if(!f.some((c)=>fe(c,l)))f.push(l);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let l of r[n])if(!f.includes(l))f.push(l);r[n]=f}else r[n]=e;else r[n]=e}return r}function fe(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!fe(t[r],i[r]))return!1;return!0}if(k(t)&&k(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!fe(t[e],i[e]))return!1}return!0}return!1}function k(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Ma(t,i){if(!fu(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return dl(i,n)}catch{return null}}catch{return null}}async function Ga({name:t="",cwd:i,defaultConfig:r}){let n=i||ll.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let l of f)for(let c of e){let s=ne(n,`${l}${c}`),h=await Ma(s,r);if(h!==null)return h}try{let l=ne(n,"package.json");if(fu(l)){let s=(await import(l))[t];if(s&&typeof s==="object"&&!Array.isArray(s))try{return dl(r,s)}catch{}}}catch{}return r}function Ha(t,i={}){let r=re.cwd();while(r.includes("storage"))r=Bh(r,"..");let n=Bh(r,t||"");if(i?.relative)return Zw(re.cwd(),n);return n}async function La(){try{let t=await Ga({name:"clarity",defaultConfig:Qn,cwd:re.cwd(),endpoint:"",headers:{}});return{...Qn,...t}}catch{return Qn}}function P(){if(fi.env.NODE_ENV==="test"||fi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function qa(){if(fi.env.NODE_ENV==="test"||fi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof fi<"u"){let t=fi.type;if(t==="renderer"||t==="worker")return!1;return!!(fi.versions&&(fi.versions.node||fi.versions.bun))}return!1}class cu{async format(t){let i=await qa(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Qi.pid,hostname:i(),environment:Qi.env.NODE_ENV||"development",platform:Qi.platform,version:Qi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qi.env.NODE_ENV||Qi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class le{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(t,i={}){this.name=t,this.config={...sl},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new cu,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??ht.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...pn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...pn};return{...pn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:sl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let r=(async()=>{let e,f=0,l=3,c=1000;while(f<l)try{try{try{await ea(this.config.logDirectory,Uh.F_OK|Uh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await fa(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let s=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:mi.from(t);try{if(!qf(this.currentLogFile))await xf(this.currentLogFile,"",{mode:420});if(e=Sh(this.currentLogFile,"a",420),na(e,s,{flag:"a"}),Rh(e),e!==void 0)Lf(e),e=void 0;if((await bi(this.currentLogFile)).size===0){if(await xf(this.currentLogFile,s,{flag:"w",mode:420}),(await bi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<l-1){let $=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,$);let w=c*2**f;await new Promise((y)=>setTimeout(y,w)),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(e!==void 0)try{Lf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(s){if(f===l-1){let u=s,$=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),s}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 Pi(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 Pi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Pi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,s])=>s.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(e.length>l)for(let[c]of e.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Hf(16).toString("hex")}generateKey(){return Hf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Hf(16),n=ta("aes-256-gcm",i,r),e=mi.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:mi.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=jh(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(mi.from(mi.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;let t=await bi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await In(this.config.logDirectory),f=e.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,h)=>{let u=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),l=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${l}`;if(await bi(r).catch(()=>null))try{if(await Fh(r,c),i.compress)try{let s=`${c}.gz`;await this.compressLogFile(c,s),await Kn(c)}catch(s){console.error("Error compressing rotated file:",s)}if(f.length===0&&!e.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await xf(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await bi(r).catch(()=>null))await Fh(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await In(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(i.maxFiles))await Kn(Pi(this.config.logDirectory,l))}}}async compressLogFile(t,i){let r=Ch(t),n=ra(i),e=jh();await la(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),qf(this.currentLogFile))try{let t=Sh(this.currentLogFile,"r+");Rh(t),Lf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await In(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await Kn(Pi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?q.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:l=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(l)y.push(i);if(f==="warning")y.push("WARN");else if(f==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(e),y.join(" ")}let s=ht.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${q.cyan(e)}`;if(!l)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,s-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,l)=>{let c=Number.parseInt(l,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,l)=>{if(l==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(l){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),l,c;if(i instanceof Error)l=i.message,c=i.stack;else l=this.formatMessage(i,r);if(this.fancy&&!P()){let h=Eu[t],u=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",$;switch(t){case"debug":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:q.gray(l),level:t}),console.error($);break;case"info":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:l,level:t}),console.error($);break;case"success":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:q.green(l),level:t}),console.error($);break;case"warning":$=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:l,level:t}),console.warn($);break;case"error":if($=this.formatConsoleMessage({timestamp:e,icon:h,tag:u,message:l,level:t}),console.error($),c){let w=c.split(`
73
- `);for(let y of w)if(y.trim()&&!y.includes(l))console.error(this.formatConsoleMessage({timestamp:e,message:q.gray(` ${y}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${l}`),c)console.error(c)}if(!this.shouldLog(t))return;let s=`${f} ${this.environment}.${t.toUpperCase()}: ${l}
74
- `;if(c)s+=`${c}
75
- `;s=s.replace(this.ANSI_PATTERN,""),await this.writeToFile(s)}time(t){let i=performance.now();if(this.fancy&&!P()){let r=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:q.blue("◐"),tag:r,message:`${q.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,l=new Date,c=this.formatConsoleTimestamp(l),h=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
76
- `,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!P()){let u=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:q.green("✓"),tag:u,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!P())console.error(h.trim());await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new le(i,{...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(r),r}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!qf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ch(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=mi.isBuffer(t)?t:mi.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),l=n.slice(16,-16),c=ia("aes-256-gcm",r,e);return c.setAuthTag(f),mi.concat([c.update(l),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}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(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!P()){let f=t.split(`
77
- `),l=Math.max(...f.map((u)=>u.length))+2,c=`┌${"─".repeat(l)}┐`,s=`└${"─".repeat(l)}┘`,h=f.map((u)=>{let $=" ".repeat(l-u.length-2);return`│ ${u}${$} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:q.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:q.cyan(c)})),h.forEach((u)=>console.error(this.formatConsoleMessage({timestamp:r,message:q.cyan(u),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:q.cyan(s),showTimestamp:!1}))}else if(!P())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
78
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${q.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();ht.stdin.removeListener("data",r);try{if(typeof ht.stdin.setRawMode==="function")ht.stdin.setRawMode(!1)}catch{}ht.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof ht.stdin.setRawMode==="function")ht.stdin.setRawMode(!0)}catch{}ht.stdin.resume(),ht.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,c=0;if(r=t.replace(l,(s,h)=>{if(h==="%")return"%";if(c>=i.length)return s;let u=i[c++];switch(h){case"s":return String(u);case"d":case"i":return Number(u).toString();case"j":case"o":return JSON.stringify(u,null,2);default:return s}}),c<i.length)r+=` ${i.slice(c).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!P()){let l=this.options.showTags!==!1&&this.name?q.gray(this.formatTag(this.name)):"",c=q.blue("◐");console.error(`${c} ${l} ${q.cyan(r)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
79
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}progress(t,i=""){if(!this.enabled||!this.fancy||P()||t<=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 r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(l,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,l)),c!==void 0)this.activeProgressBar.message=c;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},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,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;ht.stdout.write(`${"\r".padEnd(ht.stdout.columns||80)}\r`),this.log(c,l),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||P()||!ht.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=q.green("━".repeat(n)),l=q.gray("━".repeat(e)),c=`[${f}${l}]`,s=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=i||r===100?q.green("✓"):q.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${q.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${s}${h}`,y=ht.stdout.columns||80,A=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${A}`,ht.stdout.write(t.lastRenderedLine),i)ht.stdout.write(`
80
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!ht.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await In(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Pi(this.config.logDirectory,n);if(t.before)try{if((await bi(f)).mtime>=t.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Kn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function Pn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&G(i[0])&&"id"in i[0]&&i[0].id===3&&G(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(G(i)&&G(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(G(t)&&"arr"in t&&Array.isArray(t.arr)&&G(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&G(i[0])&&G(t[0])){let n=[...i];for(let e of t)if(G(e)&&"name"in e){if(!n.find((l)=>G(l)&&("name"in l)&&l.name===e.name))n.push(e)}else if(G(e)&&"path"in e){if(!n.find((l)=>G(l)&&("path"in l)&&l.path===e.path))n.push(e)}else if(!n.some((f)=>ce(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!G(i)||!G(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(G(e)&&G(r[n]))r[n]=Pn(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&G(e[0])&&G(r[n][0])){let f=[...e];for(let l of r[n])if(G(l)&&"name"in l){if(!f.find((s)=>G(s)&&("name"in s)&&s.name===l.name))f.push(l)}else if(G(l)&&"path"in l){if(!f.find((s)=>G(s)&&("path"in s)&&s.path===l.path))f.push(l)}else if(!f.some((c)=>ce(c,l)))f.push(l);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let l of r[n])if(!f.includes(l))f.push(l);r[n]=f}else r[n]=e;else r[n]=e}return r}function Yl(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:Pn(t,i);if(Array.isArray(t))return r==="replace"?i:Pn(t,i);if(!G(i)||!G(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],l=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(l))if(r==="replace")n[e]=f;else n[e]=Pn(l,f);else if(G(f)&&G(l))n[e]=Yl(l,f,r);else n[e]=f}return n}function ce(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!ce(t[r],i[r]))return!1;return!0}if(G(t)&&G(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!ce(t[e],i[e]))return!1}return!0}return!1}function G(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function kn(t,i,r="replace"){if(!eu(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Yl(i,e,r)}catch{return null}}catch{return null}}function xa(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(l,c=[]){let s={...l};for(let[h,u]of Object.entries(l)){let $=[...c,h],w=(a)=>a.replace(/([A-Z])/g,"_$1").toUpperCase(),y=`${n}_${$.map(w).join("_")}`,A=`${n}_${$.map((a)=>a.toUpperCase()).join("_")}`;if(r)$t.info(`Checking environment variable ${y} for config ${t}.${$.join(".")}`);if(typeof u==="object"&&u!==null&&!Array.isArray(u))s[h]=f(u,$);else{let a=Ur.env[y]||Ur.env[A];if(a!==void 0){if(r)$t.info(`Using environment variable ${a?y:A} for config ${t}.${$.join(".")}`);if(typeof u==="number")s[h]=Number(a);else if(typeof u==="boolean")s[h]=a.toLowerCase()==="true";else if(Array.isArray(u))try{let E=JSON.parse(a);if(Array.isArray(E))s[h]=E;else s[h]=a.split(",").map((T)=>T.trim())}catch{s[h]=a.split(",").map((E)=>E.trim())}else s[h]=a}}}return s}return f(e)}async function ka({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:l=!0,arrayStrategy:c="replace"}){let s=l&&typeof e==="object"&&e!==null&&!Array.isArray(e)?xa(t,e,f):e,h=r||Ur.cwd(),u=[".ts",".js",".mjs",".cjs",".json"];if(f)$t.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let $=[t,`.${t}`].filter(Boolean),w=[`${t}.config`,`.${t}.config`].filter(Boolean),y=i?[i,`.${i}`]:[],A=i?[`${i}.config`,`.${i}.config`]:[],a=Array.from(new Set([h,At(h,"config"),At(h,".config"),n?At(h,n):void 0].filter(Boolean)));for(let E of a){if(f)$t.info(`Searching for configuration in: ${E}`);let d=[At(h,"config"),At(h,".config")].concat(n?[At(h,n)]:[]).includes(E)?[...$,...w,...y,...A]:[...w,...$,...A,...y];for(let Y of d)for(let U of u){let B=At(E,`${Y}${U}`),X=await kn(B,s,c);if(X!==null){if(f)$t.success(`Configuration loaded from: ${B}`);return X}}}if(t){let E=At(Gf(),".config",t),T=["config",`${t}.config`];if(i)T.push(`${i}.config`);if(f)$t.info(`Checking user config directory: ${E}`);for(let d of T)for(let Y of u){let U=At(E,`${d}${Y}`),B=await kn(U,s,c);if(B!==null){if(f)$t.success(`Configuration loaded from user config directory: ${U}`);return B}}}if(t){let E=At(Gf(),".config"),T=[`.${t}.config`];if(i)T.push(`.${i}.config`);if(f)$t.info(`Checking user config directory for dotfile configs: ${E}`);for(let d of T)for(let Y of u){let U=At(E,`${d}${Y}`),B=await kn(U,s,c);if(B!==null){if(f)$t.success(`Configuration loaded from user config directory dotfile: ${U}`);return B}}}if(t){let E=Gf(),T=[`.${t}.config`,`.${t}`];if(i)T.push(`.${i}.config`),T.push(`.${i}`);if(f)$t.info(`Checking user home directory for dotfile configs: ${E}`);for(let d of T)for(let Y of u){let U=At(E,`${d}${Y}`),B=await kn(U,s,c);if(B!==null){if(f)$t.success(`Configuration loaded from user home directory: ${U}`);return B}}}try{let E=At(h,"package.json");if(eu(E)){let T=await import(E),d=T[t];if(!d&&i){if(d=T[i],d&&f)$t.success(`Using alias "${i}" configuration from package.json`)}if(d&&typeof d==="object"&&!Array.isArray(d))try{if(f)$t.success(`Configuration loaded from package.json: ${d===T[t]?t:i}`);return Yl(s,d,c)}catch(Y){if(f)$t.warn("Failed to merge package.json config:",Y)}}}catch(E){if(f)$t.warn("Failed to load package.json:",E)}if(f)$t.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return s}function Va(t,i={}){let r=ie.cwd();while(r.includes("storage"))r=Yh(r,"..");let n=Yh(r,t||"");if(i?.relative)return pw(ie.cwd(),n);return n}async function Da(){try{let t=await ka({name:"clarity",alias:"logging",defaultConfig:vn,cwd:ie.cwd()});return{...vn,...t||{}}}catch{return vn}}function it(){if(li.env.NODE_ENV==="test"||li.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ba(){if(li.env.NODE_ENV==="test"||li.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof li<"u"){let t=li.type;if(t==="renderer"||t==="worker")return!1;return!!(li.versions&&(li.versions.node||li.versions.bun))}return!1}class su{async format(t){let i=await ba(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Zi.pid,hostname:i(),environment:Zi.env.NODE_ENV||"development",platform:Zi.platform,version:Zi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Zi.env.NODE_ENV||Zi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class se{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(t,i={}){this.name=t,this.config={...hl},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new su,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??N.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Zn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Zn};return{...Zn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:hl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!it()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,l=3,c=1000;while(f<l)try{try{try{await $a(this.config.logDirectory,gh.F_OK|gh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await ya(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let s=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ri.from(t);try{if(!zn(this.currentLogFile))await Df(this.currentLogFile,"",{mode:420});if(e=Xh(this.currentLogFile,"a",420),ua(e,s,{flag:"a"}),Wh(e),e!==void 0)Vf(e),e=void 0;if((await pi(this.currentLogFile)).size===0){if(await Df(this.currentLogFile,s,{flag:"w",mode:420}),(await pi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<l-1){let $=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,$);let w=c*2**f;await new Promise((y)=>setTimeout(y,w)),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(e!==void 0)try{Vf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(s){if(f===l-1){let u=s,$=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),s}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 vi(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 vi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return vi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(it())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,s])=>s.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(e.length>l)for(let[c]of e.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return kf(16).toString("hex")}generateKey(){return kf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=kf(16),n=ca("aes-256-gcm",i,r),e=ri.isBuffer(t)?t:ri.from(t,"utf8"),f=n.update(e),l=n.final(),c=f.length+l.length,s=n.getAuthTag(),h=ri.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),l.copy(h,16+f.length),s.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=_h(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ri.from(ri.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(it())return;if(!this.shouldWriteToFile())return;let t=await pi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await On(this.config.logDirectory),f=e.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,h)=>{let u=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),l=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${l}`;if(await pi(r).catch(()=>null))try{if(await Jh(r,c),i.compress)try{let s=`${c}.gz`;await this.compressLogFile(c,s),await Mn(c)}catch(s){console.error("Error compressing rotated file:",s)}if(f.length===0&&!e.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await Df(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await pi(r).catch(()=>null))await Jh(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await On(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(i.maxFiles))await Mn(vi(this.config.logDirectory,l))}}}async compressLogFile(t,i){let r=Nh(t),n=ha(i),e=_h();await ma(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),zn(this.currentLogFile))try{let t=Xh(this.currentLogFile,"r+");Wh(t),Vf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!it()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await On(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await Mn(vi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?J.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||it())return!1;let t=typeof N.env.NO_COLOR<"u",i=N.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof N.stderr<"u"&&N.stderr.isTTY||typeof N.stdout<"u"&&N.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:l=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(l)y.push(i);if(f==="warning")y.push("WARN");else if(f==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(e),y.join(" ")}let s=N.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${J.cyan(e)}`;if(!l)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,s-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,l)=>{let c=Number.parseInt(l,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,l)=>{if(l==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(l){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=J.underline(J.blue(n)),l=this.toAbsoluteFilePath(e);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(l)}`,s="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>J.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>J.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>J.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>J.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>J.strikethrough(n)),i}supportsHyperlinks(){if(it())return!1;let t=N.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=N.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(wa(i)||i.startsWith("./")||i.startsWith("../"))i=aa(i);else return null;return zn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),l,c;if(i instanceof Error)l=i.message,c=i.stack;else l=this.formatMessage(i,r);let{consoleText:s,fileText:h}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":Tu[t],w=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:J.gray(s),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:J.green(s),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.error(y),c){let A=c.split(`
81
- `);for(let a of A)if(a.trim()&&!a.includes(l))console.error(this.formatConsoleMessage({timestamp:e,message:J.gray(` ${a}`),level:t,showTimestamp:!1}))}break}}else if(!it()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${l}`),c)console.error(c)}if(!this.shouldLog(t))return;let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
82
- `;if(c)u+=`${c}
83
- `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let r={update:(c,s)=>{},finish:(c)=>{},interrupt:(c,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!it()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!it()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,s="info")=>{if(!it()&&N.stdout.isTTY)N.stdout.write(`
84
- `);if(this[s==="warning"?"warn":s](c),this.activeProgressBar&&this.shouldStyleConsole()&&!it()&&N.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":J.blue("◐"),tag:r,message:`${J.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,l=new Date,c=this.formatConsoleTimestamp(l),h=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
85
- `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":J.green("✓"),tag:u,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!it())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new se(i,{...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(r),r}createReadStream(){if(it())throw Error("createReadStream is not supported in browser environments");if(!zn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Nh(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ri.isBuffer(t)?t:ri.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),l=n.subarray(16,n.length-16),c=sa("aes-256-gcm",r,e);c.setAuthTag(f);let s=c.update(l),h=c.final(),u=s.length+h.length,$=ri.allocUnsafe(u);return s.copy($,0),h.copy($,s.length),$.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return it()}isServerMode(){return!it()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
86
- `),s=Math.max(...c.map((w)=>w.length))+2,h=`┌${"─".repeat(s)}┐`,u=`└${"─".repeat(s)}┘`,$=c.map((w)=>{return this.formatConsoleMessage({timestamp:r,message:J.cyan(w),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:J.cyan(h),showTimestamp:!1})),$.forEach((w)=>console.error(w)),console.error(this.formatConsoleMessage({timestamp:r,message:J.cyan(u),showTimestamp:!1}))}else if(!it())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let l=`${n} ${this.environment}.INFO: [BOX] ${f}
87
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(t){if(it())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${J.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();N.stdin.removeListener("data",r);try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!1)}catch{}N.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof N.stdin.setRawMode==="function")N.stdin.setRawMode(!0)}catch{}N.stdin.resume(),N.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,h=0;if(r=t.replace(s,(u,$)=>{if($==="%")return"%";if(h>=i.length)return u;let w=i[h++];switch($){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 u}}),h<i.length)r+=` ${i.slice(h).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?J.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${J.blue("◐")} `;console.error(`${h}${s} ${J.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
88
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!N.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=J.green("━".repeat(n)),l=J.gray("━".repeat(e)),c=`[${f}${l}]`,s=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?J.green("✓"):J.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${J.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${s}${h}`,y=N.stdout.columns||80,A=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${A}`,N.stdout.write(t.lastRenderedLine),i)N.stdout.write(`
89
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||it()||!N.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(it()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await On(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=vi(this.config.logDirectory,n);if(t.before)try{if((await pi(f)).mtime>=t.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Mn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function hu(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,l=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(s){if(l=s instanceof Error?s:Error(String(s)),c===r||!e(l))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}function uu(t){return t instanceof Rt}function Pa(t){return t instanceof he}function Qa(t){if(uu(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>t.message.toLowerCase().includes(r.toLowerCase()))}class me{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:l={},verbose:c=!1,trackPerformance:s=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(t),$={...i};return this.processObject($,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:l,verbose:c,configName:t}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(s)return Nr.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let l=[...i,e],c=l.map((u)=>this.formatEnvKey(u,n.useCamelCase)),s=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${l.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,l,r,n);else{let u=Gn.env[s]||(h?Gn.env[h]:void 0);if(u!==void 0){if(n.verbose){let $=Gn.env[s]?s:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,s,n.customParsers,n.configName)}catch($){if($ instanceof ue)throw $;throw Ai.envVar(s,u,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,l]of Object.entries(n))try{return l(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw Ai.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Gn.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),l=[];switch(this.extractEnvVarInfo(i,[],f,l),e){case"markdown":return this.formatAsMarkdown(l,t);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let l=[...i,e],c=`${r}_${l.map((s)=>this.formatEnvKey(s,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,l,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${l.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
90
-
91
- `;for(let n of t)r+=`${n.key}
92
- `,r+=` Type: ${n.type}
93
- `,r+=` Description: ${n.description}
94
- `,r+=` Example: ${n.example}
95
-
96
- `;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
97
-
98
- `;r+=`| Variable | Type | Description | Example |
99
- `,r+=`|----------|------|-------------|----------|
100
- `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
101
- `;return r}}function pa(t,i){let r=mu("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function $u(t,i,r={}){return yu(t,i,r,new WeakMap)}function yu(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:l}=r;if(i===null||i===void 0)return f?t:i;if(l){let c=l(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return wu(t,i,e,n);if(!Xt(i)||!Xt(t))return i;return im(t,i,r,n)}function wu(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return va(t,i);case"smart":return Za(t,i,n);default:return i}return i}function va(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>cl(e,n)))r.push(n);return r}function Za(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Xt(i[0])&&Xt(t[0]))return tm(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function tm(t,i,r){let n=[...i];for(let e of t){if(!Xt(e)){n.push(e);continue}let f=["id","name","key","path","type"],l=!1;for(let c of f)if(c in e){if(n.find((h)=>Xt(h)&&(c in h)&&h[c]===e[c])){l=!0;break}}if(!l)n.push(e)}return n}function im(t,i,r,n){let e=i;if(Xt(e)&&n.has(e))return n.get(e);let f={...t};if(Xt(e))n.set(e,f);for(let l in e){if(!Object.prototype.hasOwnProperty.call(e,l))continue;let c=e[l],s=f[l];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[l]=c;continue}if(Xt(c)&&Xt(s))f[l]=yu(s,c,r,n);else if(Array.isArray(c)||Array.isArray(s))f[l]=wu(s,c,r.arrayMergeMode||"smart",n);else f[l]=c}return f}function Bl(t,i,r="replace"){return $u(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function cl(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!cl(t[r],i[r]))return!1;return!0}if(Xt(t)&&Xt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!cl(t[e],i[e]))return!1}return!0}return!1}function Xt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Ae{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:l=!0,verbose:c=!1}=r;if(e){let h=nr.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let s=async()=>{if(!Hn(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),$=u.default||u,w="default"in u,y=Object.keys(u).length>0;if(!w&&!y)throw new Fr(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new Fr(t,Error("Configuration must export a valid object"),"unknown");let E={config:Bl(i,$,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)nr.setWithFileCheck("file",E,t,f);return E}catch(h){throw h instanceof Error?Ai.configLoad(t,h):Ai.configLoad(t,Error(String(h)))}};if(l)return Nr.track("loadFromPath",s,{path:t});return s()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let l of this.extensions)e.push(bf(i,`${f}${l}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return hu(async()=>{return Hn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Hn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let l of this.extensions){let c=bf(t,`${f}${l}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let l of f)if(this.looksLikeConfigFile(l)){let c=bf(t,l);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!Hn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class Cl{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:l=[],trackPerformance:c=!0,verbose:s=!1}=r,h=async()=>{let u=[],$=[],w={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:l,trackPerformance:c,verbose:s};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,w);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...l],w);else return this.validateWithJSONSchema(t,i,w)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:$}}};if(c)return await Nr.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!Aa(i))throw new jr(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new jr(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let l=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(l)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${l}`,expected:c.join(" or "),actual:l,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let l=0;l<t.length;l++){let c=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(t[l],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let l=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in l)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,s]of Object.entries(i.properties))if(c in l){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(l[c],s,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let s of Object.keys(l))if(!c.has(s))e.push({path:r?`${r}.${s}`:s,message:`Additional property '${s}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let l=this.getValueByPath(t,f.path),c=this.validateWithRule(l,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:f.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,l]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(l)})}return i}mapTypeScriptType(t){switch(t.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:du},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Rl{fileLoader=new Ae;envProcessor=new me;validator=new Cl;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...l}=t;try{if(r?.enabled){let s=this.checkCache(l.name||"",l);if(s)return s}let c;try{c=await this.loadConfigurationStrategies(l,!0,r)}catch(s){let h=l.__strictErrorHandling;if(s instanceof Error&&s.name==="ConfigNotFoundError"){if(h)throw s;c={...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(s instanceof Error&&s.name==="ConfigLoadError"){let u=s.message.includes("EACCES")||s.message.includes("EPERM")||s.message.includes("permission denied"),$=!u&&(s.message.includes("syntax")||s.message.includes("Expected")||s.message.includes("Unexpected")||s.message.includes("BuildMessage")||s.message.includes("errors building")),w=s.message.includes("Configuration must export a valid object")||s.message.includes("Configuration file is empty and exports nothing");if(h&&(w||u))throw s;if($&&(!h||!w))c={...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(!h)c={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${s.message}`]};else throw s}else c={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${s instanceof Error?s.message:String(s)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,l.name);if(r?.enabled&&c)this.cacheResult(l.name||"",c,r,l);if(n?.enabled){let s={operation:"loadConfig",duration:Date.now()-i,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(s);if(n.slowThreshold&&s.duration>n.slowThreshold)Gt.warn(`Slow configuration loading detected: ${s.duration}ms for ${l.name}`);c.metrics=s}return c}catch(c){let s=Date.now()-i;throw Gt.error(`Configuration loading failed after ${s}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:l,defaultConfig:c,checkEnv:s=!0,arrayStrategy:h="replace",verbose:u=!1}=t,$=f||Si.cwd(),w=[],y=await this.loadLocalConfiguration(n,e,$,l,c,h,u,s,r);if(y)return w.push(...this.getLocalSearchPaths(n,e,$,l)),this.finalizeResult(y,w,s,n,u);let A=await this.loadHomeConfiguration(n,e,c,h,u,s);if(A)return w.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(A,w,s,n,u);let a=await this.loadPackageJsonConfiguration(n,e,$,c,h,u,s);if(a)return w.push(Et($,"package.json")),this.finalizeResult(a,w,s,n,u);if(w.push(...this.getAllSearchPaths(n,e,$,l)),i)throw Ai.configNotFound(n,w,e);return{...await this.applyEnvironmentVariables(n,c,s,u),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,l,c,s){let h=c?Sr(t,e,l):e,u=this.getLocalDirectories(r,n);for(let $ of u){if(l)Gt.info(`Searching for configuration in: ${$}`);let w=this.fileLoader.generateConfigPaths(t,$,i),y=await this.fileLoader.tryLoadFromPaths(w,h,{arrayStrategy:f,verbose:l,cacheTtl:s?.ttl,useCache:!s?.ttl||s.ttl>100});if(y){if(l)Gt.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let l=f?Sr(t,r,e):r,c=[Et(Di(),".config",t),Et(Di(),".config"),Di()];for(let s of c){if(e)Gt.info(`Checking home directory: ${s}`);let h=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:n,verbose:e});if(u){if(e)Gt.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,l){let c=l?Sr(t,n,f):n;try{let s=Et(r,"package.json");if(!fl(s))return null;let h=await import(s),u=h[t],$=t;if(!u&&i)u=h[i],$=i;if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)Gt.success(`Configuration loaded from package.json: ${$}`);return{config:Bl(c,u,e),source:{type:"package.json",path:s,priority:30,timestamp:new Date}}}}catch(s){if(f)Gt.warn("Failed to load package.json:",[s instanceof Error?s:Error(String(s))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Sr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(e.length>0)throw Ai.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return nr.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);nr.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Et(t,"config"),Et(t,".config"),i?Et(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Et(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let l of e)f.push(...this.fileLoader.generateConfigPaths(t,l,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Et(Di(),".config",t),Et(Di(),".config"),Di()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function qh(t){let r=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return r||n}async function rm(t){return si.loadConfig({...t,__strictErrorHandling:!0})}async function au(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await si.loadConfig(t);else n=await si.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)Gt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await si.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function nm(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await si.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&qh(r)))return(await si.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await si.loadConfig({...t,cwd:t.cwd||Si.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&qh(i)))return(await si.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function em(t,i,r="replace"){let n=new Ae;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function Sr(t,i,r=!1){let n=new me,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(l,c=[]){let s={...l};for(let[h,u]of Object.entries(l)){let $=[...c,h],w=[`${e}_${$.join("_").toUpperCase()}`,`${e}_${$.map((a)=>a.toUpperCase()).join("")}`,`${e}_${$.map((a)=>a.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,A;for(let a of w)if(y=Si.env[a],y!==void 0){A=a;break}if(y!==void 0&&A)if(typeof u==="boolean")s[h]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let a=Number(y);if(!Number.isNaN(a))s[h]=a}else if(Array.isArray(u))try{s[h]=JSON.parse(y)}catch{s[h]=y.split(",").map((a)=>a.trim())}else s[h]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))s[h]=f(u,$)}return s}return f(i)}function fm(t){let i=Et(Si.cwd(),t.configDir),r=Et(Si.cwd(),t.generatedDir),n=Et(r,"config-types.ts");if(!fl(dh(n)))Dw(dh(n),{recursive:!0,mode:511});let e=fl(i)?bw(i).map((l)=>l.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${_m}
102
- export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
103
- `;Pw(n,f,{mode:438})}function lm(t){let i=null,r=null,n=()=>{if(!r)r=au(t).then((f)=>{return i=f,f},(f)=>{let l="defaultConfig"in t?t.defaultConfig:{};if(i=l,"verbose"in t&&t.verbose)Gt.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return l});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,l){if(i)return i[l];let c=e[l];return n(),c},has(f,l){return l in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,l){return Object.getOwnPropertyDescriptor(i||e,l)},set(f,l,c){if(!i)i={...e};return i[l]=c,!0}})}function cm(t){let i=Ih(oa.cwd(),t?.configDir||"./config");function r(){if(!Ea(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],l=Ta(i).filter((s)=>e.has(Pf(s))).map((s)=>({base:s.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:s})),c=new Map;for(let{base:s,file:h}of l){let u=Pf(h).toLowerCase(),$=c.get(s);if(!$){c.set(s,h);continue}let w=Pf($).toLowerCase();if(f.indexOf(u)<f.indexOf(w))c.set(s,h)}return Array.from(c.entries()).map(([s,h])=>({base:s,file:h})).sort((s,h)=>s.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((h)=>h.base),l=f.length?f.map((h)=>`'${h}'`).join(" | "):"string",c=e.length?`{
104
- ${e.map((h)=>{let u=Ih(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${u}').default`}).join(`,
105
- `)}
106
- }`:"Record<string, any>";return`export type ConfigNames = ${l}
107
- export type ConfigByName = ${c}
108
- export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
109
- export type ConfigOf = Config
110
- `}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var mu,nr,Nr,Au,sm,hm,xh,Qn,sl,ut,q,um,kh,$m,Vh,ym,wm,Zf,am,Dh,bh,tl,mm,Am,Em,Tm,pn,Eu,om,$t,dm,Ym,Ph,vn,hl,rt,J,Bm,Qh,Cm,ph,Rm,Sm,il,Um,vh,Zh,Fm,rl,jm,Nm,Wm,Xm,gm,Zn,Tu,Jm,_m="0.15.6",Rt,he,Fr,ul,$l,ue,yl,wl,jr,al,ml,Ai,ou,du,Gt,si,Yu,Bu,Im=Ia(async()=>{mu=import.meta.require,nr=new Tl,Nr=new ol,Au={createKey:Ka,isEquivalent:za,estimateMemoryUsage:Oa},sm=ne(ll.cwd(),"config"),hm=ne(ll.cwd(),"src/generated"),xh=re.env.CLARITY_LOG_DIR||vw(Ha(),"logs"),Qn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},sl=await La(),ut={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},q=ut,um=ut.red,kh=ut.green,$m=ut.yellow,Vh=ut.blue,ym=ut.magenta,wm=ut.cyan,Zf=ut.white,am=ut.gray,Dh=ut.bgRed,bh=ut.bgYellow,tl=ut.bold,mm=ut.dim,Am=ut.italic,Em=ut.underline,Tm=ut.reset,pn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Eu={debug:"\uD83D\uDD0D",info:Vh("ℹ"),success:kh("✓"),warning:bh(Zf(tl(" WARN "))),error:Dh(Zf(tl(" ERROR ")))},om=new le("stacks"),$t=new le("bunfig",{showTags:!0}),dm=At(Ur.cwd(),"config"),Ym=At(Ur.cwd(),"src/generated"),Ph=ie.env.CLARITY_LOG_DIR||Qw(Va(),"logs"),vn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ph,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},hl=await Da(),rt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},J=rt,Bm=rt.red,Qh=rt.green,Cm=rt.yellow,ph=rt.blue,Rm=rt.magenta,Sm=rt.cyan,il=rt.white,Um=rt.gray,vh=rt.bgRed,Zh=rt.bgYellow,Fm=rt.bgGray,rl=rt.bold,jm=rt.dim,Nm=rt.italic,Wm=rt.underline,Xm=rt.strikethrough,gm=rt.reset,Zn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Tu={debug:"\uD83D\uDD0D",info:ph("ℹ"),success:Qh("✓"),warning:Zh(il(rl(" WARN "))),error:vh(il(rl(" ERROR ")))},Jm=new se("stacks"),Rt=class extends Error{timestamp;context;constructor(i,r={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,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(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},he=class extends Rt{code="CONFIG_NOT_FOUND";constructor(i,r,n){let e=n?` or alias "${n}"`:"";super(`Configuration "${i}"${e} not found`,{configName:i,alias:n,searchPaths:r,searchPathCount:r.length})}},Fr=class extends Rt{code="CONFIG_LOAD_ERROR";constructor(i,r,n){super(`Failed to load configuration from "${i}": ${r.message}`,{configPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},ul=class extends Rt{code="CONFIG_VALIDATION_ERROR";constructor(i,r,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:r,errorCount:r.length})}},$l=class extends Rt{code="CONFIG_MERGE_ERROR";constructor(i,r,n,e){super(`Failed to merge configuration from "${i}" with "${r}": ${n.message}`,{sourcePath:i,targetPath:r,configName:e,originalError:n.name,originalMessage:n.message});this.cause=n}},ue=class extends Rt{code="ENV_VAR_ERROR";constructor(i,r,n,e){super(`Failed to parse environment variable "${i}" with value "${r}" as ${n}`,{envKey:i,envValue:r,expectedType:n,configName:e})}},yl=class extends Rt{code="FILE_SYSTEM_ERROR";constructor(i,r,n){super(`File system ${i} failed for "${r}": ${n.message}`,{operation:i,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},wl=class extends Rt{code="TYPE_GENERATION_ERROR";constructor(i,r,n){super(`Failed to generate types from "${i}" to "${r}": ${n.message}`,{configDir:i,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},jr=class extends Rt{code="SCHEMA_VALIDATION_ERROR";constructor(i,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:r,errorCount:r.length})}},al=class extends Rt{code="BROWSER_CONFIG_ERROR";constructor(i,r,n,e){super(`Failed to fetch configuration from "${i}": ${r} ${n}`,{endpoint:i,status:r,statusText:n,configName:e})}},ml=class extends Rt{code="PLUGIN_ERROR";constructor(i,r,n){super(`Plugin "${i}" failed during ${r}: ${n.message}`,{pluginName:i,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Ai={configNotFound(t,i,r){return new he(t,i,r)},configLoad(t,i,r){return new Fr(t,i,r)},configValidation(t,i,r){return new ul(t,i,r)},configMerge(t,i,r,n){return new $l(t,i,r,n)},envVar(t,i,r,n){return new ue(t,i,r,n)},fileSystem(t,i,r){return new yl(t,i,r)},typeGeneration(t,i,r){return new wl(t,i,r)},schemaValidation(t,i,r){return new jr(t,i,r)},browserConfig(t,i,r,n){return new al(t,i,r,n)},plugin(t,i,r){return new ml(t,i,r)}},ou={replace:"replace",concat:"concat",smart:"smart"},du=/^https?:\/\//,Gt=new se("bunfig",{showTags:!0}),si=new Rl,Yu=Et(Si.cwd(),"config"),Bu=Et(Si.cwd(),"src/generated")});function Km(t,i={}){let r=ee.cwd();while(r.includes("storage"))r=Kh(r,"..");let n=Kh(r,t||"");if(i?.relative)return Ya(ee.cwd(),n);return n}var zm=ee.env.CLARITY_LOG_DIR||da(Km(),"logs"),Cu={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zm,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},$e={...Cu},Nd=(async()=>{try{let{loadConfig:t}=await Im().then(()=>lu),i=await t({name:"clarity",alias:"logging",defaultConfig:Cu,cwd:ee.cwd()});if(i)Object.assign($e,i)}catch{}return $e})();function nt(){if(ci.env.NODE_ENV==="test"||ci.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Om(){if(ci.env.NODE_ENV==="test"||ci.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ci<"u"){let t=ci.type;if(t==="renderer"||t==="worker")return!1;return!!(ci.versions&&(ci.versions.node||ci.versions.bun))}return!1}class Ru{async format(t){let i=await Om(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:rr.pid,hostname:i(),environment:rr.env.NODE_ENV||"development",platform:rr.platform,version:rr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:rr.env.NODE_ENV||rr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ft={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},I=ft,Wd=ft.red,Mm=ft.green,Xd=ft.yellow,Gm=ft.blue,gd=ft.magenta,Jd=ft.cyan,tu=ft.white,_d=ft.gray,Hm=ft.bgRed,Lm=ft.bgYellow,Id=ft.bgGray,iu=ft.bold,Kd=ft.dim,zd=ft.italic,Od=ft.underline,Md=ft.strikethrough,Gd=ft.reset,nl={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},qm={debug:"\uD83D\uDD0D",info:Gm("ℹ"),success:Mm("✓"),warning:Lm(tu(iu(" WARN "))),error:Hm(tu(iu(" ERROR ")))};class Ee{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(t,i={}){this.name=t,this.config={...$e},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Ru,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??W.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...nl,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...nl};return{...nl,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:$e.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!nt()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,l=3,c=1000;while(f<l)try{try{try{await Ua(this.config.logDirectory,Gh.F_OK|Gh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Fa(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let s=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ni.from(t);try{if(!Ln(this.currentLogFile))await vf(this.currentLogFile,"",{mode:420});if(e=Mh(this.currentLogFile,"a",420),Sa(e,s,{flag:"a"}),Oh(e),e!==void 0)pf(e),e=void 0;if((await tr(this.currentLogFile)).size===0){if(await vf(this.currentLogFile,s,{flag:"w",mode:420}),(await tr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let u=h;if(u.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(u.code)){if(f<l-1){let $=typeof u.message==="string"?u.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,$);let w=c*2**f;await new Promise((y)=>setTimeout(y,w)),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(e!==void 0)try{pf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(s){if(f===l-1){let u=s,$=typeof u.message==="string"?u.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",$),s}f++;let h=c*2**(f-1);await new Promise((u)=>setTimeout(u,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}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 ir(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 ir(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return ir(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(nt())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}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 r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,s])=>s.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(e.length>l)for(let[c]of e.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Qf(16).toString("hex")}generateKey(){return Qf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Qf(16),n=Ba("aes-256-gcm",i,r),e=ni.isBuffer(t)?t:ni.from(t,"utf8"),f=n.update(e),l=n.final(),c=f.length+l.length,s=n.getAuthTag(),h=ni.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),l.copy(h,16+f.length),s.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Lh(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ni.from(ni.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(nt())return;if(!this.shouldWriteToFile())return;let t=await tr(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await qn(this.config.logDirectory),f=e.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,h)=>{let u=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-u}),l=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${l}`;if(await tr(r).catch(()=>null))try{if(await Hh(r,c),i.compress)try{let s=`${c}.gz`;await this.compressLogFile(c,s),await xn(c)}catch(s){console.error("Error compressing rotated file:",s)}if(f.length===0&&!e.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await vf(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await tr(r).catch(()=>null))await Hh(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await qn(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(i.maxFiles))await xn(ir(this.config.logDirectory,l))}}}async compressLogFile(t,i){let r=zh(t),n=Ra(i),e=Lh();await Wa(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Ln(this.currentLogFile))try{let t=Mh(this.currentLogFile,"r+");Oh(t),pf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!nt()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await qn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await xn(ir(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?I.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||nt())return!1;let t=typeof W.env.NO_COLOR<"u",i=W.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof W.stderr<"u"&&W.stderr.isTTY||typeof W.stdout<"u"&&W.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:l=!0}=t,c=(y)=>y.replace(this.ANSI_PATTERN,"");if(!this.fancy){let y=[];if(l)y.push(i);if(f==="warning")y.push("WARN");else if(f==="error")y.push("ERROR");else if(r)y.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)y.push(n.replace(/[[\]]/g,""));return y.push(e),y.join(" ")}let s=W.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${I.cyan(e)}`;if(!l)return h.trim();let u=c(h).trim().length,$=c(i).length,w=Math.max(1,s-2-u-$);return`${h.trim()}${" ".repeat(w)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,l)=>{let c=Number.parseInt(l,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,l)=>{if(l==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(l){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=I.underline(I.blue(n)),l=this.toAbsoluteFilePath(e);if(l&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(l)}`,s="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>I.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>I.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>I.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>I.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>I.strikethrough(n)),i}supportsHyperlinks(){if(nt())return!1;let t=W.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=W.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(ja(i)||i.startsWith("./")||i.startsWith("../"))i=Na(i);else return null;return Ln(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),l,c;if(i instanceof Error)l=i.message,c=i.stack;else l=this.formatMessage(i,r);let{consoleText:s,fileText:h}=this.buildOutputTexts(l);if(this.shouldStyleConsole()){let $=this.options.showIcons===!1?"":qm[t],w=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",y;switch(t){case"debug":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:I.gray(s),level:t}),console.error(y);break;case"info":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.warn(y);break;case"success":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:I.green(s),level:t}),console.error(y);break;case"warning":y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.warn(y);break;case"error":if(y=this.formatConsoleMessage({timestamp:e,icon:$,tag:w,message:s,level:t}),console.error(y),c){let A=c.split(`
111
- `);for(let a of A)if(a.trim()&&!a.includes(l))console.error(this.formatConsoleMessage({timestamp:e,message:I.gray(` ${a}`),level:t,showTimestamp:!1}))}break}}else if(!nt()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${l}`),c)console.error(c)}let u=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
112
- `;if(c)u+=`${c}
113
- `;if(u=u.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(u)}progress(t,i=""){let r={update:(c,s)=>{},finish:(c)=>{},interrupt:(c,s)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!nt()&&W.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!nt()&&W.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,s="info")=>{if(!nt()&&W.stdout.isTTY)W.stdout.write(`
114
- `);if(this[s==="warning"?"warn":s](c),this.activeProgressBar&&this.shouldStyleConsole()&&!nt()&&W.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":I.blue("◐"),tag:r,message:`${I.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,l=new Date,c=this.formatConsoleTimestamp(l),h=`${this.formatFileTimestamp(l)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
115
- `,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let u=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":I.green("✓"),tag:u,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!nt())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Ee(i,{...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(r),r}createReadStream(){if(nt())throw Error("createReadStream is not supported in browser environments");if(!Ln(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return zh(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ni.isBuffer(t)?t:ni.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),l=n.subarray(16,n.length-16),c=Ca("aes-256-gcm",r,e);c.setAuthTag(f);let s=c.update(l),h=c.final(),u=s.length+h.length,$=ni.allocUnsafe(u);return s.copy($,0),h.copy($,s.length),$.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return nt()}isServerMode(){return!nt()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}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(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
116
- `),s=Math.max(...c.map((w)=>w.length))+2,h=`┌${"─".repeat(s)}┐`,u=`└${"─".repeat(s)}┘`,$=c.map((w)=>{return this.formatConsoleMessage({timestamp:r,message:I.cyan(w),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:I.cyan(h),showTimestamp:!1})),$.forEach((w)=>console.error(w)),console.error(this.formatConsoleMessage({timestamp:r,message:I.cyan(u),showTimestamp:!1}))}else if(!nt())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let l=`${n} ${this.environment}.INFO: [BOX] ${f}
117
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}async prompt(t){if(nt())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${I.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();W.stdin.removeListener("data",r);try{if(typeof W.stdin.setRawMode==="function")W.stdin.setRawMode(!1)}catch{}W.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof W.stdin.setRawMode==="function")W.stdin.setRawMode(!0)}catch{}W.stdin.resume(),W.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,h=0;if(r=t.replace(s,(u,$)=>{if($==="%")return"%";if(h>=i.length)return u;let w=i[h++];switch($){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 u}}),h<i.length)r+=` ${i.slice(h).map((u)=>typeof u==="object"?JSON.stringify(u,null,2):String(u)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${I.blue("◐")} `;console.error(`${h}${s} ${I.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
118
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!W.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=I.green("━".repeat(n)),l=I.gray("━".repeat(e)),c=`[${f}${l}]`,s=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",u=this.options.showIcons===!1?"":i||r===100?I.green("✓"):I.blue("▶"),$=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",w=`\r${u}${$} ${c} ${s}${h}`,y=W.stdout.columns||80,A=" ".repeat(Math.max(0,y-w.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${w}${A}`,W.stdout.write(t.lastRenderedLine),i)W.stdout.write(`
119
- `)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||nt()||!W.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(nt()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await qn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=ir(this.config.logDirectory,n);if(t.before)try{if((await tr(f)).mtime>=t.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await xn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var Hd=new Ee("stacks");class Ht extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,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(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class Su extends Ht{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class ye extends Ht{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class Uu extends Ht{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class Fu extends Ht{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class Sl extends Ht{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class ju extends Ht{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Nu extends Ht{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class we extends Ht{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class Wu extends Ht{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class Xu extends Ht{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var er={configNotFound(t,i,r){return new Su(t,i,r)},configLoad(t,i,r){return new ye(t,i,r)},configValidation(t,i,r){return new Uu(t,i,r)},configMerge(t,i,r,n){return new Fu(t,i,r,n)},envVar(t,i,r,n){return new Sl(t,i,r,n)},fileSystem(t,i,r){return new ju(t,i,r)},typeGeneration(t,i,r){return new Nu(t,i,r)},schemaValidation(t,i,r){return new we(t,i,r)},browserConfig(t,i,r,n){return new Wu(t,i,r,n)},plugin(t,i,r){return new Xu(t,i,r)}};async function xm(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,l=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(s){if(l=s instanceof Error?s:Error(String(s)),c===r||!e(l))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw l instanceof Error?l:Error(`Unknown error: ${String(l)}`)}class Ul{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:l={},verbose:c=!1,trackPerformance:s=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let u=n||this.generateEnvPrefix(t),$={...i};return this.processObject($,[],u,{useCamelCase:e,useBackwardCompatibility:f,customParsers:l,verbose:c,configName:t}),{config:$,source:{type:"environment",priority:50,timestamp:new Date}}};if(s)return El.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let l=[...i,e],c=l.map((u)=>this.formatEnvKey(u,n.useCamelCase)),s=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${l.map((u)=>u.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,l,r,n);else{let u=Vn.env[s]||(h?Vn.env[h]:void 0);if(u!==void 0){if(n.verbose){let $=Vn.env[s]?s:h}try{t[e]=this.parseEnvironmentValue(u,typeof f,s,n.customParsers,n.configName)}catch($){if($ instanceof Sl)throw $;throw er.envVar(s,u,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,l]of Object.entries(n))try{return l(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw er.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Vn.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),l=[];switch(this.extractEnvVarInfo(i,[],f,l),e){case"markdown":return this.formatAsMarkdown(l,t);case"json":return JSON.stringify(l,null,2);default:return this.formatAsText(l,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let l=[...i,e],c=`${r}_${l.map((s)=>this.formatEnvKey(s,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,l,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${l.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
120
-
121
- `;for(let n of t)r+=`${n.key}
122
- `,r+=` Type: ${n.type}
123
- `,r+=` Description: ${n.description}
124
- `,r+=` Example: ${n.example}
125
-
126
- `;return r}formatAsMarkdown(t,i){let r=`# Environment Variables for ${i}
127
-
128
- `;r+=`| Variable | Type | Description | Example |
129
- `,r+=`|----------|------|-------------|----------|
130
- `;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
131
- `;return r}}function km(t,i,r={}){return gu(t,i,r,new WeakMap)}function gu(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:l}=r;if(i===null||i===void 0)return f?t:i;if(l){let c=l(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Ju(t,i,e,n);if(!gt(i)||!gt(t))return i;return Pm(t,i,r,n)}function Ju(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return Vm(t,i);case"smart":return Dm(t,i,n);default:return i}return i}function Vm(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Al(e,n)))r.push(n);return r}function Dm(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(gt(i[0])&&gt(t[0]))return bm(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function bm(t,i,r){let n=[...i];for(let e of t){if(!gt(e)){n.push(e);continue}let f=["id","name","key","path","type"],l=!1;for(let c of f)if(c in e){if(n.find((h)=>gt(h)&&(c in h)&&h[c]===e[c])){l=!0;break}}if(!l)n.push(e)}return n}function Pm(t,i,r,n){let e=i;if(gt(e)&&n.has(e))return n.get(e);let f={...t};if(gt(e))n.set(e,f);for(let l in e){if(!Object.prototype.hasOwnProperty.call(e,l))continue;let c=e[l],s=f[l];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[l]=c;continue}if(gt(c)&&gt(s))f[l]=gu(s,c,r,n);else if(Array.isArray(c)||Array.isArray(s))f[l]=Ju(s,c,r.arrayMergeMode||"smart",n);else f[l]=c}return f}function _u(t,i,r="replace"){return km(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Al(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Al(t[r],i[r]))return!1;return!0}if(gt(t)&&gt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Al(t[e],i[e]))return!1}return!0}return!1}function gt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Iu{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:l=!0,verbose:c=!1}=r;if(e){let h=te.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let s=async()=>{if(!Dn(t))return null;try{let h=`?t=${Date.now()}`,u=await import(t+h),$=u.default||u,w="default"in u,y=Object.keys(u).length>0;if(!w&&!y)throw new ye(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof $!=="object"||$===null||Array.isArray($))throw new ye(t,Error("Configuration must export a valid object"),"unknown");let E={config:_u(i,$,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)te.setWithFileCheck("file",E,t,f);return E}catch(h){throw h instanceof Error?er.configLoad(t,h):er.configLoad(t,Error(String(h)))}};if(l)return El.track("loadFromPath",s,{path:t});return s()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let l of this.extensions)e.push(el(i,`${f}${l}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return xm(async()=>{return Dn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Dn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let l of this.extensions){let c=el(t,`${f}${l}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let l of f)if(this.looksLikeConfigFile(l)){let c=el(t,l);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){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((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!Dn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var pm=/^https?:\/\//;class Ku{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:l=[],trackPerformance:c=!0,verbose:s=!1}=r,h=async()=>{let u=[],$=[],w={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:l,trackPerformance:c,verbose:s};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,w);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...l],w);else return this.validateWithJSONSchema(t,i,w)}catch(y){return u.push({path:"",message:`Validation failed: ${y}`,rule:"system"}),{isValid:!1,errors:u,warnings:$}}};if(c)return await El.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!Qm(i))throw new we(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new we(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let l=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(l)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${l}`,expected:c.join(" or "),actual:l,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let l=0;l<t.length;l++){let c=r?`${r}[${l}]`:`[${l}]`;if(this.validateObjectAgainstSchema(t[l],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let l=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in l)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,s]of Object.entries(i.properties))if(c in l){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(l[c],s,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let s of Object.keys(l))if(!c.has(s))e.push({path:r?`${r}.${s}`:s,message:`Additional property '${s}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let l=this.getValueByPath(t,f.path),c=this.validateWithRule(l,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(l){n.push({path:f.path,message:`Rule validation failed: ${l}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,l]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(l)})}return i}mapTypeScriptType(t){switch(t.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:pm},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ei=new Ee("bunfig",{showTags:!0});function vm(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class zu{fileLoader=new Iu;envProcessor=new Ul;validator=new Ku;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...l}=t;try{if(r?.enabled){let s=this.checkCache(l.name||"",l);if(s)return s}let c;try{c=await this.loadConfigurationStrategies(l,!0,r)}catch(s){let h=l.__strictErrorHandling;if(s instanceof Error&&s.name==="ConfigNotFoundError"){if(h)throw s;c={...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(s instanceof Error&&s.name==="ConfigLoadError"){let u=s.message.includes("EACCES")||s.message.includes("EPERM")||s.message.includes("permission denied"),$=!u&&(s.message.includes("syntax")||s.message.includes("Expected")||s.message.includes("Unexpected")||s.message.includes("BuildMessage")||s.message.includes("errors building")),w=s.message.includes("Configuration must export a valid object")||s.message.includes("Configuration file is empty and exports nothing");if(h&&(w||u))throw s;if($&&(!h||!w))c={...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(!h)c={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading error, using defaults: ${s.message}`]};else throw s}else c={...await this.applyEnvironmentVariables(l.name||"",l.defaultConfig,l.checkEnv!==!1,l.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${s instanceof Error?s.message:String(s)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,l.name);if(r?.enabled&&c)this.cacheResult(l.name||"",c,r,l);if(n?.enabled){let s={operation:"loadConfig",duration:Date.now()-i,configName:l.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(s);if(n.slowThreshold&&s.duration>n.slowThreshold)ei.warn(`Slow configuration loading detected: ${s.duration}ms for ${l.name}`);c.metrics=s}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let s=Date.now()-i;throw ei.error(`Configuration loading failed after ${s}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:l,defaultConfig:c,checkEnv:s=!0,arrayStrategy:h="replace",verbose:u=!1}=t,$=f||ae.cwd(),w=[],y=await this.loadLocalConfiguration(n,e,$,l,c,h,u,s,r);if(y)return w.push(...this.getLocalSearchPaths(n,e,$,l)),this.finalizeResult(y,w,s,n,u);let A=await this.loadHomeConfiguration(n,e,c,h,u,s);if(A)return w.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(A,w,s,n,u);let a=await this.loadPackageJsonConfiguration(n,e,$,c,h,u,s);if(a)return w.push(Wt($,"package.json")),this.finalizeResult(a,w,s,n,u);if(w.push(...this.getAllSearchPaths(n,e,$,l)),i)throw er.configNotFound(n,w,e);return{...await this.applyEnvironmentVariables(n,c,s,u),warnings:[`No configuration file found for "${n}"${vm(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,l,c,s){let h=c?bn(t,e,l):e,u=this.getLocalDirectories(r,n);for(let $ of u){if(l)ei.info(`Searching for configuration in: ${$}`);let w=this.fileLoader.generateConfigPaths(t,$,i),y=await this.fileLoader.tryLoadFromPaths(w,h,{arrayStrategy:f,verbose:l,cacheTtl:s?.ttl,useCache:!s?.ttl||s.ttl>100});if(y){if(l)ei.success(`Configuration loaded from: ${y.source.path}`);return y}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let l=f?bn(t,r,e):r,c=[Wt(Vi(),".config",t),Wt(Vi(),".config"),Vi()];for(let s of c){if(e)ei.info(`Checking home directory: ${s}`);let h=this.fileLoader.generateConfigPaths(t,s,i),u=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:n,verbose:e});if(u){if(e)ei.success(`Configuration loaded from home directory: ${u.source.path}`);return u}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,l){let c=l?bn(t,n,f):n;try{let s=Wt(r,"package.json");if(!kw(s))return null;let h={};try{h=JSON.parse(Vw(s,"utf8"))}catch(w){if(f)ei.warn("Failed to parse package.json:",[w instanceof Error?w:Error(String(w))]);return null}let u=h[t],$=t;if(!u&&i){let w=Array.isArray(i)?i:[i];for(let y of w){if(!y)continue;if(h[y]){u=h[y],$=y;break}}}if(u&&typeof u==="object"&&!Array.isArray(u)){if(f)ei.success(`Configuration loaded from package.json: ${$}`);return{config:_u(c,u,e),source:{type:"package.json",path:s,priority:30,timestamp:new Date}}}}catch(s){if(f)ei.warn("Failed to load package.json:",[s instanceof Error?s:Error(String(s))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:bn(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((l)=>l.path?`${l.path}: ${l.message}`:l.message))}if(e.length>0)throw er.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return te.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);te.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Wt(t,"config"),Wt(t,".config"),i?Wt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Wt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let l of e)f.push(...this.fileLoader.generateConfigPaths(t,l,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Wt(Vi(),".config",t),Wt(Vi(),".config"),Vi()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var Vd=new zu;function bn(t,i,r=!1){let n=new Ul,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(l,c=[]){let s={...l};for(let[h,u]of Object.entries(l)){let $=[...c,h],w=[`${e}_${$.join("_").toUpperCase()}`,`${e}_${$.map((a)=>a.toUpperCase()).join("")}`,`${e}_${$.map((a)=>a.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],y,A;for(let a of w)if(y=ae.env[a],y!==void 0){A=a;break}if(y!==void 0&&A)if(typeof u==="boolean")s[h]=["true","1","yes"].includes(y.toLowerCase());else if(typeof u==="number"){let a=Number(y);if(!Number.isNaN(a))s[h]=a}else if(Array.isArray(u))try{s[h]=JSON.parse(y)}catch{s[h]=y.split(",").map((a)=>a.trim())}else s[h]=y;else if(u&&typeof u==="object"&&!Array.isArray(u))s[h]=f(u,$)}return s}return f(i)}var Dd=Wt(ae.cwd(),"config"),bd=Wt(ae.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Zm={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:jl(Fl(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:jl(Fl(),".stacks","ssl","stacks.localhost.crt"),keyPath:jl(Fl(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var Ou=Zm;import{execSync as Xr}from"node:child_process";import{homedir as nA}from"node:os";import{join as eA}from"node:path";function tA(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Ui(t){try{return _n(t)}catch{return null}}function Nl(t){try{return Kf(t)||null}catch{return null}}function Wl(t,i){try{return i.every((r)=>Of(t,r))}catch{return!1}}function iA(t,i,r=443){return zf(t,i,r)}function rA(t){let i=[];for(let r of t.split(`
132
- `)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)i.push(n[1].toUpperCase())}return i}var Ei="-d -r trustRoot -p ssl -p basic",Fi="/Library/Keychains/System.keychain",Xl="rpx.localhost";function gr(){return eA(nA(),"Library/Keychains/login.keychain-db")}function gl(){return[Fi,gr()]}function Mu(t,i=Xl){let r=Xr(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let e of r.split(`
133
- `)){let f=e.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(f)n.push(f[1].toUpperCase())}return n}function Te(t){if(process.platform!=="darwin")return;let i=Ui(t.caPath);if(!i)return;let r=t.commonName??Xl,n=t.keychains??gl();for(let e of n)for(let f of Mu(e,r)){if(f===i)continue;try{if(e.startsWith("/Library"))Wr(`security delete-certificate -Z ${f} "${e}"`);else Xr(`security delete-certificate -Z ${f} "${e}"`,{stdio:"ignore"});m("ssl",`Removed stale Root CA ${f} from ${e}`,t.verbose)}catch{}}}function Jr(t,i,r){if(process.platform!=="darwin")return _r(t,r);try{let e=Xr(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return m("ssl",`verify-cert ${i}: ${e?"trusted":"not trusted"}`,r?.verbose),e}catch{return!1}}function _r(t,i){let r=Ui(t);if(!r)return!1;for(let n of gl())try{let e=Xr(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let f of e.split(`
134
- `))if(f.toUpperCase().includes("SHA-256")){if(f.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return m("ssl",`Root CA fingerprint found in ${n}`,i?.verbose),!0}}catch{}return!1}function Jl(t,i){if(process.platform!=="darwin")return!1;let r=i.serverName;Te({caPath:t,commonName:i.commonName,verbose:i.verbose});let n=gr();try{Xr(`security add-trusted-cert ${Ei} -k "${n}" "${t}"`,{stdio:"ignore"})}catch{}try{Wr(`security add-trusted-cert ${Ei} -k ${Fi} "${t}"`)}catch{return!1}return Jr(t,r,{verbose:i.verbose})||_r(t,{verbose:i.verbose})}var Ti=null,zl=D(fr(),".stacks","ssl","rpx.localhost.crt");function Vu(t,i){return[...new Set(t.filter(Boolean))].map((r)=>({serverName:r,cert:i.cert,key:i.key}))}function Du(t,i,r){let n=D(fr(),".stacks","ssl"),e=[...new Set([i,...t,"rpx.localhost"])];return{https:{certPath:zl,keyPath:D(n,"rpx.localhost.key"),caCertPath:D(n,"rpx.localhost.ca.crt"),commonName:i},verbose:r,regenerateUntrustedCerts:!0,proxies:e.map((f)=>({from:"localhost:1",to:f,cleanUrls:!1}))}}var fA="rpx-root-ca.crt",lA="rpx-root-ca.key";function Ol(t){return{caCertPath:D(t,fA),caKeyPath:D(t,lA)}}function YY(t){return{certPath:D(t,"rpx.localhost.crt"),keyPath:D(t,"rpx.localhost.key"),caCertPath:D(t,"rpx.localhost.ca.crt"),rootCA:Ol(t)}}async function cA(t,i){try{let[r,n]=await Promise.all([Q.readFile(t.caCertPath,"utf8"),Q.readFile(t.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return m("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:r,privateKey:n}}catch(r){return m("ssl",`No existing Root CA at ${t.caCertPath} (${r.code||r}), will create one`,i),null}}function Gu(t){let i=new Set;i.add(t);let r=t.split(".");if(r.length>=2)i.add(`*.${r.slice(1).join(".")}`);return Array.from(i)}function bu(t){let r=Kl(t).replace(/\*/g,"wildcard"),n=D(fr(),".stacks","ssl"),e=n;if(typeof t?.https==="object")return e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:n,{caCertPath:t.https.caCertPath||D(e,`${r}.ca.crt`),certPath:t.https.certPath||D(e,`${r}.crt`),keyPath:t.https.keyPath||D(e,`${r}.key`)};return{caCertPath:D(e,`${r}.ca.crt`),certPath:D(e,`${r}.crt`),keyPath:D(e,`${r}.key`)}}function Hu(t){let i=new Set;if(oe(t))t.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";Gu(n).forEach((e)=>i.add(e))});else if(qu(t)){let r=t.to||"rpx.localhost";Gu(r).forEach((n)=>i.add(n))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function BY(t){m("ssl","Loading SSL configuration",t.verbose);let i={...Ou,...t};if(t.https=Hl(i),!t.https?.keyPath&&!t.https?.certPath)return m("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let r=!t.https?.keyPath?"keyPath":"certPath";throw m("ssl",`Invalid SSL configuration - missing ${r}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{m("ssl","Reading SSL certificate files",t.verbose);let r=await Q.readFile(t.https?.keyPath,"utf8"),n=await Q.readFile(t.https?.certPath,"utf8");return m("ssl","SSL configuration loaded successfully",t.verbose),{key:r,cert:n}}catch(r){return m("ssl",`Failed to read certificates: ${r}`,t.verbose),null}}catch(r){throw m("ssl",`SSL configuration error: ${r}`,t.verbose),r}}async function CY(t,i){if(Lt.platform==="darwin")return sA(t,i);if(Lt.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(e)=>{if(!e)n(!0);else r(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{n(!f)})})})}catch{return!1}return!1}async function sA(t,i){if(Lt.platform!=="darwin")return!1;let r=i?.serverName??"rpx.localhost",n=i?.verbose??!1;try{if(Jr(t,r,{verbose:n}))return m("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return m("ssl","Trusting Root CA for browsers (login + system keychains)",n),Jl(t,{serverName:r,verbose:n})}catch{return!1}}async function Pu(t){if(Ti&&!t.forceRegenerate){m("ssl","Using cached SSL configuration",t.verbose);return}Ml();let i=oe(t)?t.proxies.map((u)=>u.to):[t.to];m("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let r=Hl(t,t.verbose),n=r.basePath||D(fr(),".stacks","ssl");await Q.mkdir(n,{recursive:!0});let e=Ol(n),f=await cA(e,t.verbose),l=!1;if(!f){if(t.verbose)j.info("Generating Root CA certificate (one-time)...");f=await _f(r);try{await Promise.all([Q.writeFile(e.caCertPath,f.certificate),Q.writeFile(e.caKeyPath,f.privateKey,{mode:384})]),l=!0,m("ssl",`Persisted Root CA at ${e.caCertPath}`,t.verbose)}catch(u){throw m("ssl",`Error saving Root CA files: ${u}`,t.verbose),Error(`Failed to save Root CA files: ${u}`)}}else m("ssl",`Reusing existing Root CA from ${e.caCertPath}`,t.verbose);if(t.verbose)j.info(`Generating host certificate for: ${i.join(", ")}`);let c=await If({...r,rootCA:{certificate:f.certificate,privateKey:f.privateKey}});try{await Promise.all([Q.writeFile(r.certPath,c.certificate),Q.writeFile(r.keyPath,c.privateKey),Q.writeFile(r.caCertPath,f.certificate)]),m("ssl","Certificate files saved successfully",t.verbose)}catch(u){throw m("ssl",`Error saving certificate files: ${u}`,t.verbose),Error(`Failed to save certificate files: ${u}`)}if(l?!1:await Qu(e.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if(m("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)j.success("Root CA is already trusted in system trust store");if(Ti={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)j.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)j.info("Adding certificate to system trust store (may require sudo permission)...");let h=!1;if(Lt.platform==="darwin")try{Te({caPath:e.caCertPath,verbose:t.verbose});let u=gr();try{_l(`security add-trusted-cert ${Ei} -k "${u}" "${e.caCertPath}"`,{stdio:"ignore"})}catch{}if(Wr(`security add-trusted-cert ${Ei} -k ${Fi} "${e.caCertPath}"`),t.verbose)j.success("Successfully added Root CA to system trust store");h=!0;let $=D(n,"trust-rpx-cert.sh"),w=`#!/bin/bash
135
- echo "Trusting RPX Root CA"
136
- sudo security add-trusted-cert ${Ei} -k ${Fi} "${e.caCertPath}"
137
- echo "Root CA trusted! Please restart your browser."
138
- echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
139
- `;await Q.writeFile($,w,{mode:493})}catch(u){if(t.verbose)j.warn(`Could not add Root CA to trust store automatically: ${u}`);let $=D(n,"trust-rpx-cert.sh"),w=`#!/bin/bash
140
- echo "Trusting RPX Root CA"
141
- sudo security add-trusted-cert ${Ei} -k ${Fi} "${e.caCertPath}"
142
- echo "Root CA trusted! Please restart your browser."
143
- echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
144
- `;if(await Q.writeFile($,w,{mode:493}),t.verbose)j.info(`Created a trust helper script at: ${$}`),j.info(`If you're still having certificate issues, run: sh ${$}`)}else if(Lt.platform==="linux")try{let{exec:u}=await import("node:child_process"),$="/usr/local/share/ca-certificates/rpx",w=`
145
- mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
146
- cp "${e.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
147
- update-ca-certificates
148
- echo "RPX Root CA installed. Please restart your browser."
149
- `,y=D(Il.tmpdir(),`rpx-trust-${Date.now()}.sh`);await Q.writeFile(y,w,{mode:493}),await new Promise((A)=>{u(`sudo bash "${y}"`,(a)=>{if(a){if(t.verbose)j.warn(`Could not trust certificates: ${a}`);A(!1)}else{if(t.verbose)j.success("Successfully added certificates to system trust store");A(!0)}})}),await Q.unlink(y).catch(()=>{}),h=!0}catch(u){if(t.verbose)j.warn(`Failed to trust certificates: ${u}`)}else if(Lt.platform==="win32")try{let u=`
150
- $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${e.caCertPath.replace(/\//g,"\\")}")
151
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
152
- $store.Open("ReadWrite")
153
- $store.Add($cert)
154
- $store.Close()
155
- Write-Host "Root CA trusted successfully!"
156
- `,$=D(Il.tmpdir(),"rpx-trust.ps1");if(await Q.writeFile($,u),_l(`powershell -ExecutionPolicy Bypass -File "${$}"`),t.verbose)j.success("Successfully added certificate to Windows trust store");h=!0}catch(u){if(t.verbose)j.warn(`Could not trust certificate: ${u}`)}else try{await Mf(c,f.certificate,r),h=!0}catch(u){if(t.verbose)j.warn(`Could not add certificate to trust store: ${u}`)}if(Ti={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)j.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!h&&t.verbose)j.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),j.warn("This will bypass the warning and you should only need to do it once")}function Ml(){Ti=null}async function Gl(t){if(!t)return null;if(Ti)return Ti;let i=Hl(t);try{let[r,n,e]=await Promise.all([Q.access(i.keyPath).then(()=>!0).catch(()=>!1),Q.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?Q.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return m("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let f="regenerateUntrustedCerts"in t,l=t.regenerateUntrustedCerts,c=f?l!==!1:!0;m("ssl",`Trust check: hasFlag=${f}, flagValue=${l}, shouldCheckTrust=${c}`,t.verbose);let s=i.basePath||D(fr(),".stacks","ssl"),h=Ol(s);if(!(c?await Qu(h.caCertPath,t):!0))return m("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[$,w,y]=await Promise.all([Q.readFile(i.keyPath,"utf8"),Q.readFile(i.certPath,"utf8"),e&&i.caCertPath?Q.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(y&&!y.includes("-----BEGIN CERTIFICATE-----"))return m("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(oe(t))try{let{X509Certificate:A}=await import("node:crypto"),E=new A(w).subjectAltName||"",d=t.proxies.map((Y)=>Y.to).filter((Y)=>!E.includes(`DNS:${Y}`));if(d.length>0)return m("ssl",`Certificate missing SANs for: ${d.join(", ")}, will regenerate`,t.verbose),null}catch(A){m("ssl",`Could not verify cert SANs: ${A}`,t.verbose)}return m("ssl","Successfully loaded existing certificates",t.verbose),Ti={key:$,cert:w,ca:y},Ti}catch(r){return m("ssl",`Error checking existing certificates: ${r}`,t.verbose),null}}function Hl(t,i){let r=Kl(t);m("ssl",`Primary domain: ${r}`,i);let n=bu(t),e=D(fr(),".stacks","ssl");if(typeof t.https==="object"){let f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:e,l={domain:r,hostCertCN:r,basePath:f,caCertPath:t.https.caCertPath||n.caCertPath,certPath:t.https.certPath||n.certPath,keyPath:t.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||r,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(Hu(t)).map((c)=>({type:2,value:c}))};if(Lu(t.https.rootCA))l.rootCA=t.https.rootCA;return l}return{domain:r,hostCertCN:r,basePath:e,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(Hu(t)).map((f)=>({type:2,value:f}))}}async function RY(t,i){let r=bu({to:t,verbose:i}),n=[r.caCertPath,r.certPath,r.keyPath];m("certificates","Attempting to clean up relating certificates",i),await Promise.all(n.map((e)=>xu(e,i)))}async function Qu(t,i){try{if(m("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),Lt.platform==="darwin"){if(i?.serverName)return Jr(t,i.serverName,{verbose:i?.verbose});return _r(t,{verbose:i?.verbose})}else if(Lt.platform==="win32")try{let r=Nl(t)||"";if(!r)return m("ssl","Could not extract certificate subject",i?.verbose),!1;let n=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(_l(n).toString().includes(r))return m("ssl","Certificate found in trusted root store",i?.verbose),!0;return m("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Windows: ${r}`,i?.verbose),!1}else if(Lt.platform==="linux")try{let r=Ui(t);if(!r)return m("ssl","Could not extract certificate fingerprint",i?.verbose),!1;let n=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let e of n){let f;try{f=await Q.readdir(e)}catch{continue}for(let l of f){let c=Ui(ku.join(e,l));if(c&&c===r)return m("ssl",`Certificate fingerprint found in ${e}`,i?.verbose),!0}}return m("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Linux: ${r}`,i?.verbose),!1}return m("ssl",`Platform ${Lt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(r){return m("ssl",`Error checking if certificate is trusted: ${r}`,i?.verbose),!1}}var{connect:hA}=Bun,Ir=Symbol("rpx.pool.fallback"),de=Symbol("rpx.pool.stale");var uA=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function $A(t){return uA.has(t.toUpperCase())}var ql=Symbol("rpx.pool.timeout"),ji=Symbol("rpx.pool.busy");function yA(){let t=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(t)&&t>0?t:30000}function wA(t){let i=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(i)&&i>0?i:t*8}function aA(){let t=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(t)&&t>0?t:0}function mA(){let t=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(t)&&t>0?t:0}var Zu=1048576;function AA(){let t=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(t)&&t>0?t:256}var Ll=30000,EA=16384,t0=262144,TA=2097152,oA=524288,dA=8192,YA=4096,BA=new TextEncoder,i0=new TextDecoder,CA=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class r0{socket=null;buf=new Uint8Array(EA);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(t){let i=this.socket,r=i.write(t);while(r<t.length){if(this.closed)throw de;await new Promise((n)=>{this.drainWaiter=n}),r+=i.write(t.subarray(r))}}wakeDrain(){let t=this.drainWaiter;if(t)this.drainWaiter=null,t()}push(t){if(this.bodyQueue){let i=t.length<=this.bodyRemaining?t.length:this.bodyRemaining;if(i>0)this.bodyQueue.push(t.slice(0,i)),this.queuedBytes+=i;if(this.bodyRemaining-=i,i<t.length)this.appendToBuf(t.subarray(i));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(t),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()>TA)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=oA)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(t){let i=this.len+t.length;if(i>this.buf.length){let r=new Uint8Array(Math.max(this.buf.length*2,i));r.set(this.buf.subarray(0,this.len)),this.buf=r}this.buf.set(t,this.len),this.len=i}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let t=this.waiter;if(t)this.waiter=null,t()}waitForData(t){if(this.len>t||this.closed)return Promise.resolve();return new Promise((i)=>{this.waiter=i})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}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 n0{host;port;maxTotal;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=yA();maxWaiters;checkoutIdleMs=aA();inUse=new Set;constructor(t,i,r){this.host=t;this.port=i;this.maxTotal=r;this.maxWaiters=wA(r)}trackCheckout(t){if(t.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(t),this.ensureSweeper()}dial(){let t=new r0;return hA({hostname:this.host,port:this.port,socket:{data:(i,r)=>t.push(r),drain:()=>t.wakeDrain(),close:()=>t.markClosed(),end:()=>t.markClosed(),error:()=>t.markClosed(),connectError:()=>t.markClosed(),timeout:()=>t.markTimedOut()}}).then((i)=>{let r=i;r.setNoDelay?.(!0);let n=mA();if(n>0)r.timeout?.(n);return t.socket=i,t})}acquireIdleSync(){while(this.idle.length){let t=this.idle.pop();if(!t.closed)return t.socket?.ref(),t.pos=0,t.len=0,this.trackCheckout(t),t;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw ji;let t=await this.waitForSlot();if(t===ji)throw ji;if(t)return t.pos=0,t.len=0,this.trackCheckout(t),t}this.open++;try{let t=await this.dial();return this.trackCheckout(t),t}catch(t){throw this.open--,this.wakeWaiter(),t}}waitForSlot(){return new Promise((t)=>{let i=!1,r=(f)=>{if(i)return;i=!0,clearTimeout(e),t(f)},n=(f)=>r(f),e=setTimeout(()=>{let f=this.waiters.indexOf(n);if(f!==-1)this.waiters.splice(f,1);r(ji)},this.queueWaitMs);e.unref?.(),this.waiters.push(n)})}release(t){if(this.inUse.delete(t),t.closed){this.open--,this.wakeWaiter();return}t.clearStreaming(),t.compact(),t.fresh=!1;let i=this.waiters.shift();if(i){t.socket?.ref(),this.trackCheckout(t),i(t);return}t.idleSince=Date.now(),t.socket?.unref(),this.idle.push(t),this.ensureSweeper()}destroy(t){this.inUse.delete(t),t.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let t=this.waiters.shift();if(t)t(null)}ensureSweeper(){if(this.sweeper)return;let t=this.checkoutIdleMs>0?Math.min(Ll,this.checkoutIdleMs):Ll;this.sweeper=setInterval(()=>this.sweep(),t),this.sweeper.unref?.()}sweep(){let t=Date.now(),i=t-Ll;if(this.idle.length){let r=[];for(let n of this.idle)if(n.closed||n.idleSince<=i)n.destroy(),this.open--;else r.push(n);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=t-this.checkoutIdleMs;for(let n of this.inUse)if(!n.closed&&n.lastActivityAt>0&&n.lastActivityAt<=r)n.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper)clearInterval(this.sweeper),this.sweeper=null}}var pu=new Map;function RA(t,i){let r=pu.get(t);if(!r){let n=t.lastIndexOf(":"),e=n===-1?t:t.slice(0,n),f=n===-1?80:Number(t.slice(n+1));r=new n0(e,f,i),pu.set(t,r)}return r}function vu(t,i,r){for(let n=r+3;n<i;n++)if(t[n]===10&&t[n-1]===13&&t[n-2]===10&&t[n-3]===13)return n-3;return-1}function SA(t,i,r){let n=i0.decode(t.subarray(i,r)),e=n.indexOf(`\r
157
- `),f=e===-1?n:n.slice(0,e),l=f.indexOf(" "),c=Number.parseInt(f.slice(l+1,l+5),10),s=f.startsWith("HTTP/1.0"),h=[],u=-1,$=!1,w=s,y=!1,A=!1,a=e===-1?n.length:e+2;while(a<n.length){let E=n.indexOf(`\r
158
- `,a);if(E===-1)E=n.length;let T=n.slice(a,E);if(a=E+2,T==="")continue;let d=T.indexOf(":");if(d===-1)continue;let Y=T.slice(0,d),U=T.slice(d+1).trim(),B=Y.charCodeAt(0)|32;if(B===99||B===116||B===107){let X=Y.toLowerCase();if(X==="content-length"){let V=/^\d+$/.test(U)?Number(U):Number.NaN;if(!Number.isSafeInteger(V)||u>=0&&u!==V)A=!0;else u=V;continue}if(X==="transfer-encoding"){if(U.toLowerCase().includes("chunked"))$=!0;continue}if(X==="connection"){let V=U.toLowerCase();if(V.includes("close"))w=!0;if(V.includes("keep-alive"))y=!0;continue}if(X==="keep-alive")continue}h.push([Y,U])}if(s&&y)w=!1;if($&&u>=0)u=-1;return{status:c,headerEnd:r,headers:h,contentLength:u,chunked:$,closeConn:w,malformed:A}}function UA(t,i){return i||t===204||t===304}async function e0(t){let{hostPort:i,method:r,path:n,reqHeaders:e,forwardedHost:f,originOverride:l,body:c}=t,s=r==="HEAD";if(e.get("expect")||e.get("upgrade"))throw Ir;let h=null;if(c){let y=e.get("content-length"),A=y?Number.parseInt(y,10):Number.NaN;if(Number.isNaN(A)||A>Zu)throw Ir;if(h=await JA(c),h===null)throw Ir}let u=gA(r,n,e,i,f,l,h),$=u;if(h&&h.length)$=new Uint8Array(u.length+h.length),$.set(u),$.set(h,u.length);let w=RA(i,t.maxPerHost??AA());for(let y=0;;y++){if(y>0)await new Promise((a)=>{setTimeout(a,y)});let A;try{A=w.acquireIdleSync()??await w.acquireOrDial()}catch(a){if(a!==ji&&y<4)continue;throw a}try{let a=A.socket.write($);if(a<$.length)await A.writeAll($.subarray(a));return await jA(w,A,s)}catch(a){let E=a===de&&y<4&&(A.fresh||$A(r));if(w.destroy(A),E)continue;if(a===de)throw Error("upstream closed connection");throw a}}}async function FA(t){let i=vu(t.buf,t.len,t.pos);while(i===-1){if(t.closed){if(t.timedOut)throw ql;if(t.len===t.pos)throw de;throw Error("upstream closed mid-header")}if(t.len-t.pos>t0)throw Error("upstream header block too large");await t.waitForData(t.len),i=vu(t.buf,t.len,t.pos)}return i}async function jA(t,i,r){let n;for(;;){let f=await FA(i);if(n=SA(i.buf,i.pos,f),i.pos=f+4,n.status>=100&&n.status<200)continue;break}if(n.malformed)throw t.destroy(i),Error("upstream sent malformed response framing");let e=n.headers;if(UA(n.status,r))return f0(t,i,n.closeConn),new Response(null,{status:n.status,headers:e});if(n.chunked)return new Response(XA(t,i,n.closeConn),{status:n.status,headers:e});if(n.contentLength>=0){if(i.len-i.pos>=n.contentLength){let l=i.pos+n.contentLength,c=i.len>l,s=null;if(n.contentLength>=dA)s=i.buf.subarray(i.pos,l),i.buf=new Uint8Array(YA);else if(n.contentLength>0)s=i.buf.slice(i.pos,l);if(i.pos=0,i.len=0,n.closeConn||c)t.destroy(i);else t.release(i);return new Response(s,{status:n.status,headers:e})}return new Response(NA(t,i,n.contentLength,n.closeConn),{status:n.status,headers:e})}return new Response(WA(i),{status:n.status,headers:e})}function f0(t,i,r){if(r||i.pos!==i.len)t.destroy(i);else t.release(i)}function NA(t,i,r,n){let e=i.len-i.pos,f=e>0?i.buf.slice(i.pos,i.len):null;i.pos=0,i.len=0,i.bodyQueue=[],i.bodyRemaining=r-e,i.queuedBytes=0,i.streamingBody=!0;let l=(c)=>{if(i.bodyQueue=null,n||i.len>0)t.destroy(i);else t.release(i);c.close()};return new ReadableStream({start(c){if(f)c.enqueue(f);if(i.bodyRemaining===0&&i.bodyQueue.length===0)l(c)},async pull(c){for(;;){let s=i.bodyQueue;if(s&&s.length>0){let h=s.shift();if(i.queuedBytes-=h.length,i.resumeIfDrained(),c.enqueue(h),i.bodyRemaining===0&&s.length===0)l(c);return}if(i.bodyRemaining===0){if(i.bodyQueue)l(c);return}if(i.closed){i.bodyQueue=null,t.destroy(i),c.error(Error("upstream closed mid-body"));return}await i.waitForBody()}},cancel(){i.bodyQueue=null,t.destroy(i)}})}function WA(t){return t.streamingBody=!0,new ReadableStream({async pull(i){for(;;){if(t.len>t.pos){i.enqueue(t.buf.slice(t.pos,t.len)),t.pos=t.len,t.resumeIfDrained();return}if(t.closed){t.destroy(),i.close();return}await t.waitForData(t.len)}},cancel(){t.destroy()}})}function XA(t,i,r){i.streamingBody=!0;let n=0,e=!1;async function f(){for(;;){for(let l=i.pos;l+1<i.len;l++)if(i.buf[l]===13&&i.buf[l+1]===10){let c=i0.decode(i.buf.subarray(i.pos,l));return i.pos=l+2,c}if(i.closed)throw Error("upstream closed mid-chunk-header");if(i.len-i.pos>t0)throw Error("upstream chunk header too large");await i.waitForData(i.len)}}return new ReadableStream({async pull(l){for(;;){if(n>0){if(i.len===i.pos){if(i.closed){t.destroy(i),l.error(Error("upstream closed mid-chunk"));return}await i.waitForData(i.len);continue}let u=Math.min(n,i.len-i.pos);if(l.enqueue(i.buf.slice(i.pos,i.pos+u)),i.pos+=u,n-=u,i.resumeIfDrained(),n===0)e=!0;return}if(e)await f(),e=!1;let c=await f(),s=c.indexOf(";"),h=Number.parseInt(s===-1?c:c.slice(0,s),16);if(!Number.isInteger(h)||h<0){t.destroy(i),l.error(Error("upstream sent malformed chunk size"));return}if(h===0){for(;;)if(await f()==="")break;f0(t,i,r),l.close();return}n=h}},cancel(){t.destroy(i)}})}function gA(t,i,r,n,e,f,l){let c=`${t} ${i} HTTP/1.1\r
159
- host: ${n}\r
160
- x-forwarded-for: 127.0.0.1\r
161
- x-forwarded-proto: https\r
162
- x-forwarded-host: ${e}\r
163
- `;if(f!==void 0)c+=`origin: ${f}\r
164
- `;let s=!1;for(let[h,u]of r){let $=h.toLowerCase();if(CA.has($))continue;if(f!==void 0&&$==="origin")continue;if($==="content-length")s=!0;c+=`${h}: ${u}\r
165
- `}if(c+=`connection: keep-alive\r
166
- `,l&&!s)c+=`content-length: ${l.length}\r
167
- `;return c+=`\r
168
- `,BA.encode(c)}async function JA(t){let i=t.getReader(),r=[],n=0;for(;;){let{done:l,value:c}=await i.read();if(l)break;if(c){if(n+=c.length,n>Zu)return i.cancel().catch(()=>{}),null;r.push(c)}}if(r.length===1)return r[0];let e=new Uint8Array(n),f=0;for(let l of r)e.set(l,f),f+=l.length;return e}import*as Jt from"node:path";function l0(t,i){if(typeof t==="string")return{dir:t,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:i};return{dir:t.dir,spa:t.spa??!1,pathRewriteStyle:t.pathRewriteStyle??"directory",maxAge:t.maxAge??0,cleanUrls:i}}var _A={".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 IA(t){let i=Jt.extname(t).toLowerCase();return _A[i]??"application/octet-stream"}function KA(t){let i;try{i=decodeURIComponent(t)}catch{return null}if(i.includes("\x00")||i.includes("\\"))return null;let r=Jt.posix.normalize(`/${i}`);if(r.includes(".."))return null;return r.replace(/^\/+/,"")}function zA(t,i){let r=KA(t);if(r===null)return null;let n=Jt.posix.extname(r);if(i.cleanUrls&&n===".html"){let e=t.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Jt.join(i.dir,r),redirectTo:e||"/"}}if(r===""||t.endsWith("/"))return{filePath:Jt.join(i.dir,r,"index.html")};if(n!=="")return{filePath:Jt.join(i.dir,r)};if(i.pathRewriteStyle==="flat")return{filePath:Jt.join(i.dir,`${r}.html`)};return{filePath:Jt.join(i.dir,r,"index.html")}}async function c0(t,i){let r=zA(t,i);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=i.maxAge>0?`public, max-age=${i.maxAge}`:"no-cache",e=Bun.file(r.filePath);if(await e.exists())return new Response(e,{status:200,headers:{"Content-Type":IA(r.filePath),"Cache-Control":n}});if(i.spa){let f=Jt.join(i.dir,"index.html"),l=Bun.file(f);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})}var OA=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function MA(t){let i=t.headers.get("host")||"",r=i.indexOf(":");return r===-1?i:i.slice(0,r)}function u0(t,i){if(!i||i==="/")return t;if(t===i)return"/";if(t.startsWith(`${i}/`)){let r=t.slice(i.length);return r===""?"/":r}return t}function s0(t,i,r){let n=i.sourceHost??"",f=i.stripBasePathPrefix??!1?u0(t,i.basePath):t,l=h0(f,i.pathRewrites);if(l)n=l.targetHost,f=l.targetPath,m("request",`Path rewrite: ${t} → ${n}${f}`,r);return{targetHost:n,targetPath:f}}function GA(t){let i=t.indexOf("://"),r=i===-1?t.indexOf("/"):t.indexOf("/",i+3);if(r===-1)return{pathname:"/",search:""};let n=t.indexOf("?",r);if(n===-1)return{pathname:t.slice(r),search:""};return{pathname:t.slice(r,n),search:t.slice(n)}}function xl(t,i){let r=async(n,e)=>{let{pathname:f,search:l}=GA(n.url),c=MA(n),s=t(c,f);if(!s)return m("request",`No route found for host: ${c}`,i),new Response(`No proxy configured for ${c}`,{status:404});if(s.static){let A=s.stripBasePathPrefix??!0?u0(f,s.basePath):f;return c0(A,s.static)}if(n.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!e||!s.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:y,targetPath:A}=s0(f,s,i),a=`ws://${y}${A}${l}`,E={};for(let[Y,U]of n.headers)if(!OA.has(Y.toLowerCase())&&Y.toLowerCase()!=="host")E[Y]=U;E.host=y,E["x-forwarded-for"]="127.0.0.1",E["x-forwarded-proto"]="https",E["x-forwarded-host"]=c;let T={targetUrl:a,forwardHeaders:E};if(e.upgrade(n,{data:T})){m("ws",`upgraded ${c}${A} → ${a}`,i);return}return new Response("WebSocket upgrade failed",{status:400})}if(!s.sourceHost)return new Response(`No upstream configured for ${c}`,{status:502});if(s.cleanUrls&&f.endsWith(".html")){let y=f.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:y}})}let{targetHost:h,targetPath:u}=s0(f,s,i),$=s.changeOrigin?`http://${s.sourceHost}`:void 0,w=n.body!=null&&n.method!=="GET"&&n.method!=="HEAD";try{return await e0({hostPort:h,method:n.method,path:`${u}${l}`,reqHeaders:n.headers,forwardedHost:c,originOverride:$,body:n.body})}catch(y){if(y===ql)return m("request",`Upstream timeout for ${c}`,i),new Response("Gateway Timeout",{status:504});if(y===ji)return m("request",`Upstream pool saturated for ${c}`,i),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(y===Ir||!w)try{let A=new Headers(n.headers);if(A.set("host",h),A.set("x-forwarded-for","127.0.0.1"),A.set("x-forwarded-proto","https"),A.set("x-forwarded-host",c),$!==void 0)A.set("origin",$);return await fetch(`http://${h}${u}${l}`,{method:n.method,headers:A,body:n.body,redirect:"manual"})}catch(A){return m("request",`Proxy error for ${c}: ${A}`,i),new Response(`Proxy Error: ${A}`,{status:502})}return m("request",`Proxy error for ${c}: ${y}`,i),new Response(`Proxy Error: ${y}`,{status:502})}};return async(n,e)=>{try{return await r(n,e)}catch(f){return m("request",`Unhandled proxy handler error: ${f}`,i),new Response("Bad Gateway",{status:502})}}}function kl(t){let i=new WeakMap;return{open(r){let{targetUrl:n,forwardHeaders:e}=r.data,f;try{f=new WebSocket(n,{headers:e})}catch(c){m("ws",`failed to open upstream ${n}: ${c}`,t),r.close(1011,"upstream connect failed");return}f.binaryType="arraybuffer";let l={upstream:f,upstreamOpen:!1,pending:[]};i.set(r,l),f.addEventListener("open",()=>{l.upstreamOpen=!0;for(let c of l.pending)f.send(c);l.pending=[]}),f.addEventListener("message",(c)=>{r.send(c.data)}),f.addEventListener("close",(c)=>{try{r.close(c.code||1000,c.reason||"")}catch{}}),f.addEventListener("error",()=>{m("ws",`upstream error for ${n}`,t);try{r.close(1011,"upstream error")}catch{}})},message(r,n){let e=i.get(r);if(!e)return;let f=typeof n==="string"?n:new Uint8Array(n);if(e.upstreamOpen)e.upstream.send(f);else e.pending.push(f)},close(r,n,e){let f=i.get(r);if(!f)return;i.delete(r);try{f.upstream.close(n||1000,e||"")}catch{}}}}function Ye(t){return t.startsWith("*.")}function Vl(t,i){if(!Ye(i))return!1;let r=i.slice(1);return t.length>r.length&&t.endsWith(r)}function _Y(t,i){let r=t.get(i);if(r!==void 0)return r;let n,e=-1;for(let[f,l]of t){if(!Ye(f))continue;if(Vl(i,f)){let c=f.length-1;if(c>e)e=c,n=l}}return n}function Dl(t){if(!t||t==="/")return"/";let i=t.trim();if(!i.startsWith("/"))i=`/${i}`;return i=i.replace(/\/+$/,""),i===""?"/":i}function HA(t,i){if(i==="/")return!0;if(t===i)return!0;return t.startsWith(`${i}/`)}function bl(t){let i=new Map;for(let n of t){let e=Dl(n.path),f=i.get(n.host);if(!f)f=new Map,i.set(n.host,f);f.set(e,n.route)}let r=new Map;for(let[n,e]of i){let f=[];for(let[l,c]of e)f.push({path:l,route:c});f.sort((l,c)=>c.path.length-l.path.length),r.set(n,f)}return r}function LA(t,i){let r=t.get(i);if(r!==void 0)return r;let n,e=-1;for(let[f,l]of t){if(!Ye(f))continue;if(Vl(i,f)){let c=f.length-1;if(c>e)e=c,n=l}}return n}function Pl(t,i,r){let n=LA(t,i);if(!n)return;for(let e of n)if(HA(r,e.path))return e.route;return}import*as Kr from"node:fs/promises";import*as Ql from"node:path";function qA(t){if(!t.endsWith(".crt"))return null;let i=t.slice(0,-4);if(i.length===0)return null;if(i.startsWith("_wildcard."))return`*.${i.slice(10)}`;return i}async function xA(t,i,r,n){try{let[e,f]=await Promise.all([Kr.readFile(i,"utf8"),Kr.readFile(r,"utf8")]);return{serverName:t,cert:e,key:f}}catch(e){return m("sni",`skipping ${t}: ${e.message}`,n),null}}async function pl(t,i){let r=new Map;if(t.certsDir){let e=[];try{e=await Kr.readdir(t.certsDir)}catch(f){m("sni",`certsDir read failed (${t.certsDir}): ${f.message}`,i)}for(let f of e){let l=qA(f);if(!l)continue;let c=f.slice(0,-4);r.set(l,{certPath:Ql.join(t.certsDir,f),keyPath:Ql.join(t.certsDir,`${c}.key`)})}}if(t.domains)for(let[e,f]of Object.entries(t.domains))r.set(e,f);let n=[];for(let[e,f]of r){let l=await xA(e,f.certPath,f.keyPath,i);if(l)n.push(l)}return n}import*as oi from"node:fs/promises";import*as vl from"node:path";var kA=60000,$0=4096;function VA(t,i){if(!i||i.length===0)return!1;return i.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return t===n||t.endsWith(`.${n}`)})}function y0(t){if(!t||t.length>253)return!1;if(t.includes("/")||t.includes(":")||t.includes(" "))return!1;if(t.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(t)}class Be{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(t){this.config=t.config,this.certsDir=t.certsDir,this.onCertAdded=t.onCertAdded,this.http01Store=t.http01Store??Fn,this.issuer=t.issuer??df,this.verbose=t.verbose??!1,this.negativeCacheMs=t.negativeCacheMs??kA;for(let i of t.initial??[])this.certs.set(i.serverName,i)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(t){return this.certs.has(t)}async isApproved(t){if(!y0(t))return!1;if(VA(t,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(t)}catch(i){return m("on-demand",`ask(${t}) threw: ${i.message}`,this.verbose),!1}return!1}async ensureCert(t){if(!this.config.enabled)return!1;if(this.certs.has(t))return!0;if(!y0(t))return!1;let i=this.inFlight.get(t);if(i)return i;let r=this.negativeCache.get(t);if(r!==void 0&&Date.now()<r)return m("on-demand",`${t} negatively cached for ${r-Date.now()}ms`,this.verbose),!1;let n=this.issue(t).finally(()=>{this.inFlight.delete(t)});return this.inFlight.set(t,n),n}async issue(t){if(this.certs.has(t))return!0;if(await this.loadFromDisk(t))return!0;if(!await this.isApproved(t))return m("on-demand",`refused issuance for ${t} (not approved)`,this.verbose),this.cacheNegative(t),!1;try{m("on-demand",`issuing cert for ${t} (staging=${this.config.staging??!1})`,this.verbose);let i=await this.issuer({domains:[t],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(t,i.fullChainPem,i.keyPem);let r={serverName:t,cert:i.fullChainPem,key:i.keyPem};return this.certs.set(t,r),this.negativeCache.delete(t),m("on-demand",`issued + installed cert for ${t}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(i){return this.cacheNegative(t),m("on-demand",`issuance for ${t} failed: ${i.message}`,this.verbose),!1}}cacheNegative(t){if(this.negativeCache.size>=$0){let i=Date.now();for(let[r,n]of this.negativeCache)if(n<=i)this.negativeCache.delete(r);if(this.negativeCache.size>=$0){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(t,Date.now()+this.negativeCacheMs)}async loadFromDisk(t){let{certPath:i,keyPath:r}=this.pathsFor(t);try{let[n,e]=await Promise.all([oi.readFile(i,"utf8"),oi.readFile(r,"utf8")]),f={serverName:t,cert:n,key:e};return this.certs.set(t,f),m("on-demand",`adopted existing on-disk cert for ${t}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(t){return{certPath:vl.join(this.certsDir,`${t}.crt`),keyPath:vl.join(this.certsDir,`${t}.key`)}}async persist(t,i,r){await oi.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:e}=this.pathsFor(t);await Promise.all([oi.writeFile(n,i,"utf8"),oi.writeFile(e,r,{encoding:"utf8",mode:384})])}}import*as Ce from"node:fs";import*as Tt from"node:fs/promises";import{homedir as DA}from"node:os";import*as Zl from"node:path";import*as Re from"node:process";var bA=/^[a-zA-Z0-9._-]+$/;function lr(){return Zl.join(DA(),".stacks","rpx","registry.d")}function tc(t){return typeof t==="string"&&t.length>0&&t.length<=128&&bA.test(t)}function ic(t,i){if(!tc(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return Zl.join(t,`${i}.json`)}function qt(t){if(!Number.isInteger(t)||t<=0)return!1;try{return Re.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function w0(t){if(!t||typeof t!=="object")return!1;let i=t,r=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0,n=typeof i.from==="string"&&i.from.length>0,e=typeof i.static==="string"||!!i.static&&typeof i.static==="object"&&typeof i.static.dir==="string",f=i.path===void 0||typeof i.path==="string";return typeof i.id==="string"&&tc(i.id)&&(n||e)&&typeof i.to==="string"&&i.to.length>0&&f&&r&&typeof i.createdAt==="string"}async function PA(t){await Tt.mkdir(t,{recursive:!0})}async function kY(t,i=lr(),r){if(!w0(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await PA(i);let n=ic(i,t.id),e=`${n}.tmp.${Re.pid}.${Date.now()}`,f=JSON.stringify(t,null,2);try{await Tt.writeFile(e,f,{encoding:"utf8",mode:420}),await Tt.rename(e,n),m("registry",`wrote entry ${t.id} → ${n}`,r)}catch(l){throw await Tt.unlink(e).catch(()=>{}),l}}async function QA(t,i=lr(),r){let n=ic(i,t);try{await Tt.unlink(n),m("registry",`removed entry ${t}`,r)}catch(e){if(e.code!=="ENOENT")throw e}}async function pA(t,i=lr(),r){let n=ic(i,t);try{let e=await Tt.readFile(n,"utf8"),f=JSON.parse(e);if(!w0(f))return m("registry",`entry ${t} failed validation, removing`,r),await Tt.unlink(n).catch(()=>{}),null;return f}catch(e){if(e.code==="ENOENT")return null;if(e instanceof SyntaxError)return m("registry",`entry ${t} has invalid JSON, removing`,r),await Tt.unlink(n).catch(()=>{}),null;throw e}}async function di(t=lr(),i){let r;try{r=await Tt.readdir(t)}catch(e){if(e.code==="ENOENT")return[];throw e}let n=[];for(let e of r){if(!e.endsWith(".json"))continue;let f=e.slice(0,-5);if(!tc(f))continue;let l=await pA(f,t,i);if(l)n.push(l)}return n}async function zr(t=lr(),i){let r=await di(t,i),n=0;for(let e of r){if(e.pid===void 0)continue;if(!qt(e.pid))m("registry",`GC: pid ${e.pid} for ${e.id} is dead, removing`,i),await QA(e.id,t,i).catch(()=>{}),n++}return n}function Se(t,i={}){let r=i.dir??lr(),n=i.debounceMs??100,e=i.pollMs??Math.max(n*2,250),f=i.verbose;Ce.mkdirSync(r,{recursive:!0});let l=null,c=!1,s=null,h=!1,u=(E)=>{return JSON.stringify(E.map((T)=>({id:T.id,from:T.from,to:T.to,path:T.path,pid:T.pid,pathRewrites:T.pathRewrites,cleanUrls:T.cleanUrls,changeOrigin:T.changeOrigin,static:T.static})).sort((T,d)=>T.id.localeCompare(d.id)))},$=()=>{if(l=null,c)return;di(r,f).then((E)=>{return s=u(E),t(E)}).catch((E)=>{m("registry",`watcher onChange failed: ${E}`,f)})},w=()=>{if(c)return;if(l)clearTimeout(l);l=setTimeout($,n)},A=setInterval(()=>{if(c||h)return;h=!0,di(r,f).then((E)=>{if(u(E)!==s)w()}).catch((E)=>{m("registry",`watcher poll failed: ${E}`,f)}).finally(()=>{h=!1})},e),a=Ce.watch(r,{persistent:!0},(E,T)=>{if(T&&/\.tmp\.\d+\.\d+$/.test(T))return;w()});return a.on("error",(E)=>{m("registry",`watcher error: ${E}`,f)}),w(),{close:()=>{if(c=!0,l)clearTimeout(l);clearInterval(A),a.close()}}}var vA=5000;function ot(){return kt.join(o0(),".stacks","rpx")}function Ue(t=ot()){return kt.join(t,"daemon.pid")}async function sr(t=ot()){try{let i=await yt.readFile(Ue(t),"utf8"),r=Number.parseInt(i.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function ZA(t=ot()){let i=await sr(t);return i!==null&&qt(i)}async function d0(t=ot()){await yt.mkdir(t,{recursive:!0});let i=Ue(t);while(!0){try{let n=await yt.open(i,"wx");try{await n.write(`${o.pid}
169
- `)}finally{await n.close()}return i}catch(n){if(n.code!=="EEXIST")throw n}let r=await sr(t);if(r!==null&&qt(r))throw Error(`rpx daemon already running (pid=${r})`);await yt.unlink(i).catch(()=>{})}}async function cr(t=ot()){await yt.unlink(Ue(t)).catch(()=>{})}function Y0(t){let i=t.cleanUrls??!1,r=Dl(t.path);if(t.static)return{static:l0(t.static,i),cleanUrls:i,basePath:r};let n=t.from??"localhost:1";return{sourceHost:new URL(n.startsWith("http")?n:`http://${n}`).host,cleanUrls:i,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites,basePath:r}}function t1(t){return t.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??t[0]??"rpx.localhost"}async function rc(t,i){let r=await di(i,t.verbose),n=[...new Set(r.map((s)=>s.to).filter(Boolean))],e=t1(n),f=[...new Set([e,...n,"rpx.localhost"])],l=Du(n,e,t.verbose);if(typeof t.https==="object"&&typeof l.https==="object")l.https={...l.https,...t.https};let c=await Gl(l);if(c&&!Wl(zl,f))m("daemon",`shared cert missing SANs for registry host(s), regenerating (${f.join(", ")})`,t.verbose),Ml(),c=null;if(!c)m("daemon","no usable cert on disk, generating one via tlsx",t.verbose),await Pu({...l,forceRegenerate:!0}),c=await Gl(l);if(!c)throw Error("failed to bootstrap TLS for rpx daemon");return c}async function i1(t,i,r,n){let e=o.env.SUDO_PASSWORD,f=o.env.HOME??o0(),l=[o.execPath,...o.argv.slice(1)],c=[`HOME=${f}`,`PATH=${o.env.PATH??""}`];if(n)c.push("RPX_VERBOSE=1");let s=e?["-S","-p","","env",...c,...l]:["-n","env",...c,...l];m("daemon",`elevating daemon via sudo for privileged ports ${i}/${r}`,n);let h=T0("sudo",s,{detached:!0,stdio:["pipe","ignore","ignore"]}),u=null,$=null;if(h.once("error",(A)=>{u=A}),h.once("exit",(A)=>{$=A??0}),e&&h.stdin)h.stdin.write(`${e}
170
- `),h.stdin.end();h.unref();let w=Ue(t),y=Date.now()+15000;while(Date.now()<y){if(u)throw u;let A=await sr(t);if(A!==null&&qt(A)){if(n)j.success(`rpx daemon elevated to root (pid=${A}, https on :${i})`);return{httpsPort:i,httpPort:r,pidPath:w,done:Promise.resolve(),stop:async()=>{try{o.kill(A,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if($!==null&&$!==0)throw Error(`rpx daemon could not elevate to bind :${i} (sudo exited ${$}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((a)=>setTimeout(a,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${t})`)}var a0=!1;function nc(){if(a0)return;a0=!0,o.on("uncaughtException",(t)=>{j.error(`rpx daemon: uncaught exception (continuing): ${t?.stack??t}`)}),o.on("unhandledRejection",(t)=>{j.error(`rpx daemon: unhandled rejection (continuing): ${t}`)})}function B0(t,i){let r;try{r=new URL(t.url)}catch{return new Response("Bad Request",{status:400})}let n=(t.headers.get("host")??r.hostname).split(":")[0];if(i&&r.pathname.startsWith("/.well-known/acme-challenge/")){let e=i.challengeStore.handlePath(r.pathname);if(e!==void 0)return new Response(e,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(i&&!i.hasCert(n))i.ensureCert(n).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${n}${r.pathname}${r.search}`}})}async function lB(t={}){nc();let i=t.verbose??!1,r=t.rpxDir??ot(),n=t.registryDir??kt.join(r,"registry.d"),e=t.httpsPort??443,f=t.httpPort??80,l=t.hostname??"0.0.0.0",c=t.gcIntervalMs??vA;if(o.env.RPX_DAEMON_WORKER==="1")return e1({rpxDir:o.env.RPX_WORKER_RPXDIR??r,registryDir:o.env.RPX_WORKER_REGISTRYDIR??n,httpsPort:Number.parseInt(o.env.RPX_WORKER_HTTPSPORT??"",10)||e,hostname:o.env.RPX_WORKER_HOSTNAME??l,verbose:o.env.RPX_WORKER_VERBOSE==="1"||i});let s=e>0&&e<1024||f>0&&f<1024,h=typeof o.getuid==="function"&&o.getuid()===0;if(o.platform!=="win32"&&s&&!h)return i1(r,e,f,i);let u=Math.max(1,t.workers??(Number.parseInt(o.env.RPX_WORKERS??"",10)||1));if(u>1)return f1(t,{rpxDir:r,registryDir:n,httpsPort:e,httpPort:f,hostname:l,verbose:i,gcIntervalMs:c,workers:u});let $=await d0(r),w=new Map,y=(R,H)=>Pl(w,R,H);function A(R){w=bl(R.map((Dt)=>({host:Dt.to,path:Dt.path,route:Y0(Dt)})));let H=Array.from(w.keys());m("daemon",`routing table now covers ${H.length} host(s): ${H.join(", ")||"<empty>"}`,i)}await zr(n,i).catch((R)=>{m("daemon",`initial gc failed: ${R}`,i)});let a=await di(n,i);A(a),await ur({rpxDir:r,verbose:i}).catch((R)=>{m("daemon",`DNS reconcile on start failed: ${R}`,i)}),await Or(a,{rpxDir:r,verbose:i,ownerPid:o.pid}).catch((R)=>{m("daemon",`DNS setup on start failed: ${R}`,i)});let E=[];if(t.productionCerts){if(E=await pl(t.productionCerts,i),i&&E.length>0)j.info(`SNI: serving ${E.length} real cert(s): ${E.map((R)=>R.serverName).join(", ")}`)}let T=xl(y,i),d=kl(i),Y=null;if(E.length===0)Y=await rc(t,n);let U=t.onDemandTls,B=U?.enabled?new Be({config:U,certsDir:U.certsDir??t.productionCerts?.certsDir??kt.join(r,"on-demand-certs"),initial:E,verbose:i,onCertAdded:(R)=>{$r(R)}}):null;function X(R){if(R.length>0)return R.map((H)=>({serverName:H.serverName,cert:H.cert,key:H.key}));return{key:Y.key,cert:Y.cert,ca:Y.ca,requestCert:!1,rejectUnauthorized:!1}}function V(R){return Bun.serve({port:e,hostname:l,reusePort:E0(),tls:X(R),fetch(H,Dt){return T(H,Dt)},websocket:d,error(H){return m("daemon",`https server error: ${H}`,i),new Response(`Server Error: ${H.message}`,{status:500})}})}let St=(R)=>[...new Set(R.map((H)=>H.to).filter(Boolean))],_t=(R)=>{if(!Y)return E;return Vu([...St(R),"rpx.localhost"],Y)},Bi=V(B?B.sniEntries():E.length>0?E:_t(a)),xt=null,Ni=!1;async function $r(R){if(F)return;if(xt=R,Ni)return;Ni=!0;try{while(!F&&xt){let H=xt;xt=null,m("daemon",`rebuilding :443 with ${H.length} SNI cert(s)`,i),Bi.stop(!1);let Dt,yc=!1;for(let wc=0;wc<20&&!F;wc++)try{Bi=V(H),yc=!0;break}catch(z0){Dt=z0,await new Promise((O0)=>setTimeout(O0,25))}if(!yc)j.error(`rpx: failed to rebuild :443 after issuing cert: ${Dt?.message}`)}}finally{Ni=!1}}let Vt=null;if(f>0)Vt=Bun.serve({port:f,hostname:l,fetch(R){return B0(R,B)},error(){return new Response("Bad Request",{status:400})}});if(i)j.success(`rpx daemon listening on https://${l}:${e}${Vt?` (http→https on :${f})`:""}`),j.info(`pid file: ${$}`),j.info(`registry: ${n}`);async function yr(R){if(F||E.length>0||B||!Y)return;try{Y=await rc(t,n),await $r(_t(R))}catch(H){m("daemon",`TLS sync on registry change failed: ${H}`,i)}}let Hr=Se((R)=>{A(R),yr(R),Or(R,{rpxDir:r,verbose:i,ownerPid:o.pid}).catch((H)=>{m("daemon",`DNS sync on registry change failed: ${H}`,i)})},{dir:n,verbose:i}),Wi=setInterval(()=>{zr(n,i).then((R)=>{if(R>0)m("daemon",`gc reaped ${R} stale entries`,i)}).catch((R)=>{m("daemon",`periodic gc failed: ${R}`,i)})},c);if(typeof Wi.unref==="function")Wi.unref();let F=!1,ui,wr=new Promise((R)=>{ui=R});async function ar(){if(F)return wr;if(F=!0,clearInterval(Wi),Hr.close(),Bi.stop(!1),Vt?.stop(!1),await hr({rpxDir:r,verbose:i}).catch((R)=>{m("daemon",`DNS teardown failed: ${R}`,i)}),await cr(r),i)j.info("rpx daemon stopped");return ui(),wr}let mr=(R)=>{m("daemon",`received ${R}, shutting down`,i),ar().catch(()=>{})};return o.once("SIGINT",mr),o.once("SIGTERM",mr),{stop:ar,done:wr,httpsPort:typeof Bi.port==="number"?Bi.port:e,httpPort:Vt&&typeof Vt.port==="number"?Vt.port:f,pidPath:$,ensureCert:(R)=>B?B.ensureCert(R):Promise.resolve(!1)}}function ec(t){return kt.join(t,"cluster-sni.json")}async function m0(t,i,r){let n=ec(t),e=`${n}.${o.pid}.tmp`;await yt.writeFile(e,JSON.stringify({sni:i,dev:r}),"utf8"),await yt.rename(e,n)}async function A0(t){try{return JSON.parse(await yt.readFile(ec(t),"utf8"))}catch{return{sni:[],dev:null}}}function r1(t){if(t.sni.length>0)return t.sni.map((i)=>({serverName:i.serverName,cert:i.cert,key:i.key}));if(t.dev)return{key:t.dev.key,cert:t.dev.cert,ca:t.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function n1(){let t=o.execPath,i=o.env.RPX_WORKER_BIN;if(i)return[t,i,"daemon:start"];let r=kt.basename(t).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&o.argv[1])return[t,o.argv[1],"daemon:start"];return[t,"daemon:start"]}async function e1(t){nc();let{rpxDir:i,registryDir:r,httpsPort:n,hostname:e,verbose:f}=t,l=new Map,c=(B,X)=>Pl(l,B,X),s=(B)=>{l=bl(B.map((X)=>({host:X.to,path:X.path,route:Y0(X)})))};s(await di(r,f));let h=xl(c,f),u=kl(f),$=!1,w=(B)=>Bun.serve({port:n,hostname:e,reusePort:!0,tls:r1(B),fetch(X,V){return h(X,V)},websocket:u,error(X){return m("daemon",`worker https error: ${X}`,f),new Response(`Server Error: ${X.message}`,{status:500})}}),y=w(await A0(i));async function A(){if($)return;let B=await A0(i),X=null;for(let St=0;St<20&&!$;St++)try{X=w(B);break}catch{await new Promise((_t)=>setTimeout(_t,25))}if(!X){m("daemon","worker reloadTls: could not bind new listener; keeping current",f);return}let V=y;y=X,V.stop(!1)}let a=Se((B)=>s(B),{dir:r,verbose:f}),E=()=>{A().catch(()=>{})};o.on("SIGHUP",E);let T,d=new Promise((B)=>{T=B});async function Y(){if($)return d;return $=!0,o.off("SIGHUP",E),a.close(),y.stop(!1),T(),d}let U=()=>{Y().then(()=>o.exit(0)).catch(()=>o.exit(0))};if(o.once("SIGTERM",U),o.once("SIGINT",U),f)j.success(`rpx worker (pid ${o.pid}) serving :${n}`);return{stop:Y,done:d,httpsPort:typeof y.port==="number"?y.port:n,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1)}}async function f1(t,i){nc();let{rpxDir:r,registryDir:n,httpsPort:e,httpPort:f,hostname:l,verbose:c,gcIntervalMs:s,workers:h}=i,u=await d0(r),$=[];if(t.productionCerts)$=await pl(t.productionCerts,c);let w=null;if($.length===0)w=await rc(t,n);let y=w?{key:w.key,cert:w.cert,ca:Array.isArray(w.ca)?w.ca.join(`
171
- `):w.ca}:null,A=!1,a=[];function E(F){for(let ui of a)try{ui.kill(F)}catch{}}async function T(F){await m0(r,F,y),E("SIGHUP")}let d=t.onDemandTls,Y=d?.enabled?new Be({config:d,certsDir:d.certsDir??t.productionCerts?.certsDir??kt.join(r,"on-demand-certs"),initial:$,verbose:c,onCertAdded:(F)=>{T(F)}}):null;await m0(r,Y?Y.sniEntries():$,y);let U=await di(n,c);await ur({rpxDir:r,verbose:c}).catch((F)=>{m("daemon",`DNS reconcile on start failed: ${F}`,c)}),await Or(U,{rpxDir:r,verbose:c,ownerPid:o.pid}).catch((F)=>{m("daemon",`DNS setup on start failed: ${F}`,c)}),await zr(n,c).catch(()=>{});let B=Se((F)=>{Or(F,{rpxDir:r,verbose:c,ownerPid:o.pid}).catch((ui)=>{m("daemon",`DNS sync on registry change failed: ${ui}`,c)})},{dir:n,verbose:c}),X=setInterval(()=>{zr(n,c).catch(()=>{})},s);X.unref?.();let V=null;if(f>0)V=Bun.serve({port:f,hostname:l,fetch(F){return B0(F,Y)},error(){return new Response("Bad Request",{status:400})}});let St=10,_t=60000,Bi=30000,xt=0,Ni=Date.now();function $r(){if(A)return;let F={...o.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:n,RPX_WORKER_HTTPSPORT:String(e),RPX_WORKER_HOSTNAME:l,RPX_WORKER_VERBOSE:c?"1":"0"},ui=Bun.spawn(n1(),{env:F,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(wr,ar){if(A)return;let mr=a.indexOf(wr);if(mr!==-1)a.splice(mr,1);let R=Date.now();if(R-Ni>_t)Ni=R,xt=0;if(xt++,xt>St){j.error(`rpx: worker keeps exiting (code ${ar}); giving up after ${St} restarts in ${Math.round(_t/1000)}s`);return}let H=Math.min(Bi,100*2**Math.min(xt,8));m("daemon",`worker exited (code ${ar}); respawning in ${H}ms (restart ${xt}/${St})`,c),setTimeout($r,H).unref?.()}});a.push(ui)}for(let F=0;F<h;F++)$r();if(c)j.success(`rpx coordinator listening on https://${l}:${e} via ${h} worker(s)${V?` (http→https on :${f})`:""}`),j.info(`pid file: ${u}`);let Vt,yr=new Promise((F)=>{Vt=F});async function Hr(){if(A)return yr;if(A=!0,clearInterval(X),B.close(),V?.stop(!1),E("SIGTERM"),await Promise.race([Promise.all(a.map((F)=>F.exited)),new Promise((F)=>setTimeout(F,3000))]),E("SIGKILL"),await hr({rpxDir:r,verbose:c}).catch((F)=>{m("daemon",`DNS teardown failed: ${F}`,c)}),await cr(r),await yt.unlink(ec(r)).catch(()=>{}),c)j.info("rpx coordinator stopped");return Vt(),yr}let Wi=(F)=>{m("daemon",`coordinator received ${F}, shutting down`,c),Hr().catch(()=>{})};return o.once("SIGINT",Wi),o.once("SIGTERM",Wi),{stop:Hr,done:yr,httpsPort:e,httpPort:f,pidPath:u,ensureCert:(F)=>Y?Y.ensureCert(F):Promise.resolve(!1)}}function l1(){let t=o.execPath,i=kt.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&o.argv[1])return[t,o.argv[1],"daemon:start"];return[t,"daemon:start"]}async function cB(t={}){let i=t.rpxDir??ot(),r=t.verbose??!1;await ur({rpxDir:i,verbose:r}).catch((u)=>{m("daemon",`DNS reconcile before ensureDaemonRunning: ${u}`,r)});let n=await sr(i);if(n!==null&&qt(n))return m("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)m("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await cr(i);await yt.mkdir(i,{recursive:!0});let e=t.spawnCommand??l1();if(e.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");m("daemon",`spawning daemon: ${e.join(" ")}`,r);let f=T0(e[0],e.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??o.cwd(),env:t.spawnEnv?{...o.env,...t.spawnEnv}:o.env});f.unref();let l=null;f.once("error",(u)=>{l=u});let c=t.startupTimeoutMs??5000,s=t.pollIntervalMs??50,h=Date.now()+c;while(Date.now()<h){if(l)throw l;let u=await sr(i);if(u!==null&&qt(u))return m("daemon",`daemon registered with pid=${u}`,r),{pid:u,spawned:!0};await new Promise(($)=>setTimeout($,s))}if(l)throw l;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${i})`)}async function sB(t={}){let i=t.rpxDir??ot(),r=t.verbose??!1,n=t.timeoutMs??5000,e=t.pollIntervalMs??50,f=t.forceAfterTimeout??!0,l=await sr(i);if(l===null||!qt(l)){if(l!==null)await cr(i);return await ur({rpxDir:i,verbose:r}).catch(()=>{}),{stopped:!1,pid:l,forced:!1}}try{o.kill(l,"SIGTERM")}catch(s){if(s.code==="ESRCH")return await cr(i),{stopped:!1,pid:l,forced:!1};throw s}let c=Date.now()+n;while(Date.now()<c){if(!qt(l))return m("daemon",`daemon pid=${l} stopped cleanly`,r),{stopped:!0,pid:l,forced:!1};await new Promise((s)=>setTimeout(s,e))}if(!f)throw Error(`rpx daemon (pid=${l}) did not exit within ${n}ms`);m("daemon",`daemon pid=${l} did not exit, escalating to SIGKILL`,r);try{o.kill(l,"SIGKILL")}catch(s){if(s.code!=="ESRCH")throw s}return await cr(i),await hr({rpxDir:i,verbose:r}).catch((s)=>{m("daemon",`DNS teardown after SIGKILL: ${s}`,r)}),{stopped:!0,pid:l,forced:!0}}async function hB(t={}){let i=t.rpxDir??ot();if(await ZA(i))return;await ur({rpxDir:i,verbose:t.verbose})}import*as Yi from"node:fs/promises";import{homedir as c1}from"node:os";import*as fc from"node:path";var Fe=1,s1="dns-state.json",C0=["com","test","dev","app","page","local","localhost","example","invalid"];function R0(){return fc.join(c1(),".stacks","rpx")}function lc(t=R0()){return fc.join(t,s1)}async function je(t=R0()){try{let i=await Yi.readFile(lc(t),"utf8"),r=JSON.parse(i);if(r.version!==Fe||!Array.isArray(r.resolvers))return null;return{version:Fe,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(i){if(i.code==="ENOENT")return null;throw i}}async function S0(t,i){await Yi.mkdir(t,{recursive:!0}),await Yi.writeFile(lc(t),`${JSON.stringify(i,null,2)}
172
- `,"utf8")}async function cc(t){await Yi.rm(lc(t),{force:!0})}function U0(t){let i=t.trim().toLowerCase().replace(/\.$/,"");if(!i||i.includes("127.0.0.1"))return null;if(i==="localhost"||i.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(i))return null;if(!/^[a-z0-9.-]+$/.test(i))return null;return i}function h1(t){let i=U0(t);if(!i)return null;let r=i.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function sc(t){let i=new Set;for(let r of t){let n=h1(r);if(n)i.add(n)}return Array.from(i).sort()}function hc(t){let i=new Set;for(let r of t){let n=U0(r);if(n)i.add(n)}return Array.from(i).sort()}var We=15353,u1="# managed-by: rpx",W0="/etc/resolver",dt=null,Ne=new Set;function X0(t){return{id:t.readUInt16BE(0),flags:t.readUInt16BE(2),qdcount:t.readUInt16BE(4),ancount:t.readUInt16BE(6),nscount:t.readUInt16BE(8),arcount:t.readUInt16BE(10)}}function g0(t,i,r=0){let n=[],e=i,f=0;while(!0){if(e>=t.length||++f>128)break;let l=t[e];if(l===0){e++;break}if((l&192)===192){if(e+1>=t.length||r>=10)break;let c=t.readUInt16BE(e)&16383,{name:s}=g0(t,c,r+1);if(s)n.push(s);e+=2;break}if(e++,e+l>t.length)break;n.push(t.subarray(e,e+l).toString("ascii")),e+=l}return{name:n.join("."),newOffset:e}}function $1(t,i){let{name:r,newOffset:n}=g0(t,i),e=t.readUInt16BE(n),f=t.readUInt16BE(n+2);return{question:{name:r,type:e,class:f},newOffset:n+4}}function Mr(t){let i=t.split("."),r=[];for(let n of i)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function y1(t,i,r){let n=[],e=Buffer.alloc(12);e.writeUInt16BE(t,0),e.writeUInt16BE(33152,2),e.writeUInt16BE(1,4),e.writeUInt16BE(1,6),e.writeUInt16BE(0,8),e.writeUInt16BE(0,10),n.push(e),n.push(Mr(i.name));let f=Buffer.alloc(4);f.writeUInt16BE(i.type,0),f.writeUInt16BE(i.class,2),n.push(f),n.push(Mr(i.name));let l=Buffer.alloc(10);if(l.writeUInt16BE(i.type,0),l.writeUInt16BE(1,2),l.writeUInt32BE(300,4),i.type===1){l.writeUInt16BE(4,8),n.push(l);let c=r.split(".").map((s)=>Number.parseInt(s,10));n.push(Buffer.from(c))}else if(i.type===28)l.writeUInt16BE(16,8),n.push(l),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return e.writeUInt16BE(33155,2),e.writeUInt16BE(0,6),Buffer.concat([e,Mr(i.name),f]);return Buffer.concat(n)}function w1(t,i){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(t,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(Mr(i.name));let e=Buffer.alloc(4);return e.writeUInt16BE(i.type,0),e.writeUInt16BE(i.class,2),r.push(e),Buffer.concat(r)}async function a1(t,i){if(hi.platform!=="darwin")return!1;let r=hc(t);if(r.length===0)return!1;if(dt){for(let n of r)Ne.add(n);return m("dns","DNS server already running — merged domains",i),!0}return Ne=new Set(r),new Promise((n)=>{dt=F0.createSocket("udp4"),dt.on("error",(e)=>{m("dns",`DNS server error: ${e.message}`,i),dt?.close(),dt=null,n(!1)}),dt.on("message",(e,f)=>{try{let l=X0(e),{question:c}=$1(e,12);m("dns",`Query for ${c.name} type ${c.type} from ${f.address}`,i);let s=c.name.toLowerCase(),h=!1;for(let $ of Ne)if(s===$||s.endsWith(`.${$}`)){h=!0;break}let u;if(h&&(c.type===1||c.type===28))u=y1(l.id,c,"127.0.0.1"),m("dns",`Responding with localhost for ${c.name}`,i);else u=w1(l.id,c),m("dns",`NXDOMAIN for ${c.name}`,i);dt?.send(u,f.port,f.address)}catch(l){m("dns",`Error processing DNS query: ${l}`,i)}}),dt.on("listening",()=>{let e=dt?.address();m("dns",`DNS server listening on ${e?.address}:${e?.port}`,i),n(!0)});try{dt.bind(We,"127.0.0.1")}catch(e){m("dns",`Failed to bind DNS server: ${e}`,i),n(!1)}})}function J0(t){if(dt)m("dns","Stopping DNS server",t),dt.close(),dt=null,Ne=new Set}function TB(){return dt!==null}async function m1(t,i=500){let r=t.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((n)=>{let e=F0.createSocket("udp4"),f=setTimeout(()=>{e.close(),n(!1)},i);e.on("message",(c)=>{clearTimeout(f),e.close();try{let s=X0(c);n(s.ancount>0)}catch{n(!1)}}),e.on("error",()=>{clearTimeout(f),e.close(),n(!1)});let l=A1(r,1);e.send(l,We,"127.0.0.1",(c)=>{if(c)clearTimeout(f),e.close(),n(!1)})})}function A1(t,i){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let n=Buffer.concat([Mr(t),Buffer.from([0,i,0,1])]);return Buffer.concat([r,n])}function E1(){return`${u1}
173
- nameserver 127.0.0.1
174
- port ${We}
175
- `}function Gr(t){return N0.join(W0,t)}function T1(t){return t.includes("127.0.0.1")&&t.includes(String(We))}async function o1(t){try{return await j0.readFile(Gr(t),"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}}async function uc(t){if(hi.platform!=="darwin")return;let{execSudoSync:i,getSudoPassword:r,isProcessElevated:n}=await import("./chunk-0f32jmrb.js");if(!n()&&!r()){m("dns","Cannot flush DNS cache without SUDO_PASSWORD",t);return}try{i("dscacheutil -flushcache"),i("killall -HUP mDNSResponder 2>/dev/null || true"),m("dns","DNS cache flushed",t)}catch(e){m("dns",`Could not flush DNS cache: ${e}`,t)}}function _0(t){if(!/^[a-z0-9.-]+$/.test(t))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(t)}`)}async function d1(t,i){_0(t);let{execSudoSync:r}=await import("./chunk-0f32jmrb.js"),n=E1().replace(/\n/g,"\\n"),e=`bash -c 'mkdir -p ${W0} && printf "%b" "${n}" > ${Gr(t)}'`;r(e),m("dns",`Created ${Gr(t)}`,i)}async function Y1(t,i){_0(t);let{execSudoSync:r}=await import("./chunk-0f32jmrb.js");r(`rm -f ${Gr(t)}`),m("dns",`Removed ${Gr(t)}`,i)}async function oB(t,i){return K0({domains:i??[],verbose:t})}async function B1(t,i){if(hi.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-0f32jmrb.js");if(!n()&&!r())return m("dns","SUDO_PASSWORD not set, cannot create resolver files",i),!1;try{for(let e of t)await d1(e,i);return await uc(i),!0}catch(e){return m("dns",`Failed to create resolver file: ${e}`,i),!1}}async function $c(t,i){if(hi.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-0f32jmrb.js");if(!n()&&!r())return;try{for(let e of t)await Y1(e,i);await uc(i)}catch(e){m("dns",`Failed to remove resolver files: ${e}`,i)}}async function I0(t){if(hi.platform!=="darwin")return[];let i=[];for(let r of C0){let n=await o1(r);if(n&&T1(n))await $c([r],t),i.push(r)}return i}async function K0(t){let i=t.rpxDir??ot(),r=hc(t.domains);if(r.length===0)return!1;let n=sc(r),e=await a1(r,t.verbose);if(!e){let c=r[0];if(c&&await m1(c))e=!0;else m("dns","Dev DNS server not available on 127.0.0.1:15353",t.verbose)}if(!e)return!1;if(!await B1(n,t.verbose))return!1;let l={version:Fe,resolvers:n,domains:r,ownerPid:t.ownerPid??hi.pid,updatedAt:new Date().toISOString()};return await S0(i,l),!0}async function Or(t,i={}){let r=t.map((s)=>s.to).filter(Boolean),n=i.rpxDir??ot(),e=sc(r),c=((await je(n))?.resolvers??[]).filter((s)=>!e.includes(s));if(c.length>0)await $c(c,i.verbose);if(e.length===0){J0(i.verbose),await cc(n);return}await K0({domains:r,rpxDir:n,verbose:i.verbose,ownerPid:i.ownerPid??hi.pid})}async function hr(t={}){let i=t.rpxDir??ot();J0(t.verbose);let n=(await je(i))?.resolvers??[];await $c(n,t.verbose),await I0(t.verbose),await cc(i)}async function dB(t){await hr({verbose:t})}async function ur(t={}){let i=t.rpxDir??ot(),r=await je(i),n=r?.ownerPid!=null&&qt(r.ownerPid);if(r&&!n){m("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,t.verbose),await hr(t);return}let e=await I0(t.verbose);if(e.length>0)m("dns",`reconcile: removed legacy TLD resolvers: ${e.join(", ")}`,t.verbose);await uc(t.verbose)}
176
- export{j as a,Ou as b,tA as c,Ui as d,Nl as e,Wl as f,iA as g,rA as h,Ei as i,Fi as j,Xl as k,gr as l,gl as m,Mu as n,Te as o,Jr as p,_r as q,Jl as r,zl as s,Vu as t,Du as u,Ol as v,YY as w,BY as x,CY as y,Pu as z,Ml as A,Gl as B,Hl as C,RY as D,Qu as E,l0 as F,IA as G,KA as H,zA as I,c0 as J,u0 as K,xl as L,kl as M,Ye as N,Vl as O,_Y as P,Dl as Q,HA as R,bl as S,LA as T,Pl as U,qA as V,pl as W,VA as X,y0 as Y,Be as Z,lr as _,tc as $,qt as aa,kY as ba,QA as ca,pA as da,di as ea,zr as fa,Se as ga,Fe as ha,C0 as ia,U0 as ja,h1 as ka,sc as la,hc as ma,We as na,u1 as oa,a1 as pa,J0 as qa,TB as ra,m1 as sa,Gr as ta,T1 as ua,oB as va,I0 as wa,K0 as xa,Or as ya,hr as za,dB as Aa,ur as Ba,ot as Ca,Ue as Da,sr as Ea,ZA as Fa,d0 as Ga,cr as Ha,lB as Ia,l1 as Ja,cB as Ka,sB as La,hB as Ma};