@stacksjs/rpx 0.11.23 → 0.11.24

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,224 +0,0 @@
1
- import{hb as g,kb as Or,lb as a,mb as cw,qb as uh,rb as Pc,tb as Nf,ub as yh,wb as Kh,xb as hh}from"./chunk-prvgnh82.js";import mw from"node:dgram";import*as Ew from"node:fs/promises";import*as Tw from"node:path";import*as ht from"node:process";import{spawn as $w}from"node:child_process";import*as Ai from"node:fs/promises";import{homedir as uw}from"node:os";import*as Di from"node:path";import*as Y from"node:process";var j={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as Qc}from"node:child_process";import P from"node:fs/promises";import*as oc from"node:os";import{homedir as Ar}from"node:os";import*as wh from"node:path";import{join as b}from"node:path";import*as qi from"node:process";import{createRequire as Xw}from"node:module";import{Resolver as Df}from"node:dns/promises";import{createHash as Iw,sign as _w}from"node:crypto";import{createHash as Kw}from"node:crypto";import{sign as zw}from"node:crypto";import{generateKeyPairSync as H$,X509Certificate as xw}from"node:crypto";import bf from"node:os";import Qf from"node:path";import{existsSync as O0,statSync as G0}from"fs";import{existsSync as Vw,mkdirSync as pE,readdirSync as iT,readFileSync as Dw,writeFileSync as tT}from"fs";import{homedir as dt}from"os";import{dirname as fT,resolve as Ni}from"path";import On from"process";import{existsSync as M0,statSync as H0}from"fs";import{existsSync as Tl,mkdirSync as bw,readdirSync as Qw,writeFileSync as ow}from"fs";import{homedir as gt}from"os";import{dirname as d0,resolve as ai}from"path";import Xt from"process";import{join as Pw,relative as vw,resolve as g0}from"path";import Tn from"process";import{existsSync as d$,mkdirSync as sT,readdirSync as aT,writeFileSync as mT}from"fs";import{homedir as of}from"os";import{dirname as YT,resolve as si}from"path";import jr from"process";import{join as Zw,relative as pw,resolve as q0}from"path";import Yn from"process";import{existsSync as g$,mkdirSync as ST,readdirSync as jT,writeFileSync as FT}from"fs";import{dirname as WT,resolve as Bn}from"path";import Yl from"process";import{Buffer as At}from"buffer";import{createCipheriv as ie,createDecipheriv as te,randomBytes as Pf}from"crypto";import{closeSync as vf,createReadStream as L0,createWriteStream as re,existsSync as Zf,fsyncSync as x0,openSync as k0,writeFileSync as ne}from"fs";import{access as fe,constants as V0,mkdir as le,readdir as or,rename as D0,stat as qt,unlink as Pr,writeFile as pf}from"fs/promises";import{join as Lt}from"path";import $i from"process";import{pipeline as ce}from"stream/promises";import{createGzip as b0}from"zlib";import xt from"process";import vi from"process";import{Buffer as Qi}from"buffer";import{createCipheriv as $e,createDecipheriv as ue,randomBytes as il}from"crypto";import{closeSync as tl,createReadStream as Q0,createWriteStream as ye,existsSync as vr,fsyncSync as o0,openSync as P0,writeFileSync as he}from"fs";import{access as we,constants as v0,mkdir as ee,readdir as Zr,rename as Z0,stat as kt,unlink as pr,writeFile as rl}from"fs/promises";import{isAbsolute as Ae,join as Vt,resolve as se}from"path";import M from"process";import{pipeline as ae}from"stream/promises";import{createGzip as p0}from"zlib";import Dt from"process";import Zi from"process";import tn from"process";import{existsSync as rn}from"fs";import{resolve as nl}from"path";import{existsSync as me}from"fs";import{existsSync as Ee,readdirSync as Te}from"fs";import{extname as fl,resolve as i$}from"path";import Ye from"process";import{join as Be,relative as Ce,resolve as t$}from"path";import Cn from"process";import{Buffer as oi}from"buffer";import{createCipheriv as Ue,createDecipheriv as Re,randomBytes as ll}from"crypto";import{closeSync as cl,createReadStream as r$,createWriteStream as Se,existsSync as nn,fsyncSync as n$,openSync as f$,writeFileSync as je}from"fs";import{access as Fe,constants as l$,mkdir as Ne,readdir as fn,rename as c$,stat as bt,unlink as ln,writeFile as $l}from"fs/promises";import{isAbsolute as We,join as Qt,resolve as Xe}from"path";import H from"process";import{pipeline as Je}from"stream/promises";import{createGzip as $$}from"zlib";import ot from"process";import pi from"process";import cn from"process";import{existsSync as $n}from"fs";import{resolve as ul}from"path";import{existsSync as Ie}from"fs";import{exec as p1}from"node:child_process";import Jl from"node:fs";import iA from"node:os";import zi from"node:path";import Uu from"node:process";import{promisify as tA}from"node:util";import pt from"node:crypto";import it from"node:fs";import Kl from"node:path";import SA from"node:crypto";import jA from"node:fs";import FA from"node:tls";import{execSync as XA}from"node:child_process";import Kn from"node:os";var Jw=Xw(import.meta.url);async function j$(i,t,r={}){let n=r.timeoutMs??120000,f=r.intervalMs??3000,l=i.split(".").slice(-2).join("."),c;try{let y=new Df,h=await y.resolveNs(l),w=(await Promise.all(h.map((e)=>y.resolve4(e).catch(()=>[])))).flat();if(w.length>0)c=new Df,c.setServers(w)}catch{}let u=Date.now()+n,$=c??new Df;for(;;){try{if((await $.resolveTxt(i)).some((y)=>y.join("")===t))return!0}catch{}if(Date.now()>=u)return!1;await new Promise((y)=>setTimeout(y,f))}}class Sr{tokens=new Map;add(i,t){this.tokens.set(i,t)}get(i){return this.tokens.get(i)}remove(i){this.tokens.delete(i)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(i){let t=i.indexOf(Sr.PATH_PREFIX);if(t===-1)return;let r=i.slice(t+Sr.PATH_PREFIX.length);return this.get(r)}}var zn=new Sr;function hn(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function sl(i){return Buffer.from(i,"base64url")}function F$(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function N$(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return Iw("sha256").update(t).digest("base64url")}function W$(i){let{protectedHeader:t,payload:r,privateKey:n}=i,f=hn(JSON.stringify(t)),l=r===""?"":hn(JSON.stringify(r)),c=`${f}.${l}`,u=_w("sha256",Buffer.from(c),{key:n,dsaEncoding:"ieee-p1363"});return{protected:f,payload:l,signature:hn(u)}}var X$="https://acme-staging-v02.api.letsencrypt.org/directory",J$="https://acme-v02.api.letsencrypt.org/directory";class mn extends Error{problem;httpStatus;constructor(i,t,r){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=r}}class En{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=F$(i.accountPublicKey),this.thumbprint=N$(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await fetch(this.directoryUrl);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await fetch(i.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:r,useJwk:n}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(n)f.jwk=this.jwk;else f.kid=this.requireKid();let l=W$({protectedHeader:f,payload:r,privateKey:this.accountKey}),c=await fetch(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(l)}),u=c.headers.get("replay-nonce");if(u)this.nonce=u;let $=c.headers.get("content-type")??"",y;if($.includes("application/pem-certificate-chain")||$.startsWith("text/"))y=await c.text();else{let h=await c.text();y=h?JSON.parse(h):{}}if(c.status>=400){let h=y??{};throw new mn(`ACME request to ${t} failed (HTTP ${c.status}): ${h.type??""} ${h.detail??""}`.trim(),h,c.status)}return{status:c.status,headers:c.headers,body:y,location:c.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),r={termsOfServiceAgreed:!0};if(i.email)r.contact=[`mailto:${i.email}`];let n=await this.signedPost({url:t.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(i){let t=await this.directory(),r={identifiers:i.map((f)=>({type:"dns",value:f}))},n=await this.signedPost({url:t.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(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return Kw("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;while(Date.now()<f){let l=await this.getAuthorization(i);if(l.status==="valid")return;if(l.status==="invalid"){let c=l.challenges.find((u)=>u.status==="invalid");throw new mn(`Authorization for ${l.identifier.value} became invalid: ${c?.error?.detail??"unknown reason"}`,c?.error??{},0)}await z0(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let r=t.timeoutMs??60000,n=t.intervalMs??2000,f=Date.now()+r;while(Date.now()<f){let l=await this.getOrder(i);if(l.status==="valid"){if(!l.certificate)throw Error("ACME order is valid but has no certificate URL");return l.certificate}if(l.status==="invalid")throw Error(`ACME order ${i} became invalid`);await z0(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let r=i.challenges.find((n)=>n.type===t);if(!r)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return r}}function I$(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${i.trim()}
2
- `,chainPem:""};let n=`${r.trim()}
3
- `,f=t.slice(1).map((l)=>l.trim()).join(`
4
- `);return{certPem:n,chainPem:f?`${f}
5
- `:""}}function _$(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function z0(i){return new Promise((t)=>setTimeout(t,i))}function Ow(i){if(i<128)return Buffer.from([i]);let t=[],r=i;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function mt(i,t){return Buffer.concat([Buffer.from([i]),Ow(t.length),t])}function K$(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let r=[],n=i;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return mt(2,t)}function Wt(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let r=[40*t[0]+t[1]];for(let n=2;n<t.length;n++){let f=t[n],l=[f&127];f=Math.floor(f/128);while(f>0)l.unshift(f&127|128),f=Math.floor(f/128);r.push(...l)}return mt(6,Buffer.from(r))}function Fi(...i){return mt(48,Buffer.concat(i))}function al(...i){return mt(49,Buffer.concat(i))}function ml(i){return mt(3,Buffer.concat([Buffer.from([0]),i]))}function z$(i){return mt(4,i)}function O$(i){return mt(12,Buffer.from(i,"utf8"))}function El(i,t,r){let n=128|(r?32:0)|i;return mt(n,t)}var Gw="1.2.840.10045.2.1",Mw="1.2.840.10045.3.1.7",Hw="1.2.840.10045.4.3.2",dw="2.5.4.3",gw="1.2.840.113549.1.9.14",qw="2.5.29.17";function Lw(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=sl(t.x),n=sl(t.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 G$(i){let{domains:t,publicKey:r,privateKey:n}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=Fi(al(Fi(Wt(dw),O$(t[0])))),l=Fi(Fi(Wt(Gw),Wt(Mw)),ml(Lw(r))),c=t.map((s)=>El(2,Buffer.from(s,"ascii"),!1)),u=Fi(...c),$=Fi(Wt(qw),z$(u)),y=Fi($),h=Fi(Wt(gw),al(y)),w=El(0,h,!0),e=Fi(K$(0),f,l,w),A=zw("sha256",e,n),m=Fi(Wt(Hw));return Fi(e,m,ml(A))}function M$(i){return G$(i).toString("base64url")}function kw(i){if(i){let{createPrivateKey:f,createPublicKey:l}=Jw("node:crypto"),c=f(i),u=l(c);return{privateKey:c,publicKey:u,pem:i}}let{privateKey:t,publicKey:r}=H$("ec",{namedCurve:"P-256"}),n=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:n}}async function zl(i){let{domains:t,method:r}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((w)=>w.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=i.directoryUrl??(i.staging===!1?J$:X$),f=kw(i.accountKeyPem),l=new En({directoryUrl:n,accountKey:f.privateKey,accountPublicKey:f.publicKey});await l.newAccount({email:i.email});let{order:c,orderUrl:u}=await l.newOrder(t),$=i.http01Store??zn,y=[],h=[];try{for(let R of c.authorizations){let W=await l.getAuthorization(R);if(W.status==="valid")continue;let k=En.selectChallenge(W,r);if(r==="dns-01"){let fi=_$(W.identifier.value),ki=l.dns01TxtValue(k.token);await i.dnsProvider.setTxt(fi,ki),y.push({name:fi,value:ki}),await j$(fi,ki,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else $.add(k.token,l.keyAuthorization(k.token)),h.push(k.token);await l.notifyChallengeReady(k.url),await l.pollAuthorization(R,{timeoutMs:i.timeoutMs})}let{privateKey:w,publicKey:e}=H$("ec",{namedCurve:"P-256"}),A=M$({domains:t,publicKey:e,privateKey:w});await l.finalizeOrder(c.finalize,A);let m=await l.pollOrder(u,{timeoutMs:i.timeoutMs}),s=await l.downloadCertificate(m),{certPem:E,chainPem:T}=I$(s),B=T?`${E}${T}`:E,F=w.export({format:"pem",type:"pkcs8"}).toString(),N=new Date(new xw(E).validTo);return{certPem:E,keyPem:F,chainPem:T,fullChainPem:B,accountKeyPem:f.pem,notAfter:N}}finally{for(let{name:w,value:e}of y)await i.dnsProvider?.removeTxt(w,e).catch(()=>{});for(let w of h)$.remove(w)}}class q${cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),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(i,t){try{if(!O0(i))return!0;return G0(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=O0(r)?G0(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class L${metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var Un=new q$,Ol=new L$,_e=Object.defineProperty,Ke=(i)=>i;function ze(i,t){this[i]=Ke.bind(null,t)}var Oe=(i,t)=>{for(var r in t)_e(i,r,{get:t[r],enumerable:!0,configurable:!0,set:ze.bind(t,r)})},Ge=(i,t)=>()=>(i&&(t=i(i=0)),t),x$={};Oe(x$,{withErrorRecovery:()=>D$,tryLoadConfig:()=>l1,loadConfigWithResult:()=>n1,loadConfig:()=>v$,isRetryableError:()=>ve,isConfigNotFoundError:()=>Pe,isBunfigError:()=>b$,globalPerformanceMonitor:()=>Xr,globalCache:()=>vt,getEnvOrDefault:()=>Ze,generateConfigTypes:()=>c1,defaultGeneratedDir:()=>lu,defaultConfigDir:()=>fu,deepMergeWithArrayStrategy:()=>gl,deepMerge:()=>Q$,createLibraryConfig:()=>$1,config:()=>f1,bunfigPlugin:()=>u1,applyEnvVarsToConfig:()=>Ur,TypeGenerationError:()=>Fl,SchemaValidationError:()=>Nr,PluginError:()=>Wl,PerformanceMonitor:()=>Ml,FileSystemError:()=>jl,ErrorFactory:()=>at,EnvVarError:()=>Wn,EnvProcessor:()=>Gn,ConfigValidator:()=>ql,ConfigValidationError:()=>Rl,ConfigNotFoundError:()=>Nn,ConfigMergeError:()=>Sl,ConfigLoader:()=>Ll,ConfigLoadError:()=>Fr,ConfigFileLoader:()=>Mn,ConfigCache:()=>Gl,CacheUtils:()=>p$,BunfigError:()=>Ui,BrowserConfigError:()=>Nl,ArrayMergeStrategies:()=>ru});class Gl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),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(i,t){try{if(!M0(i))return!0;return H0(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=M0(r)?H0(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Ml{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function Me(i,t={}){let r=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return r?`${i}:${r}`:i}function He(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function de(i){return i.getStats().size*2}function Hl(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let n=[...t];for(let f of i)if(V(f)&&"name"in f){if(!n.find((l)=>V(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(V(f)&&"path"in f){if(!n.find((l)=>V(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((l)=>Rn(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!V(t)||!V(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(V(f)&&V(r[n]))r[n]=Hl(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&V(f[0])&&V(r[n][0])){let l=[...f];for(let c of r[n])if(V(c)&&"name"in c){if(!l.find((u)=>V(u)&&("name"in u)&&u.name===c.name))l.push(c)}else if(V(c)&&"path"in c){if(!l.find((u)=>V(u)&&("path"in u)&&u.path===c.path))l.push(c)}else if(!l.some((u)=>Rn(u,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function Rn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Rn(i[r],t[r]))return!1;return!0}if(V(i)&&V(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Rn(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function ge(i,t){if(!g$(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Hl(t,n)}catch{return null}}catch{return null}}async function qe({name:i="",cwd:t,defaultConfig:r}){let n=t||Yl.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],l=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of l)for(let u of f){let $=Bn(n,`${c}${u}`),y=await ge($,r);if(y!==null)return y}try{let c=Bn(n,"package.json");if(g$(c)){let u=(await import(c))[i];if(u&&typeof u==="object"&&!Array.isArray(u))try{return Hl(r,u)}catch{}}}catch{}return r}function Le(i,t={}){let r=Yn.cwd();while(r.includes("storage"))r=q0(r,"..");let n=q0(r,i||"");if(t?.relative)return pw(Yn.cwd(),n);return n}async function xe(){try{let i=await qe({name:"clarity",defaultConfig:en,cwd:Yn.cwd(),endpoint:"",headers:{}});return{...en,...i}}catch{return en}}function Q(){if(vi.env.NODE_ENV==="test"||vi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ke(){if(vi.env.NODE_ENV==="test"||vi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vi<"u"){let i=vi.type;if(i==="renderer"||i==="worker")return!1;return!!(vi.versions&&(vi.versions.node||vi.versions.bun))}return!1}class k${async format(i){let t=await ke(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:xt.pid,hostname:t(),environment:xt.env.NODE_ENV||"development",platform:xt.platform,version:xt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:xt.env.NODE_ENV||xt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Sn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Cl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new k$,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??$i.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.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 f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...An,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...An};return{...An,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Cl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let t=(async()=>{let n,f=0,l=3,c=1000;while(f<l)try{try{try{await fe(this.config.logDirectory,V0.F_OK|V0.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await le(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let u=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:At.from(i);try{if(!Zf(this.currentLogFile))await pf(this.currentLogFile,"",{mode:420});if(n=k0(this.currentLogFile,"a",420),ne(n,u,{flag:"a"}),x0(n),n!==void 0)vf(n),n=void 0;if((await qt(this.currentLogFile)).size===0){if(await pf(this.currentLogFile,u,{flag:"w",mode:420}),(await qt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let y=$;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(f<l-1){let h=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,h);let w=c*2**f;await new Promise((e)=>setTimeout(e,w)),f++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(n!==void 0)try{vf(n)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(u){if(f===l-1){let y=u,h=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),u}f++;let $=c*2**(f-1);await new Promise((y)=>setTimeout(y,$))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}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 Lt(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 Lt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Lt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(Q())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,r=Math.max(t,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 i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,u])=>u.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(n.length>l)for(let[c]of n.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Pf(16).toString("hex")}generateKey(){return Pf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=Pf(16),n=ie("aes-256-gcm",t,r),f=At.concat([n.update(i,"utf8"),n.final()]),l=n.getAuthTag();return{encrypted:At.concat([r,f,l]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=b0(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(At.from(At.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(Q())return;let i=await qt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await or(this.config.logDirectory),l=f.filter(($)=>$.startsWith(this.name)&&/\.log\.\d+$/.test($)).sort(($,y)=>{let h=Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,u=`${r}.${c}`;if(await qt(r).catch(()=>null))try{if(await D0(r,u),t.compress)try{let $=`${u}.gz`;await this.compressLogFile(u,$),await Pr(u)}catch($){console.error("Error compressing rotated file:",$)}if(l.length===0&&!f.some(($)=>$.endsWith(".log.1")))try{let $=`${r}.1`;await pf($,"")}catch($){console.error("Error creating backup file:",$)}}catch($){console.error(`Error during rotation: ${$ instanceof Error?$.message:String($)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await qt(r).catch(()=>null))await D0(r,l)}if(this.currentLogFile=n,t.maxFiles){let f=(await or(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await Pr(Lt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=L0(i),n=re(t),f=b0();await ce(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!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(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Zf(this.currentLogFile))try{let i=k0(this.currentLogFile,"r+");x0(i),vf(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!Q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await or(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await Pr(Lt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?L.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,u=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let $=$i.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${L.cyan(f)}`;if(!c)return y.trim();let h=u(y).trim().length,w=u(t).length,e=Math.max(1,$-2-h-w);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let u=Number.parseInt(c,10);return u<t[0].length?String(t[0][u]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let u=t[n++];switch(c){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 l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,u;if(t instanceof Error)c=t.message,u=t.stack;else c=this.formatMessage(t,r);if(this.fancy&&!Q()){let y=iu[i],h=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",w;switch(i){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:L.gray(c),level:i}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.error(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:L.green(c),level:i}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.error(w),u){let e=u.split(`
6
- `);for(let A of e)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:L.gray(` ${A}`),level:i,showTimestamp:!1}))}break}}else if(!Q()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),u)console.error(u)}if(!this.shouldLog(i))return;let $=`${l} ${this.environment}.${i.toUpperCase()}: ${c}
7
- `;if(u)$+=`${u}
8
- `;$=$.replace(this.ANSI_PATTERN,""),await this.writeToFile($)}time(i){let t=performance.now();if(this.fancy&&!Q()){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(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,u=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)$+=` ${JSON.stringify(r)}`;if($+=`
9
- `,$=$.replace(this.ANSI_PATTERN,""),this.fancy&&!Q()){let y=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:u,icon:L.green("✓"),tag:y,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Q())console.error($.trim());await this.writeToFile($)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new Sn(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Q())throw Error("createReadStream is not supported in browser environments");if(!Zf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return L0(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=At.isBuffer(i)?i:At.from(i,"base64"),f=n.slice(0,16),l=n.slice(-16),c=n.slice(16,-16),u=te("aes-256-gcm",r,f);return u.setAuthTag(l),At.concat([u.update(c),u.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 Q()}isServerMode(){return!Q()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!Q()){let l=i.split(`
10
- `),c=Math.max(...l.map((h)=>h.length))+2,u=`┌${"─".repeat(c)}┐`,$=`└${"─".repeat(c)}┘`,y=l.map((h)=>{let w=" ".repeat(c-h.length-2);return`│ ${h}${w} │`});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(u)})),y.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:L.cyan($),showTimestamp:!1}))}else if(!Q())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let f=`${n} ${this.environment}.INFO: [BOX] ${i}
11
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(Q())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${L.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();$i.stdin.removeListener("data",r);try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!1)}catch{}$i.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!0)}catch{}$i.stdin.resume(),$i.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let f=/%([sdijfo%])/g,l=0;if(r=i.replace(f,(c,u)=>{if(u==="%")return"%";if(l>=t.length)return c;let $=t[l++];switch(u){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return c}}),l<t.length)r+=` ${t.slice(l).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!Q()){let f=this.options.showTags!==!1&&this.name?L.gray(this.formatTag(this.name)):"",l=L.blue("◐");console.error(`${l} ${f} ${L.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
12
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(i,t=""){if(!this.enabled||!this.fancy||Q()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,n)),f!==void 0)this.activeProgressBar.message=f;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())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,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;$i.stdout.write(`${"\r".padEnd($i.stdout.columns||80)}\r`),this.log(f,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||Q()||!$i.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=L.green("━".repeat(n)),c=L.gray("━".repeat(f)),u=`[${l}${c}]`,$=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=t||r===100?L.green("✓"):L.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${L.gray(this.formatTag(this.name))}`:"",e=`\r${h}${w} ${u} ${$}${y}`,A=$i.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,$i.stdout.write(i.lastRenderedLine),t)$i.stdout.write(`
13
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||Q()||!$i.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(Q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await or(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Lt(this.config.logDirectory,n);if(i.before)try{if((await qt(f)).mtime>=i.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 Pr(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function wn(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&d(t[0])&&"id"in t[0]&&t[0].id===3&&d(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(d(t)&&d(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(d(i)&&"arr"in i&&Array.isArray(i.arr)&&d(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&d(t[0])&&d(i[0])){let n=[...t];for(let f of i)if(d(f)&&"name"in f){if(!n.find((l)=>d(l)&&("name"in l)&&l.name===f.name))n.push(f)}else if(d(f)&&"path"in f){if(!n.find((l)=>d(l)&&("path"in l)&&l.path===f.path))n.push(f)}else if(!n.some((l)=>jn(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!d(t)||!d(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(d(f)&&d(r[n]))r[n]=wn(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&d(f[0])&&d(r[n][0])){let l=[...f];for(let c of r[n])if(d(c)&&"name"in c){if(!l.find((u)=>d(u)&&("name"in u)&&u.name===c.name))l.push(c)}else if(d(c)&&"path"in c){if(!l.find((u)=>d(u)&&("path"in u)&&u.path===c.path))l.push(c)}else if(!l.some((u)=>jn(u,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function dl(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:wn(i,t);if(Array.isArray(i))return r==="replace"?t:wn(i,t);if(!d(t)||!d(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let l=t[f],c=n[f];if(l===null||l===void 0)continue;if(Array.isArray(l)||Array.isArray(c))if(r==="replace")n[f]=l;else n[f]=wn(c,l);else if(d(l)&&d(c))n[f]=dl(c,l,r);else n[f]=l}return n}function jn(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!jn(i[r],t[r]))return!1;return!0}if(d(i)&&d(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!jn(i[f],t[f]))return!1}return!0}return!1}function d(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function un(i,t,r="replace"){if(!d$(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return dl(t,f,r)}catch{return null}}catch{return null}}function Ve(i,t,r=!1){if(!i)return t;let n=i.toUpperCase().replace(/-/g,"_"),f={...t};function l(c,u=[]){let $={...c};for(let[y,h]of Object.entries(c)){let w=[...u,y],e=(s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase(),A=`${n}_${w.map(e).join("_")}`,m=`${n}_${w.map((s)=>s.toUpperCase()).join("_")}`;if(r)yi.info(`Checking environment variable ${A} for config ${i}.${w.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))$[y]=l(h,w);else{let s=jr.env[A]||jr.env[m];if(s!==void 0){if(r)yi.info(`Using environment variable ${s?A:m} for config ${i}.${w.join(".")}`);if(typeof h==="number")$[y]=Number(s);else if(typeof h==="boolean")$[y]=s.toLowerCase()==="true";else if(Array.isArray(h))try{let E=JSON.parse(s);if(Array.isArray(E))$[y]=E;else $[y]=s.split(",").map((T)=>T.trim())}catch{$[y]=s.split(",").map((E)=>E.trim())}else $[y]=s}}}return $}return l(f)}async function De({name:i="",alias:t,cwd:r,configDir:n,defaultConfig:f,verbose:l=!1,checkEnv:c=!0,arrayStrategy:u="replace"}){let $=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?Ve(i,f,l):f,y=r||jr.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(l)yi.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${y}`);let w=[i,`.${i}`].filter(Boolean),e=[`${i}.config`,`.${i}.config`].filter(Boolean),A=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],s=Array.from(new Set([y,si(y,"config"),si(y,".config"),n?si(y,n):void 0].filter(Boolean)));for(let E of s){if(l)yi.info(`Searching for configuration in: ${E}`);let T=[si(y,"config"),si(y,".config")].concat(n?[si(y,n)]:[]).includes(E)?[...w,...e,...A,...m]:[...e,...w,...m,...A];for(let B of T)for(let F of h){let N=si(E,`${B}${F}`),R=await un(N,$,u);if(R!==null){if(l)yi.success(`Configuration loaded from: ${N}`);return R}}}if(i){let E=si(of(),".config",i),T=["config",`${i}.config`];if(t)T.push(`${t}.config`);if(l)yi.info(`Checking user config directory: ${E}`);for(let B of T)for(let F of h){let N=si(E,`${B}${F}`),R=await un(N,$,u);if(R!==null){if(l)yi.success(`Configuration loaded from user config directory: ${N}`);return R}}}if(i){let E=si(of(),".config"),T=[`.${i}.config`];if(t)T.push(`.${t}.config`);if(l)yi.info(`Checking user config directory for dotfile configs: ${E}`);for(let B of T)for(let F of h){let N=si(E,`${B}${F}`),R=await un(N,$,u);if(R!==null){if(l)yi.success(`Configuration loaded from user config directory dotfile: ${N}`);return R}}}if(i){let E=of(),T=[`.${i}.config`,`.${i}`];if(t)T.push(`.${t}.config`),T.push(`.${t}`);if(l)yi.info(`Checking user home directory for dotfile configs: ${E}`);for(let B of T)for(let F of h){let N=si(E,`${B}${F}`),R=await un(N,$,u);if(R!==null){if(l)yi.success(`Configuration loaded from user home directory: ${N}`);return R}}}try{let E=si(y,"package.json");if(d$(E)){let T=await import(E),B=T[i];if(!B&&t){if(B=T[t],B&&l)yi.success(`Using alias "${t}" configuration from package.json`)}if(B&&typeof B==="object"&&!Array.isArray(B))try{if(l)yi.success(`Configuration loaded from package.json: ${B===T[i]?i:t}`);return dl($,B,u)}catch(F){if(l)yi.warn("Failed to merge package.json config:",F)}}}catch(E){if(l)yi.warn("Failed to load package.json:",E)}if(l)yi.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return $}function be(i,t={}){let r=Tn.cwd();while(r.includes("storage"))r=g0(r,"..");let n=g0(r,i||"");if(t?.relative)return vw(Tn.cwd(),n);return n}async function Qe(){try{let i=await De({name:"clarity",alias:"logging",defaultConfig:sn,cwd:Tn.cwd()});return{...sn,...i||{}}}catch{return sn}}function Z(){if(Zi.env.NODE_ENV==="test"||Zi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function oe(){if(Zi.env.NODE_ENV==="test"||Zi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Zi<"u"){let i=Zi.type;if(i==="renderer"||i==="worker")return!1;return!!(Zi.versions&&(Zi.versions.node||Zi.versions.bun))}return!1}class V${async format(i){let t=await oe(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Fn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Ul},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new V$,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??M.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.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 f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...an,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...an};return{...an,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Ul.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!Z()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,l=3,c=1000;while(f<l)try{try{try{await we(this.config.logDirectory,v0.F_OK|v0.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await ee(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let u=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Qi.from(i);try{if(!vr(this.currentLogFile))await rl(this.currentLogFile,"",{mode:420});if(n=P0(this.currentLogFile,"a",420),he(n,u,{flag:"a"}),o0(n),n!==void 0)tl(n),n=void 0;if((await kt(this.currentLogFile)).size===0){if(await rl(this.currentLogFile,u,{flag:"w",mode:420}),(await kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let y=$;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(f<l-1){let h=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,h);let w=c*2**f;await new Promise((e)=>setTimeout(e,w)),f++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(n!==void 0)try{tl(n)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(u){if(f===l-1){let y=u,h=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),u}f++;let $=c*2**(f-1);await new Promise((y)=>setTimeout(y,$))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}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 Vt(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 Vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(Z())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,r=Math.max(t,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 i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,u])=>u.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(n.length>l)for(let[c]of n.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return il(16).toString("hex")}generateKey(){return il(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=il(16),n=$e("aes-256-gcm",t,r),f=Qi.isBuffer(i)?i:Qi.from(i,"utf8"),l=n.update(f),c=n.final(),u=l.length+c.length,$=n.getAuthTag(),y=Qi.allocUnsafe(16+u+16);return r.copy(y,0),l.copy(y,16),c.copy(y,16+l.length),$.copy(y,16+u),{encrypted:y,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=p0(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(Qi.from(Qi.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(Z())return;if(!this.shouldWriteToFile())return;let i=await kt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Zr(this.config.logDirectory),l=f.filter(($)=>$.startsWith(this.name)&&/\.log\.\d+$/.test($)).sort(($,y)=>{let h=Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,u=`${r}.${c}`;if(await kt(r).catch(()=>null))try{if(await Z0(r,u),t.compress)try{let $=`${u}.gz`;await this.compressLogFile(u,$),await pr(u)}catch($){console.error("Error compressing rotated file:",$)}if(l.length===0&&!f.some(($)=>$.endsWith(".log.1")))try{let $=`${r}.1`;await rl($,"")}catch($){console.error("Error creating backup file:",$)}}catch($){console.error(`Error during rotation: ${$ instanceof Error?$.message:String($)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await kt(r).catch(()=>null))await Z0(r,l)}if(this.currentLogFile=n,t.maxFiles){let f=(await Zr(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await pr(Vt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=Q0(i),n=ye(t),f=p0();await ae(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!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(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),vr(this.currentLogFile))try{let i=P0(this.currentLogFile,"r+");o0(i),tl(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!Z()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Zr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await pr(Vt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?K.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Z())return!1;let i=typeof M.env.NO_COLOR<"u",t=M.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof M.stderr<"u"&&M.stderr.isTTY||typeof M.stdout<"u"&&M.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,u=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let $=M.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${K.cyan(f)}`;if(!c)return y.trim();let h=u(y).trim().length,w=u(t).length,e=Math.max(1,$-2-h-w);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let u=Number.parseInt(c,10);return u<t[0].length?String(t[0][u]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let u=t[n++];switch(c){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 l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=K.underline(K.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let u=`file://${encodeURI(c)}`,$="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${u}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>K.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>K.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>K.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>K.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>K.strikethrough(n)),t}supportsHyperlinks(){if(Z())return!1;let i=M.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=M.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Ae(t)||t.startsWith("./")||t.startsWith("../"))t=se(t);else return null;return vr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,u;if(t instanceof Error)c=t.message,u=t.stack;else c=this.formatMessage(t,r);let{consoleText:$,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":tu[i],e=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:K.gray($),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:K.green($),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.error(A),u){let m=u.split(`
14
- `);for(let s of m)if(s.trim()&&!s.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:K.gray(` ${s}`),level:i,showTimestamp:!1}))}break}}else if(!Z()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),u)console.error(u)}if(!this.shouldLog(i))return;let h=`${l} ${this.environment}.${i.toUpperCase()}: ${y}
15
- `;if(u)h+=`${u}
16
- `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(f,l)=>{},finish:(f)=>{},interrupt:(f,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Z()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!Z()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,l="info")=>{if(!Z()&&M.stdout.isTTY)M.stdout.write(`
17
- `);if(this[l==="warning"?"warn":l](f),this.activeProgressBar&&this.shouldStyleConsole()&&!Z()&&M.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:r,message:`${K.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,u=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)$+=` ${JSON.stringify(r)}`;if($+=`
18
- `,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:u,icon:this.options.showIcons===!1?"":K.green("✓"),tag:y,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Z())console.error($.trim());if(this.shouldWriteToFile())await this.writeToFile($)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new Fn(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Z())throw Error("createReadStream is not supported in browser environments");if(!vr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Q0(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Qi.isBuffer(i)?i:Qi.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),u=ue("aes-256-gcm",r,f);u.setAuthTag(l);let $=u.update(c),y=u.final(),h=$.length+y.length,w=Qi.allocUnsafe(h);return $.copy(w,0),y.copy(w,$.length),w.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 Z()}isServerMode(){return!Z()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let u=f.split(`
19
- `),$=Math.max(...u.map((e)=>e.length))+2,y=`┌${"─".repeat($)}┐`,h=`└${"─".repeat($)}┘`,w=u.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:K.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(y),showTimestamp:!1})),w.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:K.cyan(h),showTimestamp:!1}))}else if(!Z())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
20
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(Z())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${K.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();M.stdin.removeListener("data",r);try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!1)}catch{}M.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof M.stdin.setRawMode==="function")M.stdin.setRawMode(!0)}catch{}M.stdin.resume(),M.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,u=0;if(r=i.replace(c,($,y)=>{if(y==="%")return"%";if(u>=t.length)return $;let h=t[u++];switch(y){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return $}}),u<t.length)r+=` ${t.slice(u).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${u}${c} ${K.cyan(n)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
21
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!M.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=K.green("━".repeat(n)),c=K.gray("━".repeat(f)),u=`[${l}${c}]`,$=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===100?K.green("✓"):K.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",e=`\r${h}${w} ${u} ${$}${y}`,A=M.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,M.stdout.write(i.lastRenderedLine),t)M.stdout.write(`
22
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||Z()||!M.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(Z()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zr(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Vt(this.config.logDirectory,n);if(i.before)try{if((await kt(f)).mtime>=i.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 pr(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function D$(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let u=0;u<=r;u++)try{return await i()}catch($){if(c=$ instanceof Error?$:Error(String($)),u===r||!f(c))break;if(n>0)await new Promise((y)=>setTimeout(y,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function b$(i){return i instanceof Ui}function Pe(i){return i instanceof Nn}function ve(i){if(b$(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>i.message.toLowerCase().includes(t.toLowerCase()))}class Gn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:u=!1,trackPerformance:$=!0}=r,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),w={...t};return this.processObject(w,[],h,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:u,configName:i}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if($)return Xr.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],u=c.map((h)=>this.formatEnvKey(h,n.useCamelCase)),$=`${r}_${u.join("_")}`,y=n.useBackwardCompatibility?`${r}_${c.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let h=tn.env[$]||(y?tn.env[y]:void 0);if(h!==void 0){if(n.verbose){let w=tn.env[$]?$:y}try{i[f]=this.parseEnvironmentValue(h,typeof l,$,n.customParsers,n.configName)}catch(w){if(w instanceof Wn)throw w;throw at.envVar($,h,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw at.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(tn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],u=`${r}_${c.map(($)=>this.formatEnvKey($,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:u,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
23
-
24
- `;for(let n of i)r+=`${n.key}
25
- `,r+=` Type: ${n.type}
26
- `,r+=` Description: ${n.description}
27
- `,r+=` Example: ${n.example}
28
-
29
- `;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
30
-
31
- `;r+=`| Variable | Type | Description | Example |
32
- `,r+=`|----------|------|-------------|----------|
33
- `;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
34
- `;return r}}function Ze(i,t){let r=Z$("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function Q$(i,t,r={}){return o$(i,t,r,new WeakMap)}function o$(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let u=c(i,t);if(u!==void 0)return u}if(Array.isArray(t)||Array.isArray(i))return P$(i,t,f,n);if(!Wi(t)||!Wi(i))return t;return r1(i,t,r,n)}function P$(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return pe(i,t);case"smart":return i1(i,t,n);default:return t}return t}function pe(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Bl(f,n)))r.push(n);return r}function i1(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Wi(t[0])&&Wi(i[0]))return t1(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function t1(i,t,r){let n=[...t];for(let f of i){if(!Wi(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let u of l)if(u in f){if(n.find(($)=>Wi($)&&(u in $)&&$[u]===f[u])){c=!0;break}}if(!c)n.push(f)}return n}function r1(i,t,r,n){let f=t;if(Wi(f)&&n.has(f))return n.get(f);let l={...i};if(Wi(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let u=f[c],$=l[c];if(r.skipNullish&&(u===null||u===void 0))continue;if(u===null||u===void 0){l[c]=u;continue}if(Wi(u)&&Wi($))l[c]=o$($,u,r,n);else if(Array.isArray(u)||Array.isArray($))l[c]=P$($,u,r.arrayMergeMode||"smart",n);else l[c]=u}return l}function gl(i,t,r="replace"){return Q$(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Bl(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Bl(i[r],t[r]))return!1;return!0}if(Wi(i)&&Wi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Bl(i[f],t[f]))return!1}return!0}return!1}function Wi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Mn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:u=!1}=r;if(f){let y=vt.getWithFileCheck("file",i);if(y){if(u)console.log(`Configuration loaded from cache: ${i}`);return y}}let $=async()=>{if(!rn(i))return null;try{let y=`?t=${Date.now()}`,h=await import(i+y),w=h.default||h,e="default"in h,A=Object.keys(h).length>0;if(!e&&!A)throw new Fr(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new Fr(i,Error("Configuration must export a valid object"),"unknown");let m={config:gl(t,w,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)vt.setWithFileCheck("file",m,i,l);return m}catch(y){throw y instanceof Error?at.configLoad(i,y):at.configLoad(i,Error(String(y)))}};if(c)return Xr.track("loadFromPath",$,{path:i});return $()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(nl(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return D$(async()=>{return rn(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!rn(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let u=nl(i,`${l}${c}`);if(await this.checkFileAccess(u))n.push(u)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let u=nl(i,c);if(await this.checkFileAccess(u))n.push(u)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!rn(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class ql{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:u=!0,verbose:$=!1}=r,y=async()=>{let h=[],w=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:u,verbose:$};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return h.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:h,warnings:w}}};if(u)return await Xr.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,r){try{if(!me(t))throw new Nr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Nr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,u=Array.isArray(t.type)?t.type:[t.type];if(!u.includes(c)){if(n.push({path:r,message:`Expected type ${u.join(" or ")}, got ${c}`,expected:u.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let u=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,u,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let u of t.required)if(!(u in c)){if(n.push({path:r?`${r}.${u}`:u,message:`Missing required property '${u}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[u,$]of Object.entries(t.properties))if(u in c){let y=r?`${r}.${u}`:u;if(this.validateObjectAgainstSchema(c[u],$,y,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let u=new Set(Object.keys(t.properties||{}));for(let $ of Object.keys(c))if(!u.has($))f.push({path:r?`${r}.${$}`:$,message:`Additional property '${$}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),u=this.validateWithRule(c,l,l.path);if(n.push(...u),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:nu},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Ll{fileLoader=new Mn;envProcessor=new Gn;validator=new ql;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let $=this.checkCache(c.name||"",c);if($)return $}let u;try{u=await this.loadConfigurationStrategies(c,!0,r)}catch($){let y=c.__strictErrorHandling;if($ instanceof Error&&$.name==="ConfigNotFoundError"){if(y)throw $;u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if($ instanceof Error&&$.name==="ConfigLoadError"){let h=$.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"),w=!h&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")||$.message.includes("errors building")),e=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");if(y&&(e||h))throw $;if(w&&(!y||!e))u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${$.message}`]};else throw $}else u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${$ instanceof Error?$.message:String($)}`]}}if(f||l)await this.validateConfiguration(u.config,f,l,c.name);if(r?.enabled&&u)this.cacheResult(c.name||"",u,r,c);if(n?.enabled){let $={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics($);if(n.slowThreshold&&$.duration>n.slowThreshold)Oi.warn(`Slow configuration loading detected: ${$.duration}ms for ${c.name}`);u.metrics=$}return u}catch(u){let $=Date.now()-t;throw Oi.error(`Configuration loading failed after ${$}ms:`,[u instanceof Error?u:Error(String(u))]),u}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:u,checkEnv:$=!0,arrayStrategy:y="replace",verbose:h=!1}=i,w=l||Xt.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,w,c,u,y,h,$,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,w,c)),this.finalizeResult(A,e,$,n,h);let m=await this.loadHomeConfiguration(n,f,u,y,h,$);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,$,n,h);let s=await this.loadPackageJsonConfiguration(n,f,w,u,y,h,$);if(s)return e.push(ai(w,"package.json")),this.finalizeResult(s,e,$,n,h);if(e.push(...this.getAllSearchPaths(n,f,w,c)),t)throw at.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,u,$,h),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,u,$){let y=u?Ur(i,f,c):f,h=this.getLocalDirectories(r,n);for(let w of h){if(c)Oi.info(`Searching for configuration in: ${w}`);let e=this.fileLoader.generateConfigPaths(i,w,t),A=await this.fileLoader.tryLoadFromPaths(e,y,{arrayStrategy:l,verbose:c,cacheTtl:$?.ttl,useCache:!$?.ttl||$.ttl>100});if(A){if(c)Oi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?Ur(i,r,f):r,u=[ai(gt(),".config",i),ai(gt(),".config"),gt()];for(let $ of u){if(f)Oi.info(`Checking home directory: ${$}`);let y=this.fileLoader.generateConfigPaths(i,$,t),h=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:n,verbose:f});if(h){if(f)Oi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let u=c?Ur(i,n,l):n;try{let $=ai(r,"package.json");if(!Tl($))return null;let y=await import($),h=y[i],w=i;if(!h&&t)h=y[t],w=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(l)Oi.success(`Configuration loaded from package.json: ${w}`);return{config:gl(u,h,f),source:{type:"package.json",path:$,priority:30,timestamp:new Date}}}}catch($){if(l)Oi.warn("Failed to load package.json:",[$ instanceof Error?$:Error(String($))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Ur(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw at.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return vt.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);vt.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,ai(i,"config"),ai(i,".config"),t?ai(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(ai(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[ai(gt(),".config",i),ai(gt(),".config"),gt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function u$(i){let t=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||r}async function n1(i){return tt.loadConfig({...i,__strictErrorHandling:!0})}async function v$(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await tt.loadConfig(i);else n=await tt.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",l=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||l.includes("config"))&&i.verbose)Oi.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await tt.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function f1(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await tt.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&u$(r)))return(await tt.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}try{return(await tt.loadConfig({...i,cwd:i.cwd||Xt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&u$(t)))return(await tt.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function l1(i,t,r="replace"){let n=new Mn;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Ur(i,t,r=!1){let n=new Gn,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,u=[]){let $={...c};for(let[y,h]of Object.entries(c)){let w=[...u,y],e=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((s)=>s.toUpperCase()).join("")}`,`${f}_${w.map((s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let s of e)if(A=Xt.env[s],A!==void 0){m=s;break}if(A!==void 0&&m)if(typeof h==="boolean")$[y]=["true","1","yes"].includes(A.toLowerCase());else if(typeof h==="number"){let s=Number(A);if(!Number.isNaN(s))$[y]=s}else if(Array.isArray(h))try{$[y]=JSON.parse(A)}catch{$[y]=A.split(",").map((s)=>s.trim())}else $[y]=A;else if(h&&typeof h==="object"&&!Array.isArray(h))$[y]=l(h,w)}return $}return l(t)}function c1(i){let t=ai(Xt.cwd(),i.configDir),r=ai(Xt.cwd(),i.generatedDir),n=ai(r,"config-types.ts");if(!Tl(d0(n)))bw(d0(n),{recursive:!0,mode:511});let f=Tl(t)?Qw(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],l=`// Generated by bunfig v${O1}
35
- export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
36
- `;ow(n,l,{mode:438})}function $1(i){let t=null,r=null,n=()=>{if(!r)r=v$(i).then((l)=>{return t=l,l},(l)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)Oi.warn("Config loading failed, using defaults:",[l instanceof Error?l:Error(String(l))]);return c});return r},f="defaultConfig"in i?i.defaultConfig:{};return t=f,n(),new Proxy({},{get(l,c){if(t)return t[c];let u=f[c];return n(),u},has(l,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(l,c){return Object.getOwnPropertyDescriptor(t||f,c)},set(l,c,u){if(!t)t={...f};return t[c]=u,!0}})}function u1(i){let t=i$(Ye.cwd(),i?.configDir||"./config");function r(){if(!Ee(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),l=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=Te(t).filter(($)=>f.has(fl($))).map(($)=>({base:$.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:$})),u=new Map;for(let{base:$,file:y}of c){let h=fl(y).toLowerCase(),w=u.get($);if(!w){u.set($,y);continue}let e=fl(w).toLowerCase();if(l.indexOf(h)<l.indexOf(e))u.set($,y)}return Array.from(u.entries()).map(([$,y])=>({base:$,file:y})).sort(($,y)=>$.base.localeCompare(y.base))}function n(){let f=r(),l=f.map(($)=>$.base),c=l.length?l.map(($)=>`'${$}'`).join(" | "):"string",u=f.length?`{
37
- ${f.map(($)=>{let y=i$(t,$.file).replace(/\\/g,"/");return` '${$.base}': typeof import('${y}').default`}).join(`,
38
- `)}
39
- }`:"Record<string, any>";return`export type ConfigNames = ${c}
40
- export type ConfigByName = ${u}
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(f){f.onResolve({filter:/^virtual:bunfig-types$/},(l)=>{return{path:l.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var Z$,vt,Xr,p$,y1,h1,y$,en,Cl,ui,L,w1,h$,e1,w$,A1,s1,yl,a1,e$,A$,hl,m1,E1,T1,Y1,An,iu,B1,yi,C1,U1,s$,sn,Ul,p,K,R1,a$,S1,m$,j1,F1,wl,N1,E$,T$,W1,el,X1,J1,I1,_1,K1,an,tu,z1,O1="0.15.6",Ui,Nn,Fr,Rl,Sl,Wn,jl,Fl,Nr,Nl,Wl,at,ru,nu,Oi,tt,fu,lu,G1=Ge(async()=>{Z$=import.meta.require,vt=new Gl,Xr=new Ml,p$={createKey:Me,isEquivalent:He,estimateMemoryUsage:de},y1=Bn(Yl.cwd(),"config"),h1=Bn(Yl.cwd(),"src/generated"),y$=Yn.env.CLARITY_LOG_DIR||Zw(Le(),"logs"),en={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:y$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Cl=await xe(),ui={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},L=ui,w1=ui.red,h$=ui.green,e1=ui.yellow,w$=ui.blue,A1=ui.magenta,s1=ui.cyan,yl=ui.white,a1=ui.gray,e$=ui.bgRed,A$=ui.bgYellow,hl=ui.bold,m1=ui.dim,E1=ui.italic,T1=ui.underline,Y1=ui.reset,An={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},iu={debug:"\uD83D\uDD0D",info:w$("ℹ"),success:h$("✓"),warning:A$(yl(hl(" WARN "))),error:e$(yl(hl(" ERROR ")))},B1=new Sn("stacks"),yi=new Sn("bunfig",{showTags:!0}),C1=si(jr.cwd(),"config"),U1=si(jr.cwd(),"src/generated"),s$=Tn.env.CLARITY_LOG_DIR||Pw(be(),"logs"),sn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:s$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ul=await Qe(),p={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},K=p,R1=p.red,a$=p.green,S1=p.yellow,m$=p.blue,j1=p.magenta,F1=p.cyan,wl=p.white,N1=p.gray,E$=p.bgRed,T$=p.bgYellow,W1=p.bgGray,el=p.bold,X1=p.dim,J1=p.italic,I1=p.underline,_1=p.strikethrough,K1=p.reset,an={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tu={debug:"\uD83D\uDD0D",info:m$("ℹ"),success:a$("✓"),warning:T$(wl(el(" WARN "))),error:E$(wl(el(" ERROR ")))},z1=new Fn("stacks"),Ui=class extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Nn=class extends Ui{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${i}"${n} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}},Fr=class extends Ui{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},Rl=class extends Ui{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}},Sl=class extends Ui{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Wn=class extends Ui{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}},jl=class extends Ui{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Fl=class extends Ui{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Nr=class extends Ui{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}},Nl=class extends Ui{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}},Wl=class extends Ui{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},at={configNotFound(i,t,r){return new Nn(i,t,r)},configLoad(i,t,r){return new Fr(i,t,r)},configValidation(i,t,r){return new Rl(i,t,r)},configMerge(i,t,r,n){return new Sl(i,t,r,n)},envVar(i,t,r,n){return new Wn(i,t,r,n)},fileSystem(i,t,r){return new jl(i,t,r)},typeGeneration(i,t,r){return new Fl(i,t,r)},schemaValidation(i,t,r){return new Nr(i,t,r)},browserConfig(i,t,r,n){return new Nl(i,t,r,n)},plugin(i,t,r){return new Wl(i,t,r)}},ru={replace:"replace",concat:"concat",smart:"smart"},nu=/^https?:\/\//,Oi=new Fn("bunfig",{showTags:!0}),tt=new Ll,fu=ai(Xt.cwd(),"config"),lu=ai(Xt.cwd(),"src/generated")});function M1(i,t={}){let r=Cn.cwd();while(r.includes("storage"))r=t$(r,"..");let n=t$(r,i||"");if(t?.relative)return Ce(Cn.cwd(),n);return n}var H1=Cn.env.CLARITY_LOG_DIR||Be(M1(),"logs"),cu={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:H1,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Xn={...cu},YY=(async()=>{try{let{loadConfig:i}=await G1().then(()=>x$),t=await i({name:"clarity",alias:"logging",defaultConfig:cu,cwd:Cn.cwd()});if(t)Object.assign(Xn,t)}catch{}return Xn})();function ii(){if(pi.env.NODE_ENV==="test"||pi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function d1(){if(pi.env.NODE_ENV==="test"||pi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pi<"u"){let i=pi.type;if(i==="renderer"||i==="worker")return!1;return!!(pi.versions&&(pi.versions.node||pi.versions.bun))}return!1}class $u{async format(i){let t=await d1(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:ot.pid,hostname:t(),environment:ot.env.NODE_ENV||"development",platform:ot.platform,version:ot.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ot.env.NODE_ENV||ot.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var li={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=li,BY=li.red,g1=li.green,CY=li.yellow,q1=li.blue,UY=li.magenta,RY=li.cyan,Y$=li.white,SY=li.gray,L1=li.bgRed,x1=li.bgYellow,jY=li.bgGray,B$=li.bold,FY=li.dim,NY=li.italic,WY=li.underline,XY=li.strikethrough,JY=li.reset,Al={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},k1={debug:"\uD83D\uDD0D",info:q1("ℹ"),success:g1("✓"),warning:x1(Y$(B$(" WARN "))),error:L1(Y$(B$(" ERROR ")))};class Hn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Xn},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new $u,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.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 f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Al,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Al};return{...Al,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Xn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ii()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let n,f=0,l=3,c=1000;while(f<l)try{try{try{await Fe(this.config.logDirectory,l$.F_OK|l$.W_OK)}catch($){if($ instanceof Error&&"code"in $)if($.code==="ENOENT")await Ne(this.config.logDirectory,{recursive:!0,mode:493});else if($.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw $;else throw $}}catch($){throw console.error("Debug: [writeToFile] Failed to create log directory:",$),$}let u=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:oi.from(i);try{if(!nn(this.currentLogFile))await $l(this.currentLogFile,"",{mode:420});if(n=f$(this.currentLogFile,"a",420),je(n,u,{flag:"a"}),n$(n),n!==void 0)cl(n),n=void 0;if((await bt(this.currentLogFile)).size===0){if(await $l(this.currentLogFile,u,{flag:"w",mode:420}),(await bt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch($){let y=$;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(f<l-1){let h=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,h);let w=c*2**f;await new Promise((e)=>setTimeout(e,w)),f++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(n!==void 0)try{cl(n)}catch($){console.error("Debug: [writeToFile] Error closing file descriptor:",$)}}}catch(u){if(f===l-1){let y=u,h=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),u}f++;let $=c*2**(f-1);await new Promise((y)=>setTimeout(y,$))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}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 Qt(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 Qt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Qt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ii())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,r=Math.max(t,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 i=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,c],[,u])=>u.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(n.length>l)for(let[c]of n.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return ll(16).toString("hex")}generateKey(){return ll(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=ll(16),n=Ue("aes-256-gcm",t,r),f=oi.isBuffer(i)?i:oi.from(i,"utf8"),l=n.update(f),c=n.final(),u=l.length+c.length,$=n.getAuthTag(),y=oi.allocUnsafe(16+u+16);return r.copy(y,0),l.copy(y,16),c.copy(y,16+l.length),$.copy(y,16+u),{encrypted:y,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=$$(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(oi.from(oi.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ii())return;if(!this.shouldWriteToFile())return;let i=await bt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await fn(this.config.logDirectory),l=f.filter(($)=>$.startsWith(this.name)&&/\.log\.\d+$/.test($)).sort(($,y)=>{let h=Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,u=`${r}.${c}`;if(await bt(r).catch(()=>null))try{if(await c$(r,u),t.compress)try{let $=`${u}.gz`;await this.compressLogFile(u,$),await ln(u)}catch($){console.error("Error compressing rotated file:",$)}if(l.length===0&&!f.some(($)=>$.endsWith(".log.1")))try{let $=`${r}.1`;await $l($,"")}catch($){console.error("Error creating backup file:",$)}}catch($){console.error(`Error during rotation: ${$ instanceof Error?$.message:String($)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await bt(r).catch(()=>null))await c$(r,l)}if(this.currentLogFile=n,t.maxFiles){let f=(await fn(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await ln(Qt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let r=r$(i),n=Se(t),f=$$();await Je(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!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(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),nn(this.currentLogFile))try{let i=f$(this.currentLogFile,"r+");n$(i),cl(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ii()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await fn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await ln(Qt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ii())return!1;let i=typeof H.env.NO_COLOR<"u",t=H.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,u=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let $=H.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${O.cyan(f)}`;if(!c)return y.trim();let h=u(y).trim().length,w=u(t).length,e=Math.max(1,$-2-h-w);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let u=Number.parseInt(c,10);return u<t[0].length?String(t[0][u]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let u=t[n++];switch(c){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 l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=O.underline(O.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let u=`file://${encodeURI(c)}`,$="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${u}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>O.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>O.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>O.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>O.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>O.strikethrough(n)),t}supportsHyperlinks(){if(ii())return!1;let i=H.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=H.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(We(t)||t.startsWith("./")||t.startsWith("../"))t=Xe(t);else return null;return nn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,u;if(t instanceof Error)c=t.message,u=t.stack;else c=this.formatMessage(t,r);let{consoleText:$,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":k1[i],e=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:O.gray($),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:O.green($),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.error(A),u){let m=u.split(`
44
- `);for(let s of m)if(s.trim()&&!s.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:O.gray(` ${s}`),level:i,showTimestamp:!1}))}break}}else if(!ii()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),u)console.error(u)}let h=`${l} ${this.environment}.${i.toUpperCase()}: ${y}
45
- `;if(u)h+=`${u}
46
- `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(f,l)=>{},finish:(f)=>{},interrupt:(f,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ii()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!ii()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,l="info")=>{if(!ii()&&H.stdout.isTTY)H.stdout.write(`
47
- `);if(this[l==="warning"?"warn":l](f),this.activeProgressBar&&this.shouldStyleConsole()&&!ii()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":O.blue("◐"),tag:r,message:`${O.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,u=this.formatConsoleTimestamp(c),$=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)$+=` ${JSON.stringify(r)}`;if($+=`
48
- `,$=$.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:u,icon:this.options.showIcons===!1?"":O.green("✓"),tag:y,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ii())console.error($.trim());if(this.shouldWriteToFile())await this.writeToFile($)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new Hn(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ii())throw Error("createReadStream is not supported in browser environments");if(!nn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return r$(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=oi.isBuffer(i)?i:oi.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),u=Re("aes-256-gcm",r,f);u.setAuthTag(l);let $=u.update(c),y=u.final(),h=$.length+y.length,w=oi.allocUnsafe(h);return $.copy(w,0),y.copy(w,$.length),w.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 ii()}isServerMode(){return!ii()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let u=f.split(`
49
- `),$=Math.max(...u.map((e)=>e.length))+2,y=`┌${"─".repeat($)}┐`,h=`└${"─".repeat($)}┘`,w=u.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:O.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(y),showTimestamp:!1})),w.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:O.cyan(h),showTimestamp:!1}))}else if(!ii())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
50
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ii())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();H.stdin.removeListener("data",r);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,u=0;if(r=i.replace(c,($,y)=>{if(y==="%")return"%";if(u>=t.length)return $;let h=t[u++];switch(y){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return $}}),u<t.length)r+=` ${t.slice(u).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",u=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${u}${c} ${O.cyan(n)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
51
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=O.green("━".repeat(n)),c=O.gray("━".repeat(f)),u=`[${l}${c}]`,$=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===100?O.green("✓"):O.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",e=`\r${h}${w} ${u} ${$}${y}`,A=H.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,H.stdout.write(i.lastRenderedLine),t)H.stdout.write(`
52
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ii()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ii()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await fn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Qt(this.config.logDirectory,n);if(i.before)try{if((await bt(f)).mtime>=i.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 ln(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var IY=new Hn("stacks");class Hi extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class uu extends Hi{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],f="";if(n.length===1)f=` or alias "${n[0]}"`;else if(n.length>1)f=` or aliases ${n.map((l)=>`"${l}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}}class Jn extends Hi{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class yu extends Hi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class hu extends Hi{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class xl extends Hi{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}}class wu extends Hi{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class eu extends Hi{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class In extends Hi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class Au extends Hi{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}}class su extends Hi{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var Zt={configNotFound(i,t,r){return new uu(i,t,r)},configLoad(i,t,r){return new Jn(i,t,r)},configValidation(i,t,r){return new yu(i,t,r)},configMerge(i,t,r,n){return new hu(i,t,r,n)},envVar(i,t,r,n){return new xl(i,t,r,n)},fileSystem(i,t,r){return new wu(i,t,r)},typeGeneration(i,t,r){return new eu(i,t,r)},schemaValidation(i,t,r){return new In(i,t,r)},browserConfig(i,t,r,n){return new Au(i,t,r,n)},plugin(i,t,r){return new su(i,t,r)}};async function V1(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let u=0;u<=r;u++)try{return await i()}catch($){if(c=$ instanceof Error?$:Error(String($)),u===r||!f(c))break;if(n>0)await new Promise((y)=>setTimeout(y,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class kl{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:u=!1,trackPerformance:$=!0}=r,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),w={...t};return this.processObject(w,[],h,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:u,configName:i}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if($)return Ol.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],u=c.map((h)=>this.formatEnvKey(h,n.useCamelCase)),$=`${r}_${u.join("_")}`,y=n.useBackwardCompatibility?`${r}_${c.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let h=cn.env[$]||(y?cn.env[y]:void 0);if(h!==void 0){if(n.verbose){let w=cn.env[$]?$:y}try{i[f]=this.parseEnvironmentValue(h,typeof l,$,n.customParsers,n.configName)}catch(w){if(w instanceof xl)throw w;throw Zt.envVar($,h,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw Zt.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(cn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],u=`${r}_${c.map(($)=>this.formatEnvKey($,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:u,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
53
-
54
- `;for(let n of i)r+=`${n.key}
55
- `,r+=` Type: ${n.type}
56
- `,r+=` Description: ${n.description}
57
- `,r+=` Example: ${n.example}
58
-
59
- `;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
60
-
61
- `;r+=`| Variable | Type | Description | Example |
62
- `,r+=`|----------|------|-------------|----------|
63
- `;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
64
- `;return r}}function D1(i,t,r={}){return au(i,t,r,new WeakMap)}function au(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let u=c(i,t);if(u!==void 0)return u}if(Array.isArray(t)||Array.isArray(i))return mu(i,t,f,n);if(!Xi(t)||!Xi(i))return t;return P1(i,t,r,n)}function mu(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return b1(i,t);case"smart":return Q1(i,t,n);default:return t}return t}function b1(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Xl(f,n)))r.push(n);return r}function Q1(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Xi(t[0])&&Xi(i[0]))return o1(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function o1(i,t,r){let n=[...t];for(let f of i){if(!Xi(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let u of l)if(u in f){if(n.find(($)=>Xi($)&&(u in $)&&$[u]===f[u])){c=!0;break}}if(!c)n.push(f)}return n}function P1(i,t,r,n){let f=t;if(Xi(f)&&n.has(f))return n.get(f);let l={...i};if(Xi(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let u=f[c],$=l[c];if(r.skipNullish&&(u===null||u===void 0))continue;if(u===null||u===void 0){l[c]=u;continue}if(Xi(u)&&Xi($))l[c]=au($,u,r,n);else if(Array.isArray(u)||Array.isArray($))l[c]=mu($,u,r.arrayMergeMode||"smart",n);else l[c]=u}return l}function Eu(i,t,r="replace"){return D1(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Xl(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Xl(i[r],t[r]))return!1;return!0}if(Xi(i)&&Xi(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Xl(i[f],t[f]))return!1}return!0}return!1}function Xi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Tu{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:u=!1}=r;if(f){let y=Un.getWithFileCheck("file",i);if(y){if(u)console.log(`Configuration loaded from cache: ${i}`);return y}}let $=async()=>{if(!$n(i))return null;try{let y=`?t=${Date.now()}`,h=await import(i+y),w=h.default||h,e="default"in h,A=Object.keys(h).length>0;if(!e&&!A)throw new Jn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new Jn(i,Error("Configuration must export a valid object"),"unknown");let m={config:Eu(t,w,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Un.setWithFileCheck("file",m,i,l);return m}catch(y){throw y instanceof Error?Zt.configLoad(i,y):Zt.configLoad(i,Error(String(y)))}};if(c)return Ol.track("loadFromPath",$,{path:i});return $()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(ul(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let l of n){if(!l)continue;if(r.push(l,`.${l}.config`,`${l}.config`,`.${l}`),i)r.push(`${i}.${l}.config`,`.${i}.${l}.config`)}let f=new Set;return r.filter((l)=>{if(!l||f.has(l))return!1;return f.add(l),!0})}checkFileAccess(i){return V1(async()=>{return $n(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!$n(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let u=ul(i,`${l}${c}`);if(await this.checkFileAccess(u))n.push(u)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let u=ul(i,c);if(await this.checkFileAccess(u))n.push(u)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!$n(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var v1=/^https?:\/\//;class Yu{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:u=!0,verbose:$=!1}=r,y=async()=>{let h=[],w=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:u,verbose:$};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return h.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:h,warnings:w}}};if(u)return await Ol.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,r){try{if(!Ie(t))throw new In(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new In(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,u=Array.isArray(t.type)?t.type:[t.type];if(!u.includes(c)){if(n.push({path:r,message:`Expected type ${u.join(" or ")}, got ${c}`,expected:u.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let u=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,u,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let u of t.required)if(!(u in c)){if(n.push({path:r?`${r}.${u}`:u,message:`Missing required property '${u}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[u,$]of Object.entries(t.properties))if(u in c){let y=r?`${r}.${u}`:u;if(this.validateObjectAgainstSchema(c[u],$,y,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let u=new Set(Object.keys(t.properties||{}));for(let $ of Object.keys(c))if(!u.has($))f.push({path:r?`${r}.${$}`:$,message:`Additional property '${$}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),u=this.validateWithRule(c,l,l.path);if(n.push(...u),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:v1},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Pi=new Hn("bunfig",{showTags:!0});function Z1(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class Bu{fileLoader=new Tu;envProcessor=new kl;validator=new Yu;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let $=this.checkCache(c.name||"",c);if($)return $}let u;try{u=await this.loadConfigurationStrategies(c,!0,r)}catch($){let y=c.__strictErrorHandling;if($ instanceof Error&&$.name==="ConfigNotFoundError"){if(y)throw $;u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if($ instanceof Error&&$.name==="ConfigLoadError"){let h=$.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"),w=!h&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")||$.message.includes("errors building")),e=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");if(y&&(e||h))throw $;if(w&&(!y||!e))u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${$.message}`]};else throw $}else u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${$ instanceof Error?$.message:String($)}`]}}if(f||l)await this.validateConfiguration(u.config,f,l,c.name);if(r?.enabled&&u)this.cacheResult(c.name||"",u,r,c);if(n?.enabled){let $={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics($);if(n.slowThreshold&&$.duration>n.slowThreshold)Pi.warn(`Slow configuration loading detected: ${$.duration}ms for ${c.name}`);u.metrics=$}return u}catch(u){if(u instanceof Error&&u.name==="ConfigNotFoundError")throw u;let $=Date.now()-t;throw Pi.error(`Configuration loading failed after ${$}ms:`,[u instanceof Error?u:Error(String(u))]),u}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:u,checkEnv:$=!0,arrayStrategy:y="replace",verbose:h=!1}=i,w=l||On.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,w,c,u,y,h,$,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,w,c)),this.finalizeResult(A,e,$,n,h);let m=await this.loadHomeConfiguration(n,f,u,y,h,$);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,$,n,h);let s=await this.loadPackageJsonConfiguration(n,f,w,u,y,h,$);if(s)return e.push(Ni(w,"package.json")),this.finalizeResult(s,e,$,n,h);if(e.push(...this.getAllSearchPaths(n,f,w,c)),t)throw Zt.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,u,$,h),warnings:[`No configuration file found for "${n}"${Z1(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,u,$){let y=u?yn(i,f,c):f,h=this.getLocalDirectories(r,n);for(let w of h){if(c)Pi.info(`Searching for configuration in: ${w}`);let e=this.fileLoader.generateConfigPaths(i,w,t),A=await this.fileLoader.tryLoadFromPaths(e,y,{arrayStrategy:l,verbose:c,cacheTtl:$?.ttl,useCache:!$?.ttl||$.ttl>100});if(A){if(c)Pi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?yn(i,r,f):r,u=[Ni(dt(),".config",i),Ni(dt(),".config"),dt()];for(let $ of u){if(f)Pi.info(`Checking home directory: ${$}`);let y=this.fileLoader.generateConfigPaths(i,$,t),h=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:n,verbose:f});if(h){if(f)Pi.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let u=c?yn(i,n,l):n;try{let $=Ni(r,"package.json");if(!Vw($))return null;let y={};try{y=JSON.parse(Dw($,"utf8"))}catch(e){if(l)Pi.warn("Failed to parse package.json:",[e instanceof Error?e:Error(String(e))]);return null}let h=y[i],w=i;if(!h&&t){let e=Array.isArray(t)?t:[t];for(let A of e){if(!A)continue;if(y[A]){h=y[A],w=A;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(l)Pi.success(`Configuration loaded from package.json: ${w}`);return{config:Eu(u,h,f),source:{type:"package.json",path:$,priority:30,timestamp:new Date}}}}catch($){if(l)Pi.warn("Failed to load package.json:",[$ instanceof Error?$:Error(String($))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:yn(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Zt.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return Un.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);Un.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ni(i,"config"),Ni(i,".config"),t?Ni(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ni(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ni(dt(),".config",i),Ni(dt(),".config"),dt()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var _Y=new Bu;function yn(i,t,r=!1){let n=new kl,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,u=[]){let $={...c};for(let[y,h]of Object.entries(c)){let w=[...u,y],e=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((s)=>s.toUpperCase()).join("")}`,`${f}_${w.map((s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let s of e)if(A=On.env[s],A!==void 0){m=s;break}if(A!==void 0&&m)if(typeof h==="boolean")$[y]=["true","1","yes"].includes(A.toLowerCase());else if(typeof h==="number"){let s=Number(A);if(!Number.isNaN(s))$[y]=s}else if(Array.isArray(h))try{$[y]=JSON.parse(A)}catch{$[y]=A.split(",").map((s)=>s.trim())}else $[y]=A;else if(h&&typeof h==="object"&&!Array.isArray(h))$[y]=l(h,w)}return $}return l(t)}var KY=Ni(On.cwd(),"config"),zY=Ni(On.cwd(),"src/generated"),Cu={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:Qf.join(bf.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:Qf.join(bf.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:Qf.join(bf.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},v=Cu,Gi={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"},Pt={info:(...i)=>console.log(...i),warn:(...i)=>console.warn(...i),success:(...i)=>console.log(...i),error:(...i)=>console.error(...i),debug:(...i)=>console.debug(...i)};function Ru(i){return Jl.readFileSync(i,"utf8")}function Il(i,t){let r=[];function n(f){let l;try{l=Jl.readdirSync(f)}catch{return}for(let c of l){let u=zi.join(f,c);try{if(Jl.statSync(u).isDirectory())n(u);else if(c===t)r.push(f)}catch{continue}}}return n(i),r}function U(i,t,r){if(r||v.verbose)console.debug(`[tlsx:${i}] ${t}`)}var rA=tA(p1);function Su(){return Uu.env.SUDO_PASSWORD}var C$="[redacted]",nA=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),fA=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function lA(i){let t=i.toLowerCase();return nA.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function _n(i){if(Array.isArray(i))return i.map((r)=>_n(r));if(typeof i==="string")return fA.test(i)?C$:i;if(!i||typeof i!=="object")return i;let t={};for(let[r,n]of Object.entries(i)){if(lA(r)){t[r]=C$;continue}t[r]=_n(n)}return t}function dn(i){return JSON.stringify(_n(i))}function cA(i){let t=Su();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let r=t.replace(/'/g,"'\\''"),n=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function st(i,t={}){let r=cA(i);try{let{stdout:n,stderr:f}=await rA(r,{cwd:t.cwd||Uu.cwd(),timeout:t.timeout||30000});return{stdout:n.trim(),stderr:f.trim()}}catch(n){let f=Error(`Failed to execute command: ${i}
65
- Error: ${n.message}`);throw f.stack=n.stack,f}}function ju(i){if(i.domain)return i.domain;if(i.domains?.length)return i.domains[0];throw Error("Either domain or domains must be specified")}function Vl(i){let t=zi.join(iA.homedir(),".stacks","ssl"),r=i.basePath&&i.basePath.trim()!==""?i.basePath:v.basePath&&v.basePath.trim()!==""?v.basePath:t,n=i.certPath?zi.isAbsolute(i.certPath)?i.certPath:zi.join(r,i.certPath):zi.join(r,v.certPath),f=i.keyPath?zi.isAbsolute(i.keyPath)?i.keyPath:zi.join(r,i.keyPath):zi.join(r,v.keyPath),l=i.caCertPath?zi.isAbsolute(i.caCertPath)?i.caCertPath:zi.join(r,i.caCertPath):zi.join(r,v.caCertPath);return{certPath:n,keyPath:f,caCertPath:l,basePath:r}}function Fu(i){let t=[],r=new Set;if(i.domain)r.add(i.domain);if(i.domains?.length)i.domains.forEach((n)=>r.add(n));for(let n of r)t.push({type:2,value:n});if(i.altNameIPs?.length)for(let n of i.altNameIPs)t.push({type:7,ip:n});if(i.altNameURIs?.length)for(let n of i.altNameURIs)t.push({type:6,value:n});if(i.subjectAltNames?.length)t.push(...i.subjectAltNames);return U(S.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function Dl(i){let t=i.notBeforeDays??Gi.DEFAULT_NOT_BEFORE_DAYS,r=i.validityDays??(i.validityYears?i.validityYears*365:Gi.DEFAULT_VALIDITY_DAYS);U(S.CERT,"Calculating certificate validity dates",i.verbose);let n=new Date(Date.now()-86400*t*1000),f=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),U(S.CERT,`Validity period: ${n.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:n,notAfter:f}}var Mi={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},mi={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 Rr(i){if(i<128)return Buffer.from([i]);let t=[],r=i;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function Si(i,t){let r=Rr(t.length);return Buffer.concat([Buffer.from([i]),r,t])}function Wr(i){let t=i.split(".").map(Number),r=[];r.push(40*t[0]+t[1]);for(let n=2;n<t.length;n++){let f=t[n],l=[];l.unshift(f&127),f>>=7;while(f>0)l.unshift(f&127|128),f>>=7;r.push(...l)}return Si(Mi.OID,Buffer.from(r))}function _l(i){let t;if(typeof i==="bigint"){let r=i.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let r=i.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Si(Mi.INTEGER,t)}function Nu(i,t=0){return Si(Mi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function Wu(i){return Si(Mi.OCTET_STRING,i)}function Ri(...i){return Si(Mi.SEQUENCE,Buffer.concat(i))}function $A(...i){return Si(Mi.SET,Buffer.concat(i))}function uA(i){return Si(Mi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function yA(i){return Si(Mi.UTF8_STRING,Buffer.from(i,"utf8"))}function hA(){return Buffer.from([Mi.NULL,0])}function U$(i,t,r=!0){let n=160|i|(r?0:0),f=Rr(t.length);return Buffer.concat([Buffer.from([n]),f,t])}function R$(i){let t=i.getUTCFullYear();if(t>=2050){let r=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Si(Mi.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(t%100).toString().padStart(2,"0"),n=(i.getUTCMonth()+1).toString().padStart(2,"0"),f=i.getUTCDate().toString().padStart(2,"0"),l=i.getUTCHours().toString().padStart(2,"0"),c=i.getUTCMinutes().toString().padStart(2,"0"),u=i.getUTCSeconds().toString().padStart(2,"0"),$=`${r}${n}${f}${l}${c}${u}Z`;return Si(Mi.UTC_TIME,Buffer.from($,"ascii"))}}function wA(i,t){return Ri(R$(i),R$(t))}function S$(i){let t=[];for(let r of i){let n;switch(r.shortName){case"CN":n=mi.COMMON_NAME;break;case"C":n=mi.COUNTRY;break;case"L":n=mi.LOCALITY;break;case"ST":n=mi.STATE;break;case"O":n=mi.ORGANIZATION;break;case"OU":n=mi.ORGANIZATIONAL_UNIT;break;default:continue}let f=r.shortName==="C"?uA(r.value):yA(r.value),l=Ri(Wr(n),f);t.push($A(l))}return Ri(...t)}function Xu(i){return Ri(Wr(i),hA())}function eA(i){return i.export({type:"spki",format:"der"})}function AA(i){if(i.includes(":")){let t=i;if(i.includes("::")){let f=i.split("::"),l=f[0]?f[0].split(":"):[],c=f[1]?f[1].split(":"):[],u=8-l.length-c.length,$=Array.from({length:u},()=>"0");t=[...l,...$,...c].join(":")}let r=t.split(":"),n=Buffer.alloc(16);for(let f=0;f<8;f++){let l=Number.parseInt(r[f]||"0",16);n.writeUInt16BE(l,f*2)}return n}else{let t=i.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(t)}}function sA(i){let t=[];for(let r of i)if(r.type===2&&r.value){let n=Rr(r.value.length);t.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=AA(r.ip),f=Rr(n.length);t.push(Buffer.concat([Buffer.from([135]),f,n]))}else if(r.type===6&&r.value){let n=Rr(r.value.length);t.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return Ri(...t)}function aA(i,t){if(i){if(t!==void 0)return Ri(Si(1,Buffer.from([255])),_l(t));return Ri(Si(1,Buffer.from([255])))}return Ri()}function mA(i){let t=0;if(i.digitalSignature)t|=128;if(i.keyEncipherment)t|=32;if(i.keyCertSign)t|=4;if(i.cRLSign)t|=2;let r=0,n=t;while(n>0&&(n&1)===0)r++,n>>=1;if(t===0)r=7;return Nu(Buffer.from([t]),r)}function EA(i){let t=[];if(i.serverAuth)t.push(Wr(mi.SERVER_AUTH));if(i.clientAuth)t.push(Wr(mi.CLIENT_AUTH));return Ri(...t)}function Cr(i,t,r){let n=[Wr(i)];if(t)n.push(Si(1,Buffer.from([255])));return n.push(Wu(r)),Ri(...n)}function TA(i){let t=[];if(t.push(U$(0,_l(2))),t.push(_l(i.serialNumber)),t.push(Xu(mi.SHA256_WITH_RSA)),t.push(S$(i.issuer)),t.push(wA(i.notBefore,i.notAfter)),t.push(S$(i.subject)),t.push(eA(i.publicKey)),i.extensions){let r=[];if(i.extensions.basicConstraints)r.push(Cr(mi.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,aA(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)r.push(Cr(mi.KEY_USAGE,i.extensions.keyUsage.critical??!0,mA(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)r.push(Cr(mi.EXTENDED_KEY_USAGE,!1,EA(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)r.push(Cr(mi.SUBJECT_ALT_NAME,!1,sA(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)r.push(Cr(mi.SUBJECT_KEY_IDENTIFIER,!1,Wu(i.extensions.subjectKeyIdentifier)));if(r.length>0)t.push(U$(3,Ri(...r)))}return Ri(...t)}function YA(i,t){let r=pt.createSign("SHA256");r.update(i);let n=r.sign(t);return Ri(i,Xu(mi.SHA256_WITH_RSA),Nu(n))}function BA(i,t){let r=i.toString("base64"),n=[];for(let f=0;f<r.length;f+=64)n.push(r.slice(f,f+64));return`-----BEGIN ${t}-----
66
- ${n.join(`
67
- `)}
68
- -----END ${t}-----
69
- `}function bl(){let i=pt.randomBytes(20);return i[0]=i[0]&127||1,i}function Ju(i=2048){let{privateKey:t,publicKey:r}=pt.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:r}}function CA(i){let t=i.export({type:"spki",format:"der"});return pt.createHash("sha1").update(t).digest()}function Iu(i){let t={serialNumber:i.serialNumber||bl(),notBefore:i.notBefore,notAfter:i.notAfter,subject:i.subject,issuer:i.issuer||i.subject,publicKey:i.publicKey,extensions:{basicConstraints:{isCA:i.isCA??!1,critical:!0,pathLenConstraint:i.pathLenConstraint},subjectKeyIdentifier:CA(i.publicKey)}};if(i.keyUsage)t.extensions.keyUsage={...i.keyUsage,critical:!0};if(i.extendedKeyUsage)t.extensions.extendedKeyUsage=i.extendedKeyUsage;if(i.subjectAltName?.length)t.extensions.subjectAltName=i.subjectAltName;let r=TA(t),n=YA(r,i.signingKey);return{certificate:BA(n,"CERTIFICATE"),certificateDer:n}}function _u(i){return i.export({type:"pkcs8",format:"pem"})}function UA(i){return pt.createPrivateKey(i)}function RA(i){let t=new pt.X509Certificate(i),r=t.publicKey,n=[],f=t.subject.split(`
70
- `);for(let l of f){let[c,...u]=l.split("="),$=u.join("=");if(c&&$)n.push({shortName:c.trim(),value:$.trim()})}return{publicKey:r,subject:n}}async function Ql(i={}){U("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Gi.DEFAULT_KEY_SIZE;U("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:r,publicKey:n}=Ju(t),f=[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organization||"Local Development CA"},{shortName:"OU",value:i.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:i.commonName||"Local Development Root CA"}],{notBefore:l,notAfter:c}=Dl({validityYears:i.validityYears||Gi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:u}=Iu({serialNumber:bl(),notBefore:l,notAfter:c,subject:f,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:u,privateKey:_u(r),notBefore:l,notAfter:c}}async function ol(i){if(U("ca","Generating new certificate",i.verbose),U("ca",`Options: ${dn(i)}`,i.verbose),!i.domain&&!i.domains?.length)throw Error("Either domain or domains must be specified");if(!i.rootCA?.certificate||!i.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=RA(i.rootCA.certificate),r=UA(i.rootCA.privateKey);U("ca",`Generating ${Gi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let n=Gi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:l}=Ju(n),c=i.commonName||ju(i),u=i.certificateAttributes||[{shortName:"C",value:i.countryName||v.countryName},{shortName:"ST",value:i.stateName||v.stateName},{shortName:"L",value:i.localityName||v.localityName},{shortName:"O",value:i.organizationName||v.organizationName},{shortName:"CN",value:c}],{notBefore:$,notAfter:y}=Dl({validityDays:i.validityDays||Gi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),h=Fu(i),w=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},e=i.extKeyUsage||{serverAuth:!0},{certificate:A}=Iu({serialNumber:bl(),notBefore:$,notAfter:y,subject:u,issuer:t,publicKey:l,signingKey:r,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:w,extendedKeyUsage:e,subjectAltName:h});return{certificate:A,privateKey:_u(f),notBefore:$,notAfter:y}}function Ku(i,t){U(S.STORAGE,`Storing certificate and private key with options: ${dn(t)}`,t?.verbose);let{certPath:r,keyPath:n}=Vl({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});U(S.STORAGE,`Certificate path: ${r}`,t?.verbose),U(S.STORAGE,`Private key path: ${n}`,t?.verbose);let f=Kl.dirname(r);if(!it.existsSync(f))U(S.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),it.mkdirSync(f,{recursive:!0});U(S.STORAGE,"Writing certificate file",t?.verbose),it.writeFileSync(r,i.certificate);let l=Kl.dirname(n);if(!it.existsSync(l))U(S.STORAGE,`Creating private key directory: ${l}`,t?.verbose),it.mkdirSync(l,{recursive:!0});return U(S.STORAGE,"Writing private key file",t?.verbose),it.writeFileSync(n,i.privateKey),U(S.STORAGE,"Certificate and private key stored successfully",t?.verbose),r}function zu(i,t){U(S.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:r}=Vl({basePath:t?.basePath,caCertPath:t?.caCertPath});U(S.STORAGE,`CA certificate path: ${r}`,t?.verbose);let n=Kl.dirname(r);if(!it.existsSync(n))U(S.STORAGE,`Creating CA certificate directory: ${n}`,t?.verbose),it.mkdirSync(n,{recursive:!0});return U(S.STORAGE,"Writing CA certificate file",t?.verbose),it.writeFileSync(r,i),U(S.STORAGE,"CA certificate stored successfully",t?.verbose),r}function gn(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=Ru(i);return new SA.X509Certificate(t)}function qn(i){return gn(i).fingerprint256.replace(/:/g,"").toUpperCase()}function Pl(i){return Ou(gn(i).subject)}function vl(i,t,r=443,n=4000){let f;try{f=t.includes("-----BEGIN")?t:jA.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((l)=>{let c=!1,u=(y)=>{if(c)return;c=!0,l(y)},$=FA.connect({host:i,port:r,servername:i,ca:f,rejectUnauthorized:!0},()=>{u($.authorized),$.end()});$.setTimeout(n,()=>{$.destroy(),u(!1)}),$.on("error",()=>u(!1))})}function NA(i){let t=[],r=i.split(`
71
- `);for(let n of r){let[f,...l]=n.split("="),c=l.join("=");if(f&&c)t.push({shortName:f.trim(),value:c.trim()})}return t}function Ou(i){return NA(i).find((t)=>t.shortName==="CN")?.value||""}function WA(i){let t=[],r=Ou(i.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))t.push(r);let n=i.subjectAltName;if(n){let f=n.split(", ");for(let l of f)if(l.startsWith("DNS:"))t.push(l.slice(4))}return[...new Set(t)]}function Zl(i,t){let r=gn(i),n=WA(r);for(let f of n){if(f===t)return!0;if(f.startsWith("*.")){let l=f.slice(2);if(t.endsWith(l)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function JA(i,t){if(Kn.platform()!=="darwin")return!1;try{let r=qn(i);if(!r)return U(S.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(XA("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
72
- `).some((n)=>{let f=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===r}))return U(S.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return U(S.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(r){return U(S.TRUST,`Error checking certificate trust: ${r}`,t),!1}}var IA={platform:"darwin",async addCertificate(i,t){if(await JA(i,t?.verbose)){U(S.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),Pt.success("Certificate is already trusted in system keychain");return}U(S.TRUST,"Adding certificate to macOS keychain",t?.verbose),await st(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,r){let n=r||v.commonName;U(S.TRUST,`Removing certificate ${n} from macOS keychain`,t?.verbose);try{await st(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),U(S.TRUST,`Removed certificate ${n} from macOS keychain`,t?.verbose)}catch(f){throw U(S.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},_A={platform:"win32",async addCertificate(i,t){U(S.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await st(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,r){let n=r||v.commonName;U(S.TRUST,`Removing certificate ${n} from Windows certificate store`,t?.verbose);try{await st(`certutil -delstore -enterprise Root "${n}"`),U(S.TRUST,`Removed certificate ${n} from Windows certificate store`,t?.verbose)}catch(f){throw U(S.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},KA={platform:"linux",async addCertificate(i,t){U(S.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let r=Kn.homedir(),n=Gi.LINUX_CERT_DB_FILENAME,f=Gi.LINUX_TRUST_ARGS;U(S.TRUST,`Searching for certificate databases in ${r}`,t?.verbose);let l=Il(r,n);if(l.length===0){Pt.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of l){U(S.TRUST,`Processing certificate database in ${c}`,t?.verbose);try{U(S.TRUST,`Attempting to delete existing cert for ${v.commonName}`,t?.verbose),await st(`certutil -d sql:${c} -D -n ${v.commonName}`)}catch(u){U(S.TRUST,`Warning: Error deleting existing cert: ${u}`,t?.verbose),console.warn(`Error deleting existing cert: ${u}`)}U(S.TRUST,`Adding new certificate to ${c}`,t?.verbose),await st(`certutil -d sql:${c} -A -t ${f} -n ${v.commonName} -i ${i}`),Pt.info(`Cert added to ${c}`)}},async removeCertificate(i,t,r){let n=r||v.commonName;U(S.TRUST,`Removing certificate ${n} from Linux certificate store`,t?.verbose);let f=Kn.homedir(),l=Gi.LINUX_CERT_DB_FILENAME;U(S.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let c=Il(f,l);if(c.length===0){Pt.warn("No certificate databases found. Cannot remove certificate.");return}for(let u of c){U(S.TRUST,`Processing certificate database in ${u}`,t?.verbose);try{await st(`certutil -d sql:${u} -D -n "${n}"`),Pt.info(`Cert removed from ${u}`)}catch($){U(S.TRUST,`Error removing cert from ${u}: ${$}`,t?.verbose),console.warn(`Error removing cert from ${u}: ${$}`)}}}},zA={darwin:IA,win32:_A,linux:KA};async function pl(i,t,r){U(S.TRUST,`Adding certificate to system trust store with options: ${dn(r)}`,r?.verbose),U(S.TRUST,"Storing certificate and private key",r?.verbose);let n=Ku(i,r);U(S.TRUST,"Storing CA certificate",r?.verbose);let f=zu(t,r),l=Kn.platform();U(S.TRUST,`Detected platform: ${l}`,r?.verbose);let c=zA[l];if(!c){let u=`Unsupported platform: ${l}`;throw U(S.TRUST,`Error: ${u}`,r?.verbose),Error(u)}return await c.addCertificate(f,r),U(S.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as qc}from"node:os";import{join as Lc,resolve as EU}from"node:path";import{existsSync as Gu,statSync as Mu}from"fs";import{existsSync as OA,mkdirSync as IB,readdirSync as _B,readFileSync as GA,writeFileSync as KB}from"fs";import{homedir as ir}from"os";import{dirname as GB,resolve as Ji}from"path";import Uf from"process";import{existsSync as Hu,statSync as du}from"fs";import{existsSync as Yc,mkdirSync as MA,readdirSync as HA,writeFileSync as dA}from"fs";import{homedir as tr}from"os";import{dirname as gu,resolve as Ti}from"path";import Jt from"process";import{join as gA,relative as qA,resolve as qu}from"path";import yf from"process";import{existsSync as Sy,mkdirSync as DB,readdirSync as bB,writeFileSync as QB}from"fs";import{homedir as ic}from"os";import{dirname as vB,resolve as Ei}from"path";import Ir from"process";import{join as LA,relative as xA,resolve as Lu}from"path";import hf from"process";import{existsSync as jy,mkdirSync as rC,readdirSync as nC,writeFileSync as fC}from"fs";import{dirname as cC,resolve as wf}from"path";import Bc from"process";import{Buffer as Et}from"buffer";import{createCipheriv as kA,createDecipheriv as VA,randomBytes as tc}from"crypto";import{closeSync as rc,createReadStream as xu,createWriteStream as DA,existsSync as nc,fsyncSync as ku,openSync as Vu,writeFileSync as bA}from"fs";import{access as QA,constants as Du,mkdir as oA,readdir as Ln,rename as bu,stat as rr,unlink as xn,writeFile as fc}from"fs/promises";import{join as nr}from"path";import hi from"process";import{pipeline as PA}from"stream/promises";import{createGzip as Qu}from"zlib";import fr from"process";import lt from"process";import{Buffer as rt}from"buffer";import{createCipheriv as vA,createDecipheriv as ZA,randomBytes as lc}from"crypto";import{closeSync as cc,createReadStream as ou,createWriteStream as pA,existsSync as kn,fsyncSync as Pu,openSync as vu,writeFileSync as is}from"fs";import{access as ts,constants as Zu,mkdir as rs,readdir as Vn,rename as pu,stat as lr,unlink as Dn,writeFile as $c}from"fs/promises";import{isAbsolute as ns,join as cr,resolve as fs}from"path";import I from"process";import{pipeline as ls}from"stream/promises";import{createGzip as iy}from"zlib";import $r from"process";import ct from"process";import bn from"process";import{existsSync as Qn}from"fs";import{resolve as uc}from"path";import{existsSync as cs}from"fs";import{existsSync as $s,readdirSync as us}from"fs";import{extname as yc,resolve as ty}from"path";import ys from"process";import{join as hs,relative as ws,resolve as ry}from"path";import ef from"process";import{Buffer as nt}from"buffer";import{createCipheriv as es,createDecipheriv as As,randomBytes as hc}from"crypto";import{closeSync as wc,createReadStream as ny,createWriteStream as ss,existsSync as on,fsyncSync as fy,openSync as ly,writeFileSync as as}from"fs";import{access as ms,constants as cy,mkdir as Es,readdir as Pn,rename as $y,stat as ur,unlink as vn,writeFile as ec}from"fs/promises";import{isAbsolute as Ts,join as yr,resolve as Ys}from"path";import _ from"process";import{pipeline as Bs}from"stream/promises";import{createGzip as uy}from"zlib";import hr from"process";import $t from"process";import pn from"process";import{existsSync as tf}from"fs";import{resolve as Tc}from"path";import{existsSync as ga}from"fs";class Uy{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),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(i,t){try{if(!Gu(i))return!0;return Mu(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=Gu(r)?Mu(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Ry{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var uf=new Uy,Ic=new Ry;var Cs=Object.defineProperty,Us=(i)=>i;function Rs(i,t){this[i]=Us.bind(null,t)}var Ss=(i,t)=>{for(var r in t)Cs(i,r,{get:t[r],enumerable:!0,configurable:!0,set:Rs.bind(t,r)})},js=(i,t)=>()=>(i&&(t=i(i=0)),t),Fy={};Ss(Fy,{withErrorRecovery:()=>Xy,tryLoadConfig:()=>Qs,loadConfigWithResult:()=>Ds,loadConfig:()=>zy,isRetryableError:()=>gs,isConfigNotFoundError:()=>ds,isBunfigError:()=>Jy,globalPerformanceMonitor:()=>zr,globalCache:()=>wr,getEnvOrDefault:()=>qs,generateConfigTypes:()=>os,defaultGeneratedDir:()=>Ly,defaultConfigDir:()=>qy,deepMergeWithArrayStrategy:()=>Gc,deepMerge:()=>Iy,createLibraryConfig:()=>Ps,config:()=>bs,bunfigPlugin:()=>vs,applyEnvVarsToConfig:()=>Jr,TypeGenerationError:()=>Nc,SchemaValidationError:()=>Kr,PluginError:()=>Xc,PerformanceMonitor:()=>Kc,FileSystemError:()=>Fc,ErrorFactory:()=>Tt,EnvVarError:()=>Tf,EnvProcessor:()=>Rf,ConfigValidator:()=>Mc,ConfigValidationError:()=>Sc,ConfigNotFoundError:()=>Ef,ConfigMergeError:()=>jc,ConfigLoader:()=>Hc,ConfigLoadError:()=>_r,ConfigFileLoader:()=>Sf,ConfigCache:()=>_c,CacheUtils:()=>Gy,BunfigError:()=>ji,BrowserConfigError:()=>Wc,ArrayMergeStrategies:()=>dy});class _c{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${r}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(i[r][0])}set(i,t,r,n){if(!this.options.enabled)return;let f=this.generateKey(i,r),l=n??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(i,t),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(i,t){try{if(!Hu(i))return!0;return du(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let r=this.get(i,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(i,t);return}return r.value}setWithFileCheck(i,t,r,n){try{let f=Hu(r)?du(r):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},r,n)}catch{this.set(i,t,r,n)}}delete(i,t){let r=this.generateKey(i,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((n,f)=>n+f.size,0),r=i.map((n)=>n.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let i={};for(let[t,r]of this.cache.entries())i[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return i}import(i){this.cache.clear();for(let[t,r]of Object.entries(i))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(t,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Kc{metrics=[];maxMetrics=1000;async track(i,t,r={}){let n=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-n;return this.recordMetric({operation:i,duration:c,timestamp:f,...r}),l}catch(l){let c=performance.now()-n;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...r}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((f)=>f.duration),n=r.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:n/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function Fs(i,t={}){let n=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return n?`${i}:${n}`:i}function Ns(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function Ws(i){return i.getStats().size*2}function zc(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&D(t[0])&&"id"in t[0]&&t[0].id===3&&D(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(D(t)&&D(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(D(i)&&"arr"in i&&Array.isArray(i.arr)&&D(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&D(t[0])&&D(i[0])){let n=[...t];for(let f of i)if(D(f)&&"name"in f){if(!n.find((c)=>D(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(D(f)&&"path"in f){if(!n.find((c)=>D(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((l)=>Af(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!D(t)||!D(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(D(f)&&D(r[n]))r[n]=zc(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&D(f[0])&&D(r[n][0])){let l=[...f];for(let c of r[n])if(D(c)&&"name"in c){if(!l.find(($)=>D($)&&("name"in $)&&$.name===c.name))l.push(c)}else if(D(c)&&"path"in c){if(!l.find(($)=>D($)&&("path"in $)&&$.path===c.path))l.push(c)}else if(!l.some((u)=>Af(u,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function Af(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Af(i[r],t[r]))return!1;return!0}if(D(i)&&D(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Af(i[f],t[f]))return!1}return!0}return!1}function D(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Xs(i,t){if(!jy(i))return null;try{let r=await import(i),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return zc(t,n)}catch{return null}}catch{return null}}async function Js({name:i="",cwd:t,defaultConfig:r}){let n=t||Bc.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],l=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of l)for(let u of f){let $=wf(n,`${c}${u}`),y=await Xs($,r);if(y!==null)return y}try{let c=wf(n,"package.json");if(jy(c)){let $=(await import(c))[i];if($&&typeof $==="object"&&!Array.isArray($))try{return zc(r,$)}catch{}}}catch{}return r}function Is(i,t={}){let r=hf.cwd();while(r.includes("storage"))r=Lu(r,"..");let n=Lu(r,i||"");if(t?.relative)return xA(hf.cwd(),n);return n}async function _s(){try{let i=await Js({name:"clarity",defaultConfig:ff,cwd:hf.cwd(),endpoint:"",headers:{}});return{...ff,...i}}catch{return ff}}function o(){if(lt.env.NODE_ENV==="test"||lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Ks(){if(lt.env.NODE_ENV==="test"||lt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof lt<"u"){let i=lt.type;if(i==="renderer"||i==="worker")return!1;return!!(lt.versions&&(lt.versions.node||lt.versions.bun))}return!1}class Ny{async format(i){let t=await Ks(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:fr.pid,hostname:t(),environment:fr.env.NODE_ENV||"development",platform:fr.platform,version:fr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:fr.env.NODE_ENV||fr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class sf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Uc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ny,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??hi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.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 f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...lf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...lf};return{...lf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Uc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(i){let r=(async()=>{let f,l=0,c=3,u=1000;while(l<c)try{try{try{await QA(this.config.logDirectory,Du.F_OK|Du.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await oA(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Et.from(i);try{if(!nc(this.currentLogFile))await fc(this.currentLogFile,"",{mode:420});if(f=Vu(this.currentLogFile,"a",420),bA(f,$,{flag:"a"}),ku(f),f!==void 0)rc(f),f=void 0;if((await rr(this.currentLogFile)).size===0){if(await fc(this.currentLogFile,$,{flag:"w",mode:420}),(await rr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let h=y;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(l<c-1){let w=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,w);let e=u*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{rc(f)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch($){if(l===c-1){let h=$,w=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),$}l++;let y=u*2**(l-1);await new Promise((h)=>setTimeout(h,y))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 nr(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 nr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return nr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(o())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=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 f=Array.from(this.encryptionKeys.entries()).sort(([,u],[,$])=>$.createdAt.getTime()-u.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[u]of f.slice(c))this.encryptionKeys.delete(u),this.keys.delete(u)}generateKeyId(){return tc(16).toString("hex")}generateKey(){return tc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=tc(16),n=kA("aes-256-gcm",t,r),f=Et.concat([n.update(i,"utf8"),n.final()]),l=n.getAuthTag();return{encrypted:Et.concat([r,f,l]),iv:r}}async compressData(i){return new Promise((t,r)=>{let n=Qu(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(Et.from(Et.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(o())return;let i=await rr(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ln(this.config.logDirectory),l=f.filter(($)=>$.startsWith(this.name)&&/\.log\.\d+$/.test($)).sort(($,y)=>{let h=Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,u=`${r}.${c}`;if(await rr(r).catch(()=>null))try{if(await bu(r,u),t.compress)try{let $=`${u}.gz`;await this.compressLogFile(u,$),await xn(u)}catch($){console.error("Error compressing rotated file:",$)}if(l.length===0&&!f.some(($)=>$.endsWith(".log.1")))try{let $=`${r}.1`;await fc($,"")}catch($){console.error("Error creating backup file:",$)}}catch($){console.error(`Error during rotation: ${$ instanceof Error?$.message:String($)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await rr(r).catch(()=>null))await bu(r,l)}if(this.currentLogFile=n,t.maxFiles){let l=(await Ln(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,u)=>u.localeCompare(c));for(let c of l.slice(t.maxFiles))await xn(nr(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=xu(i),n=DA(t),f=Qu();await PA(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!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(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),nc(this.currentLogFile))try{let i=Vu(this.currentLogFile,"r+");ku(i),rc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!o()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Ln(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await xn(nr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?x.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,u=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let $=hi.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${x.cyan(f)}`;if(!c)return y.trim();let h=u(y).trim().length,w=u(t).length,e=Math.max(1,$-2-h-w);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let u=Number.parseInt(c,10);return u<t[0].length?String(t[0][u]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let u=t[n++];switch(c){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 l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,u;if(t instanceof Error)c=t.message,u=t.stack;else c=this.formatMessage(t,r);if(this.fancy&&!o()){let y=My[i],h=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",w;switch(i){case"debug":w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:x.gray(c),level:i}),console.error(w);break;case"info":w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.error(w);break;case"success":w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:x.green(c),level:i}),console.error(w);break;case"warning":w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.warn(w);break;case"error":if(w=this.formatConsoleMessage({timestamp:f,icon:y,tag:h,message:c,level:i}),console.error(w),u){let e=u.split(`
73
- `);for(let A of e)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:x.gray(` ${A}`),level:i,showTimestamp:!1}))}break}}else if(!o()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),u)console.error(u)}if(!this.shouldLog(i))return;let $=`${l} ${this.environment}.${i.toUpperCase()}: ${c}
74
- `;if(u)$+=`${u}
75
- `;$=$.replace(this.ANSI_PATTERN,""),await this.writeToFile($)}time(i){let t=performance.now();if(this.fancy&&!o()){let r=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:x.blue("◐"),tag:r,message:`${x.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,u=this.formatConsoleTimestamp(c),y=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
76
- `,y=y.replace(this.ANSI_PATTERN,""),this.fancy&&!o()){let h=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:u,icon:x.green("✓"),tag:h,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!o())console.error(y.trim());await this.writeToFile(y)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new sf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(o())throw Error("createReadStream is not supported in browser environments");if(!nc(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xu(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Et.isBuffer(i)?i:Et.from(i,"base64"),f=n.slice(0,16),l=n.slice(-16),c=n.slice(16,-16),u=VA("aes-256-gcm",r,f);return u.setAuthTag(l),Et.concat([u.update(c),u.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 o()}isServerMode(){return!o()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t);if(this.fancy&&!o()){let l=i.split(`
77
- `),c=Math.max(...l.map((h)=>h.length))+2,u=`┌${"─".repeat(c)}┐`,$=`└${"─".repeat(c)}┘`,y=l.map((h)=>{let w=" ".repeat(c-h.length-2);return`│ ${h}${w} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:x.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(u)})),y.forEach((h)=>console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan(h),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:x.cyan($),showTimestamp:!1}))}else if(!o())console.error(`${n} ${this.environment}.INFO: [BOX] ${i}`);let f=`${n} ${this.environment}.INFO: [BOX] ${i}
78
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(o())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${x.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();hi.stdin.removeListener("data",r);try{if(typeof hi.stdin.setRawMode==="function")hi.stdin.setRawMode(!1)}catch{}hi.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof hi.stdin.setRawMode==="function")hi.stdin.setRawMode(!0)}catch{}hi.stdin.resume(),hi.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,u=0;if(r=i.replace(c,($,y)=>{if(y==="%")return"%";if(u>=t.length)return $;let h=t[u++];switch(y){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return $}}),u<t.length)r+=` ${t.slice(u).map(($)=>typeof $==="object"?JSON.stringify($,null,2):String($)).join(" ")}`}if(this.fancy&&!o()){let c=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",u=x.blue("◐");console.error(`${u} ${c} ${x.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
79
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(l)}progress(i,t=""){if(!this.enabled||!this.fancy||o()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,u)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,c)),u!==void 0)this.activeProgressBar.message=u;let $=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,$)},finish:(c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;if(this.activeProgressBar.current=this.activeProgressBar.total,c!==void 0)this.activeProgressBar.message=c;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(c,u="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||o())return;hi.stdout.write(`${"\r".padEnd(hi.stdout.columns||80)}\r`),this.log(u,c),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||o()||!hi.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=x.green("━".repeat(n)),c=x.gray("━".repeat(f)),u=`[${l}${c}]`,$=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=t||r===100?x.green("✓"):x.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",e=`\r${h}${w} ${u} ${$}${y}`,A=hi.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,hi.stdout.write(i.lastRenderedLine),t)hi.stdout.write(`
80
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||o()||!hi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(o()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ln(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let l=nr(this.config.logDirectory,n);if(i.before)try{if((await rr(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}r.push(l)}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(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function nf(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&q(t[0])&&"id"in t[0]&&t[0].id===3&&q(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(q(t)&&q(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(q(i)&&"arr"in i&&Array.isArray(i.arr)&&q(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&q(t[0])&&q(i[0])){let n=[...t];for(let f of i)if(q(f)&&"name"in f){if(!n.find((c)=>q(c)&&("name"in c)&&c.name===f.name))n.push(f)}else if(q(f)&&"path"in f){if(!n.find((c)=>q(c)&&("path"in c)&&c.path===f.path))n.push(f)}else if(!n.some((l)=>af(l,f)))n.push(f);return n}if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}if(!q(t)||!q(i))return t;let r={...i};for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let f=t[n];if(f===null||f===void 0)continue;else if(q(f)&&q(r[n]))r[n]=nf(r[n],f);else if(Array.isArray(f)&&Array.isArray(r[n]))if(f.length>0&&r[n].length>0&&q(f[0])&&q(r[n][0])){let l=[...f];for(let c of r[n])if(q(c)&&"name"in c){if(!l.find(($)=>q($)&&("name"in $)&&$.name===c.name))l.push(c)}else if(q(c)&&"path"in c){if(!l.find(($)=>q($)&&("path"in $)&&$.path===c.path))l.push(c)}else if(!l.some((u)=>af(u,c)))l.push(c);r[n]=l}else if(f.every((l)=>typeof l==="string")&&r[n].every((l)=>typeof l==="string")){let l=[...f];for(let c of r[n])if(!l.includes(c))l.push(c);r[n]=l}else r[n]=f;else r[n]=f}return r}function Oc(i,t,r="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return r==="replace"?t:nf(i,t);if(Array.isArray(i))return r==="replace"?t:nf(i,t);if(!q(t)||!q(i))return t;let n={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let l=t[f],c=n[f];if(l===null||l===void 0)continue;if(Array.isArray(l)||Array.isArray(c))if(r==="replace")n[f]=l;else n[f]=nf(c,l);else if(q(l)&&q(c))n[f]=Oc(c,l,r);else n[f]=l}return n}function af(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!af(i[r],t[r]))return!1;return!0}if(q(i)&&q(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!af(i[f],t[f]))return!1}return!0}return!1}function q(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Zn(i,t,r="replace"){if(!Sy(i))return null;try{let n=await import(i),f=n.default||n;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return Oc(t,f,r)}catch{return null}}catch{return null}}function zs(i,t,r=!1){if(!i)return t;let n=i.toUpperCase().replace(/-/g,"_"),f={...t};function l(c,u=[]){let $={...c};for(let[y,h]of Object.entries(c)){let w=[...u,y],e=(s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase(),A=`${n}_${w.map(e).join("_")}`,m=`${n}_${w.map((s)=>s.toUpperCase()).join("_")}`;if(r)ei.info(`Checking environment variable ${A} for config ${i}.${w.join(".")}`);if(typeof h==="object"&&h!==null&&!Array.isArray(h))$[y]=l(h,w);else{let s=Ir.env[A]||Ir.env[m];if(s!==void 0){if(r)ei.info(`Using environment variable ${s?A:m} for config ${i}.${w.join(".")}`);if(typeof h==="number")$[y]=Number(s);else if(typeof h==="boolean")$[y]=s.toLowerCase()==="true";else if(Array.isArray(h))try{let E=JSON.parse(s);if(Array.isArray(E))$[y]=E;else $[y]=s.split(",").map((T)=>T.trim())}catch{$[y]=s.split(",").map((E)=>E.trim())}else $[y]=s}}}return $}return l(f)}async function Os({name:i="",alias:t,cwd:r,configDir:n,defaultConfig:f,verbose:l=!1,checkEnv:c=!0,arrayStrategy:u="replace"}){let $=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?zs(i,f,l):f,y=r||Ir.cwd(),h=[".ts",".js",".mjs",".cjs",".json"];if(l)ei.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${y}`);let w=[i,`.${i}`].filter(Boolean),e=[`${i}.config`,`.${i}.config`].filter(Boolean),A=t?[t,`.${t}`]:[],m=t?[`${t}.config`,`.${t}.config`]:[],s=Array.from(new Set([y,Ei(y,"config"),Ei(y,".config"),n?Ei(y,n):void 0].filter(Boolean)));for(let E of s){if(l)ei.info(`Searching for configuration in: ${E}`);let B=[Ei(y,"config"),Ei(y,".config")].concat(n?[Ei(y,n)]:[]).includes(E)?[...w,...e,...A,...m]:[...e,...w,...m,...A];for(let F of B)for(let N of h){let R=Ei(E,`${F}${N}`),W=await Zn(R,$,u);if(W!==null){if(l)ei.success(`Configuration loaded from: ${R}`);return W}}}if(i){let E=Ei(ic(),".config",i),T=["config",`${i}.config`];if(t)T.push(`${t}.config`);if(l)ei.info(`Checking user config directory: ${E}`);for(let B of T)for(let F of h){let N=Ei(E,`${B}${F}`),R=await Zn(N,$,u);if(R!==null){if(l)ei.success(`Configuration loaded from user config directory: ${N}`);return R}}}if(i){let E=Ei(ic(),".config"),T=[`.${i}.config`];if(t)T.push(`.${t}.config`);if(l)ei.info(`Checking user config directory for dotfile configs: ${E}`);for(let B of T)for(let F of h){let N=Ei(E,`${B}${F}`),R=await Zn(N,$,u);if(R!==null){if(l)ei.success(`Configuration loaded from user config directory dotfile: ${N}`);return R}}}if(i){let E=ic(),T=[`.${i}.config`,`.${i}`];if(t)T.push(`.${t}.config`),T.push(`.${t}`);if(l)ei.info(`Checking user home directory for dotfile configs: ${E}`);for(let B of T)for(let F of h){let N=Ei(E,`${B}${F}`),R=await Zn(N,$,u);if(R!==null){if(l)ei.success(`Configuration loaded from user home directory: ${N}`);return R}}}try{let E=Ei(y,"package.json");if(Sy(E)){let T=await import(E),B=T[i];if(!B&&t){if(B=T[t],B&&l)ei.success(`Using alias "${t}" configuration from package.json`)}if(B&&typeof B==="object"&&!Array.isArray(B))try{if(l)ei.success(`Configuration loaded from package.json: ${B===T[i]?i:t}`);return Oc($,B,u)}catch(F){if(l)ei.warn("Failed to merge package.json config:",F)}}}catch(E){if(l)ei.warn("Failed to load package.json:",E)}if(l)ei.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return $}function Gs(i,t={}){let r=yf.cwd();while(r.includes("storage"))r=qu(r,"..");let n=qu(r,i||"");if(t?.relative)return qA(yf.cwd(),n);return n}async function Ms(){try{let i=await Os({name:"clarity",alias:"logging",defaultConfig:cf,cwd:yf.cwd()});return{...cf,...i||{}}}catch{return cf}}function ti(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Hs(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ct<"u"){let i=ct.type;if(i==="renderer"||i==="worker")return!1;return!!(ct.versions&&(ct.versions.node||ct.versions.bun))}return!1}class Wy{async format(i){let t=await Hs(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:$r.pid,hostname:t(),environment:$r.env.NODE_ENV||"development",platform:$r.platform,version:$r.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$r.env.NODE_ENV||$r.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Rc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Wy,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.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 f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...$f,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...$f};return{...$f,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Rc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,l=0,c=3,u=1000;while(l<c)try{try{try{await ts(this.config.logDirectory,Zu.F_OK|Zu.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await rs(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:rt.from(i);try{if(!kn(this.currentLogFile))await $c(this.currentLogFile,"",{mode:420});if(f=vu(this.currentLogFile,"a",420),is(f,$,{flag:"a"}),Pu(f),f!==void 0)cc(f),f=void 0;if((await lr(this.currentLogFile)).size===0){if(await $c(this.currentLogFile,$,{flag:"w",mode:420}),(await lr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let h=y;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(l<c-1){let w=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,w);let e=u*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{cc(f)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch($){if(l===c-1){let h=$,w=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),$}l++;let y=u*2**(l-1);await new Promise((h)=>setTimeout(h,y))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 cr(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 cr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return cr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ti())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=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 f=Array.from(this.encryptionKeys.entries()).sort(([,u],[,$])=>$.createdAt.getTime()-u.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[u]of f.slice(c))this.encryptionKeys.delete(u),this.keys.delete(u)}generateKeyId(){return lc(16).toString("hex")}generateKey(){return lc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=lc(16),n=vA("aes-256-gcm",t,r),f=rt.isBuffer(i)?i:rt.from(i,"utf8"),l=n.update(f),c=n.final(),u=l.length+c.length,$=n.getAuthTag(),y=rt.allocUnsafe(16+u+16);return r.copy(y,0),l.copy(y,16),c.copy(y,16+l.length),$.copy(y,16+u),{encrypted:y,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=iy(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(rt.from(rt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await lr(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Vn(this.config.logDirectory),l=f.filter(($)=>$.startsWith(this.name)&&/\.log\.\d+$/.test($)).sort(($,y)=>{let h=Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,u=`${r}.${c}`;if(await lr(r).catch(()=>null))try{if(await pu(r,u),t.compress)try{let $=`${u}.gz`;await this.compressLogFile(u,$),await Dn(u)}catch($){console.error("Error compressing rotated file:",$)}if(l.length===0&&!f.some(($)=>$.endsWith(".log.1")))try{let $=`${r}.1`;await $c($,"")}catch($){console.error("Error creating backup file:",$)}}catch($){console.error(`Error during rotation: ${$ instanceof Error?$.message:String($)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await lr(r).catch(()=>null))await pu(r,l)}if(this.currentLogFile=n,t.maxFiles){let l=(await Vn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,u)=>u.localeCompare(c));for(let c of l.slice(t.maxFiles))await Dn(cr(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=ou(i),n=pA(t),f=iy();await ls(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!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(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),kn(this.currentLogFile))try{let i=vu(this.currentLogFile,"r+");Pu(i),cc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ti()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Vn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Dn(cr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?z.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ti())return!1;let i=typeof I.env.NO_COLOR<"u",t=I.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,u=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let $=I.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${z.cyan(f)}`;if(!c)return y.trim();let h=u(y).trim().length,w=u(t).length,e=Math.max(1,$-2-h-w);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let u=Number.parseInt(c,10);return u<t[0].length?String(t[0][u]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let u=t[n++];switch(c){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 l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=z.underline(z.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let u=`file://${encodeURI(c)}`,$="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${u}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>z.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>z.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>z.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>z.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>z.strikethrough(n)),t}supportsHyperlinks(){if(ti())return!1;let i=I.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=I.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ns(t)||t.startsWith("./")||t.startsWith("../"))t=fs(t);else return null;return kn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,u;if(t instanceof Error)c=t.message,u=t.stack;else c=this.formatMessage(t,r);let{consoleText:$,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":Hy[i],e=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:z.gray($),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:z.green($),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.error(A),u){let m=u.split(`
81
- `);for(let s of m)if(s.trim()&&!s.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:z.gray(` ${s}`),level:i,showTimestamp:!1}))}break}}else if(!ti()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),u)console.error(u)}if(!this.shouldLog(i))return;let h=`${l} ${this.environment}.${i.toUpperCase()}: ${y}
82
- `;if(u)h+=`${u}
83
- `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(u,$)=>{},finish:(u)=>{},interrupt:(u,$)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ti()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(u,$)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,u),this.activeProgressBar.total),$!==void 0)this.activeProgressBar.message=$;if(this.shouldStyleConsole()&&!ti()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(u)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,u)},interrupt:(u,$="info")=>{if(!ti()&&I.stdout.isTTY)I.stdout.write(`
84
- `);if(this[$==="warning"?"warn":$](u),this.activeProgressBar&&this.shouldStyleConsole()&&!ti()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":z.blue("◐"),tag:r,message:`${z.cyan(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,u=this.formatConsoleTimestamp(c),y=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
85
- `,y=y.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:u,icon:this.options.showIcons===!1?"":z.green("✓"),tag:h,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ti())console.error(y.trim());if(this.shouldWriteToFile())await this.writeToFile(y)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new mf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!kn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ou(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=rt.isBuffer(i)?i:rt.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),u=ZA("aes-256-gcm",r,f);u.setAuthTag(l);let $=u.update(c),y=u.final(),h=$.length+y.length,w=rt.allocUnsafe(h);return $.copy(w,0),y.copy(w,$.length),w.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 ti()}isServerMode(){return!ti()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let u=f.split(`
86
- `),$=Math.max(...u.map((e)=>e.length))+2,y=`┌${"─".repeat($)}┐`,h=`└${"─".repeat($)}┘`,w=u.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:z.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(y),showTimestamp:!1})),w.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(h),showTimestamp:!1}))}else if(!ti())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
87
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ti())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${z.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();I.stdin.removeListener("data",r);try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!1)}catch{}I.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!0)}catch{}I.stdin.resume(),I.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let $=/%([sdijfo%])/g,y=0;if(r=i.replace($,(h,w)=>{if(w==="%")return"%";if(y>=t.length)return h;let e=t[y++];switch(w){case"s":return String(e);case"d":case"i":return Number(e).toString();case"j":case"o":return JSON.stringify(e,null,2);default:return h}}),y<t.length)r+=` ${t.slice(y).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${z.blue("◐")} `;console.error(`${y}${$} ${z.cyan(n)}`)}let u=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
88
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(u)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=z.green("━".repeat(n)),c=z.gray("━".repeat(f)),u=`[${l}${c}]`,$=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===100?z.green("✓"):z.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",e=`\r${h}${w} ${u} ${$}${y}`,A=I.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,I.stdout.write(i.lastRenderedLine),t)I.stdout.write(`
89
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ti()||!I.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ti()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Vn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let l=cr(this.config.logDirectory,n);if(i.before)try{if((await lr(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}r.push(l)}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 Dn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Xy(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let u=0;u<=r;u++)try{return await i()}catch($){if(c=$ instanceof Error?$:Error(String($)),u===r||!f(c))break;if(n>0)await new Promise((y)=>setTimeout(y,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function Jy(i){return i instanceof ji}function ds(i){return i instanceof Ef}function gs(i){if(Jy(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>i.message.toLowerCase().includes(r.toLowerCase()))}class Rf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:u=!1,trackPerformance:$=!0}=r,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),w={...t};return this.processObject(w,[],h,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:u,configName:i}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if($)return zr.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],u=c.map((h)=>this.formatEnvKey(h,n.useCamelCase)),$=`${r}_${u.join("_")}`,y=n.useBackwardCompatibility?`${r}_${c.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let h=bn.env[$]||(y?bn.env[y]:void 0);if(h!==void 0){if(n.verbose){let w=bn.env[$]?$:y}try{i[f]=this.parseEnvironmentValue(h,typeof l,$,n.customParsers,n.configName)}catch(w){if(w instanceof Tf)throw w;throw Tt.envVar($,h,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw Tt.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(bn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],u=`${r}_${c.map(($)=>this.formatEnvKey($,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:u,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
90
-
91
- `;for(let n of i)r+=`${n.key}
92
- `,r+=` Type: ${n.type}
93
- `,r+=` Description: ${n.description}
94
- `,r+=` Example: ${n.example}
95
-
96
- `;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
97
-
98
- `;r+=`| Variable | Type | Description | Example |
99
- `,r+=`|----------|------|-------------|----------|
100
- `;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
101
- `;return r}}function qs(i,t){let r=Oy("process");if(typeof r>"u"||!r.env)return t;let n=r.env[i];return n!==void 0?n:t}function Iy(i,t,r={}){return _y(i,t,r,new WeakMap)}function _y(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let u=c(i,t);if(u!==void 0)return u}if(Array.isArray(t)||Array.isArray(i))return Ky(i,t,f,n);if(!Ii(t)||!Ii(i))return t;return Vs(i,t,r,n)}function Ky(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return Ls(i,t);case"smart":return xs(i,t,n);default:return t}return t}function Ls(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Cc(f,n)))r.push(n);return r}function xs(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return ks(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function ks(i,t,r){let n=[...t];for(let f of i){if(!Ii(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let u of l)if(u in f){if(n.find((y)=>Ii(y)&&(u in y)&&y[u]===f[u])){c=!0;break}}if(!c)n.push(f)}return n}function Vs(i,t,r,n){let f=t;if(Ii(f)&&n.has(f))return n.get(f);let l={...i};if(Ii(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let u=f[c],$=l[c];if(r.skipNullish&&(u===null||u===void 0))continue;if(u===null||u===void 0){l[c]=u;continue}if(Ii(u)&&Ii($))l[c]=_y($,u,r,n);else if(Array.isArray(u)||Array.isArray($))l[c]=Ky($,u,r.arrayMergeMode||"smart",n);else l[c]=u}return l}function Gc(i,t,r="replace"){return Iy(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Cc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Cc(i[r],t[r]))return!1;return!0}if(Ii(i)&&Ii(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Cc(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Sf{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:u=!1}=r;if(f){let y=wr.getWithFileCheck("file",i);if(y){if(u)console.log(`Configuration loaded from cache: ${i}`);return y}}let $=async()=>{if(!Qn(i))return null;try{let y=`?t=${Date.now()}`,h=await import(i+y),w=h.default||h,e="default"in h,A=Object.keys(h).length>0;if(!e&&!A)throw new _r(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new _r(i,Error("Configuration must export a valid object"),"unknown");let E={config:Gc(t,w,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)wr.setWithFileCheck("file",E,i,l);return E}catch(y){throw y instanceof Error?Tt.configLoad(i,y):Tt.configLoad(i,Error(String(y)))}};if(c)return zr.track("loadFromPath",$,{path:i});return $()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(uc(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)r.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(i){return Xy(async()=>{return Qn(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!Qn(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let u=uc(i,`${l}${c}`);if(await this.checkFileAccess(u))n.push(u)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let u=uc(i,c);if(await this.checkFileAccess(u))n.push(u)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!Qn(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}class Mc{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:u=!0,verbose:$=!1}=r,y=async()=>{let h=[],w=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:u,verbose:$};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return h.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:h,warnings:w}}};if(u)return await zr.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,r){try{if(!cs(t))throw new Kr(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Kr(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,u=Array.isArray(t.type)?t.type:[t.type];if(!u.includes(c)){if(n.push({path:r,message:`Expected type ${u.join(" or ")}, got ${c}`,expected:u.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let u=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,u,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let u of t.required)if(!(u in c)){if(n.push({path:r?`${r}.${u}`:u,message:`Missing required property '${u}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[u,$]of Object.entries(t.properties))if(u in c){let y=r?`${r}.${u}`:u;if(this.validateObjectAgainstSchema(c[u],$,y,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let u=new Set(Object.keys(t.properties||{}));for(let $ of Object.keys(c))if(!u.has($))f.push({path:r?`${r}.${$}`:$,message:`Additional property '${$}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),u=this.validateWithRule(c,l,l.path);if(n.push(...u),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:gy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Hc{fileLoader=new Sf;envProcessor=new Rf;validator=new Mc;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let $=this.checkCache(c.name||"",c);if($)return $}let u;try{u=await this.loadConfigurationStrategies(c,!0,r)}catch($){let y=c.__strictErrorHandling;if($ instanceof Error&&$.name==="ConfigNotFoundError"){if(y)throw $;u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if($ instanceof Error&&$.name==="ConfigLoadError"){let h=$.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"),w=!h&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")||$.message.includes("errors building")),e=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");if(y&&(e||h))throw $;if(w&&(!y||!e))u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${$.message}`]};else throw $}else u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${$ instanceof Error?$.message:String($)}`]}}if(f||l)await this.validateConfiguration(u.config,f,l,c.name);if(r?.enabled&&u)this.cacheResult(c.name||"",u,r,c);if(n?.enabled){let $={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics($);if(n.slowThreshold&&$.duration>n.slowThreshold)di.warn(`Slow configuration loading detected: ${$.duration}ms for ${c.name}`);u.metrics=$}return u}catch(u){let $=Date.now()-t;throw di.error(`Configuration loading failed after ${$}ms:`,[u instanceof Error?u:Error(String(u))]),u}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:u,checkEnv:$=!0,arrayStrategy:y="replace",verbose:h=!1}=i,w=l||Jt.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,w,c,u,y,h,$,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,w,c)),this.finalizeResult(A,e,$,n,h);let m=await this.loadHomeConfiguration(n,f,u,y,h,$);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,$,n,h);let s=await this.loadPackageJsonConfiguration(n,f,w,u,y,h,$);if(s)return e.push(Ti(w,"package.json")),this.finalizeResult(s,e,$,n,h);if(e.push(...this.getAllSearchPaths(n,f,w,c)),t)throw Tt.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,u,$,h),warnings:[`No configuration file found for "${n}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,u,$){let y=u?Jr(i,f,c):f,h=this.getLocalDirectories(r,n);for(let w of h){if(c)di.info(`Searching for configuration in: ${w}`);let e=this.fileLoader.generateConfigPaths(i,w,t),A=await this.fileLoader.tryLoadFromPaths(e,y,{arrayStrategy:l,verbose:c,cacheTtl:$?.ttl,useCache:!$?.ttl||$.ttl>100});if(A){if(c)di.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?Jr(i,r,f):r,u=[Ti(tr(),".config",i),Ti(tr(),".config"),tr()];for(let $ of u){if(f)di.info(`Checking home directory: ${$}`);let y=this.fileLoader.generateConfigPaths(i,$,t),h=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:n,verbose:f});if(h){if(f)di.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let u=c?Jr(i,n,l):n;try{let $=Ti(r,"package.json");if(!Yc($))return null;let y=await import($),h=y[i],w=i;if(!h&&t)h=y[t],w=t;if(h&&typeof h==="object"&&!Array.isArray(h)){if(l)di.success(`Configuration loaded from package.json: ${w}`);return{config:Gc(u,h,f),source:{type:"package.json",path:$,priority:30,timestamp:new Date}}}}catch($){if(l)di.warn("Failed to load package.json:",[$ instanceof Error?$:Error(String($))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Jr(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Tt.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return wr.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);wr.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias)r.push(`alias:${t.alias}`);if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ti(i,"config"),Ti(i,".config"),t?Ti(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ti(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ti(tr(),".config",i),Ti(tr(),".config"),tr()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}function yy(i){let r=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return r||n}async function Ds(i){return ut.loadConfig({...i,__strictErrorHandling:!0})}async function zy(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},r="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let n;if(r)n=await ut.loadConfig(i);else n=await ut.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??t}catch(n){let f=n instanceof Error?n.name:"UnknownError",l=n instanceof Error?n.message:String(n);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||l.includes("config"))&&i.verbose)di.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let u=r?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ut.applyEnvironmentVariables(u.name||"",t,!0,u.verbose||!1))?.config??t;return t}}async function bs(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await ut.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&yy(r)))return(await ut.applyEnvironmentVariables(i,{},!0,!1)).config;throw r}}try{return(await ut.loadConfig({...i,cwd:i.cwd||Jt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&yy(t)))return(await ut.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function Qs(i,t,r="replace"){let n=new Sf;try{let f=await n.loadFromPath(i,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Jr(i,t,r=!1){let n=new Rf,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,u=[]){let $={...c};for(let[y,h]of Object.entries(c)){let w=[...u,y],e=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((s)=>s.toUpperCase()).join("")}`,`${f}_${w.map((s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let s of e)if(A=Jt.env[s],A!==void 0){m=s;break}if(A!==void 0&&m)if(typeof h==="boolean")$[y]=["true","1","yes"].includes(A.toLowerCase());else if(typeof h==="number"){let s=Number(A);if(!Number.isNaN(s))$[y]=s}else if(Array.isArray(h))try{$[y]=JSON.parse(A)}catch{$[y]=A.split(",").map((s)=>s.trim())}else $[y]=A;else if(h&&typeof h==="object"&&!Array.isArray(h))$[y]=l(h,w)}return $}return l(t)}function os(i){let t=Ti(Jt.cwd(),i.configDir),r=Ti(Jt.cwd(),i.generatedDir),n=Ti(r,"config-types.ts");if(!Yc(gu(n)))MA(gu(n),{recursive:!0,mode:511});let f=Yc(t)?HA(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],l=`// Generated by bunfig v${Sa}
102
- export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
103
- `;dA(n,l,{mode:438})}function Ps(i){let t=null,r=null,n=()=>{if(!r)r=zy(i).then((l)=>{return t=l,l},(l)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)di.warn("Config loading failed, using defaults:",[l instanceof Error?l:Error(String(l))]);return c});return r},f="defaultConfig"in i?i.defaultConfig:{};return t=f,n(),new Proxy({},{get(l,c){if(t)return t[c];let u=f[c];return n(),u},has(l,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(l,c){return Object.getOwnPropertyDescriptor(t||f,c)},set(l,c,u){if(!t)t={...f};return t[c]=u,!0}})}function vs(i){let t=ty(ys.cwd(),i?.configDir||"./config");function r(){if(!$s(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),l=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=us(t).filter(($)=>f.has(yc($))).map(($)=>({base:$.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:$})),u=new Map;for(let{base:$,file:y}of c){let h=yc(y).toLowerCase(),w=u.get($);if(!w){u.set($,y);continue}let e=yc(w).toLowerCase();if(l.indexOf(h)<l.indexOf(e))u.set($,y)}return Array.from(u.entries()).map(([$,y])=>({base:$,file:y})).sort(($,y)=>$.base.localeCompare(y.base))}function n(){let f=r(),l=f.map((y)=>y.base),c=l.length?l.map((y)=>`'${y}'`).join(" | "):"string",u=f.length?`{
104
- ${f.map((y)=>{let h=ty(t,y.file).replace(/\\/g,"/");return` '${y.base}': typeof import('${h}').default`}).join(`,
105
- `)}
106
- }`:"Record<string, any>";return`export type ConfigNames = ${c}
107
- export type ConfigByName = ${u}
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(f){f.onResolve({filter:/^virtual:bunfig-types$/},(l)=>{return{path:l.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var Oy,wr,zr,Gy,Zs,ps,hy,ff,Uc,wi,x,ia,wy,ta,ey,ra,na,Ac,fa,Ay,sy,sc,la,ca,$a,ua,lf,My,ya,ei,ha,wa,ay,cf,Rc,ri,z,ea,my,Aa,Ey,sa,aa,ac,ma,Ty,Yy,Ea,mc,Ta,Ya,Ba,Ca,Ua,$f,Hy,Ra,Sa="0.15.6",ji,Ef,_r,Sc,jc,Tf,Fc,Nc,Kr,Wc,Xc,Tt,dy,gy,di,ut,qy,Ly,ja=js(async()=>{Oy=import.meta.require,wr=new _c,zr=new Kc,Gy={createKey:Fs,isEquivalent:Ns,estimateMemoryUsage:Ws},Zs=wf(Bc.cwd(),"config"),ps=wf(Bc.cwd(),"src/generated"),hy=hf.env.CLARITY_LOG_DIR||LA(Is(),"logs"),ff={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:hy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Uc=await _s(),wi={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},x=wi,ia=wi.red,wy=wi.green,ta=wi.yellow,ey=wi.blue,ra=wi.magenta,na=wi.cyan,Ac=wi.white,fa=wi.gray,Ay=wi.bgRed,sy=wi.bgYellow,sc=wi.bold,la=wi.dim,ca=wi.italic,$a=wi.underline,ua=wi.reset,lf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},My={debug:"\uD83D\uDD0D",info:ey("ℹ"),success:wy("✓"),warning:sy(Ac(sc(" WARN "))),error:Ay(Ac(sc(" ERROR ")))},ya=new sf("stacks"),ei=new sf("bunfig",{showTags:!0}),ha=Ei(Ir.cwd(),"config"),wa=Ei(Ir.cwd(),"src/generated"),ay=yf.env.CLARITY_LOG_DIR||gA(Gs(),"logs"),cf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ay,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Rc=await Ms(),ri={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},z=ri,ea=ri.red,my=ri.green,Aa=ri.yellow,Ey=ri.blue,sa=ri.magenta,aa=ri.cyan,ac=ri.white,ma=ri.gray,Ty=ri.bgRed,Yy=ri.bgYellow,Ea=ri.bgGray,mc=ri.bold,Ta=ri.dim,Ya=ri.italic,Ba=ri.underline,Ca=ri.strikethrough,Ua=ri.reset,$f={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Hy={debug:"\uD83D\uDD0D",info:Ey("ℹ"),success:my("✓"),warning:Yy(ac(mc(" WARN "))),error:Ty(ac(mc(" ERROR ")))},Ra=new mf("stacks"),ji=class extends Error{timestamp;context;constructor(t,r={}){super(t);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 t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},Ef=class extends ji{code="CONFIG_NOT_FOUND";constructor(t,r,n){let f=n?` or alias "${n}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:n,searchPaths:r,searchPathCount:r.length})}},_r=class extends ji{code="CONFIG_LOAD_ERROR";constructor(t,r,n){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Sc=class extends ji{code="CONFIG_VALIDATION_ERROR";constructor(t,r,n){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:n,validationErrors:r,errorCount:r.length})}},jc=class extends ji{code="CONFIG_MERGE_ERROR";constructor(t,r,n,f){super(`Failed to merge configuration from "${t}" with "${r}": ${n.message}`,{sourcePath:t,targetPath:r,configName:f,originalError:n.name,originalMessage:n.message});this.cause=n}},Tf=class extends ji{code="ENV_VAR_ERROR";constructor(t,r,n,f){super(`Failed to parse environment variable "${t}" with value "${r}" as ${n}`,{envKey:t,envValue:r,expectedType:n,configName:f})}},Fc=class extends ji{code="FILE_SYSTEM_ERROR";constructor(t,r,n){super(`File system ${t} failed for "${r}": ${n.message}`,{operation:t,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Nc=class extends ji{code="TYPE_GENERATION_ERROR";constructor(t,r,n){super(`Failed to generate types from "${t}" to "${r}": ${n.message}`,{configDir:t,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Kr=class extends ji{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:t,configName:n,validationErrors:r,errorCount:r.length})}},Wc=class extends ji{code="BROWSER_CONFIG_ERROR";constructor(t,r,n,f){super(`Failed to fetch configuration from "${t}": ${r} ${n}`,{endpoint:t,status:r,statusText:n,configName:f})}},Xc=class extends ji{code="PLUGIN_ERROR";constructor(t,r,n){super(`Plugin "${t}" failed during ${r}: ${n.message}`,{pluginName:t,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Tt={configNotFound(i,t,r){return new Ef(i,t,r)},configLoad(i,t,r){return new _r(i,t,r)},configValidation(i,t,r){return new Sc(i,t,r)},configMerge(i,t,r,n){return new jc(i,t,r,n)},envVar(i,t,r,n){return new Tf(i,t,r,n)},fileSystem(i,t,r){return new Fc(i,t,r)},typeGeneration(i,t,r){return new Nc(i,t,r)},schemaValidation(i,t,r){return new Kr(i,t,r)},browserConfig(i,t,r,n){return new Wc(i,t,r,n)},plugin(i,t,r){return new Xc(i,t,r)}},dy={replace:"replace",concat:"concat",smart:"smart"},gy=/^https?:\/\//,di=new mf("bunfig",{showTags:!0}),ut=new Hc,qy=Ti(Jt.cwd(),"config"),Ly=Ti(Jt.cwd(),"src/generated")});function Fa(i,t={}){let r=ef.cwd();while(r.includes("storage"))r=ry(r,"..");let n=ry(r,i||"");if(t?.relative)return ws(ef.cwd(),n);return n}var Na=ef.env.CLARITY_LOG_DIR||hs(Fa(),"logs"),xy={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Na,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Yf={...xy},bC=(async()=>{try{let{loadConfig:i}=await ja().then(()=>Fy),t=await i({name:"clarity",alias:"logging",defaultConfig:xy,cwd:ef.cwd()});if(t)Object.assign(Yf,t)}catch{}return Yf})();function ni(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Wa(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let i=$t.type;if(i==="renderer"||i==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class ky{async format(i){let t=await Wa(),r=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:r})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:hr.pid,hostname:t(),environment:hr.env.NODE_ENV||"development",platform:hr.platform,version:hr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:hr.env.NODE_ENV||hr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ci={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},G=ci,QC=ci.red,Xa=ci.green,oC=ci.yellow,Ja=ci.blue,PC=ci.magenta,vC=ci.cyan,By=ci.white,ZC=ci.gray,Ia=ci.bgRed,_a=ci.bgYellow,pC=ci.bgGray,Cy=ci.bold,iU=ci.dim,tU=ci.italic,rU=ci.underline,nU=ci.strikethrough,fU=ci.reset,Ec={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ka={debug:"\uD83D\uDD0D",info:Ja("ℹ"),success:Xa("✓"),warning:_a(By(Cy(" WARN "))),error:Ia(By(Cy(" ERROR ")))};class jf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Yf},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ky,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},n=t.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 f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[r]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Ec,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Ec};return{...Ec,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Yf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(i).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let r=(async()=>{let f,l=0,c=3,u=1000;while(l<c)try{try{try{await ms(this.config.logDirectory,cy.F_OK|cy.W_OK)}catch(y){if(y instanceof Error&&"code"in y)if(y.code==="ENOENT")await Es(this.config.logDirectory,{recursive:!0,mode:493});else if(y.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw y;else throw y}}catch(y){throw console.error("Debug: [writeToFile] Failed to create log directory:",y),y}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:nt.from(i);try{if(!on(this.currentLogFile))await ec(this.currentLogFile,"",{mode:420});if(f=ly(this.currentLogFile,"a",420),as(f,$,{flag:"a"}),fy(f),f!==void 0)wc(f),f=void 0;if((await ur(this.currentLogFile)).size===0){if(await ec(this.currentLogFile,$,{flag:"w",mode:420}),(await ur(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(y){let h=y;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(l<c-1){let w=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,w);let e=u*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(f!==void 0)try{wc(f)}catch(y){console.error("Debug: [writeToFile] Error closing file descriptor:",y)}}}catch($){if(l===c-1){let h=$,w=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",w),$}l++;let y=u*2**(l-1);await new Promise((h)=>setTimeout(h,y))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}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 yr(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 yr(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return yr(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ni())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let r=typeof t.interval==="number"?t.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=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 f=Array.from(this.encryptionKeys.entries()).sort(([,u],[,$])=>$.createdAt.getTime()-u.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[u]of f.slice(c))this.encryptionKeys.delete(u),this.keys.delete(u)}generateKeyId(){return hc(16).toString("hex")}generateKey(){return hc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),r=hc(16),n=es("aes-256-gcm",t,r),f=nt.isBuffer(i)?i:nt.from(i,"utf8"),l=n.update(f),c=n.final(),u=l.length+c.length,$=n.getAuthTag(),y=nt.allocUnsafe(16+u+16);return r.copy(y,0),l.copy(y,16),c.copy(y,16+l.length),$.copy(y,16+u),{encrypted:y,iv:r}}async compressData(i){return new Promise((t,r)=>{let n=uy(),f=[];n.on("data",(l)=>f.push(l)),n.on("end",()=>t(nt.from(nt.concat(f)))),n.on("error",r),n.write(i),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ni())return;if(!this.shouldWriteToFile())return;let i=await ur(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Pn(this.config.logDirectory),l=f.filter(($)=>$.startsWith(this.name)&&/\.log\.\d+$/.test($)).sort(($,y)=>{let h=Number.parseInt($.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(y.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,u=`${r}.${c}`;if(await ur(r).catch(()=>null))try{if(await $y(r,u),t.compress)try{let $=`${u}.gz`;await this.compressLogFile(u,$),await vn(u)}catch($){console.error("Error compressing rotated file:",$)}if(l.length===0&&!f.some(($)=>$.endsWith(".log.1")))try{let $=`${r}.1`;await ec($,"")}catch($){console.error("Error creating backup file:",$)}}catch($){console.error(`Error during rotation: ${$ instanceof Error?$.message:String($)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=r.replace(/\.log$/,`-${f}.log`);if(await ur(r).catch(()=>null))await $y(r,l)}if(this.currentLogFile=n,t.maxFiles){let l=(await Pn(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,u)=>u.localeCompare(c));for(let c of l.slice(t.maxFiles))await vn(yr(this.config.logDirectory,c))}}}async compressLogFile(i,t){let r=ny(i),n=ss(t),f=uy();await Bs(r,f,n)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!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(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),on(this.currentLogFile))try{let i=ly(this.currentLogFile,"r+");fy(i),wc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ni()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Pn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await vn(yr(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:r="",tag:n="",message:f,level:l,showTimestamp:c=!0}=i,u=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(r)A.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)A.push(n.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let $=_.stdout.columns||120,y="";if(l==="warning"||l==="error")y=`${r} ${f}`;else if(l==="info"||l==="success")y=`${r} ${n} ${f}`;else y=`${r} ${n} ${G.cyan(f)}`;if(!c)return y.trim();let h=u(y).trim().length,w=u(t).length,e=Math.max(1,$-2-h-w);return`${y.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let u=Number.parseInt(c,10);return u<t[0].length?String(t[0][u]):l});let r=/%([sdijfo%])/g,n=0,f=i.replace(r,(l,c)=>{if(c==="%")return"%";if(n>=t.length)return l;let u=t[n++];switch(c){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 l}});if(n<t.length)f+=` ${t.slice(n).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,f)=>{let l=G.underline(G.blue(n)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let u=`file://${encodeURI(c)}`,$="\x1B]8;;",y="\x1B\\";return`\x1B]8;;${u}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(r,n)=>G.bgGray(n)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,n)=>G.bold(n)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>G.italic(n)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>G.italic(n)),t=t.replace(/~([^~]+)~/g,(r,n)=>G.strikethrough(n)),t}supportsHyperlinks(){if(ni())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=_.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Ts(t)||t.startsWith("./")||t.startsWith("../"))t=Ys(t);else return null;return on(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,r=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(i,t,...r){if(!this.shouldLog(i))return;let n=new Date,f=this.formatConsoleTimestamp(n),l=this.formatFileTimestamp(n),c,u;if(t instanceof Error)c=t.message,u=t.stack;else c=this.formatMessage(t,r);let{consoleText:$,fileText:y}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let w=this.options.showIcons===!1?"":Ka[i],e=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:G.gray($),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:G.green($),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:w,tag:e,message:$,level:i}),console.error(A),u){let m=u.split(`
111
- `);for(let s of m)if(s.trim()&&!s.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:G.gray(` ${s}`),level:i,showTimestamp:!1}))}break}}else if(!ni()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),u)console.error(u)}let h=`${l} ${this.environment}.${i.toUpperCase()}: ${y}
112
- `;if(u)h+=`${u}
113
- `;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(i,t=""){let r={update:(u,$)=>{},finish:(u)=>{},interrupt:(u,$)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!ni()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(u,$)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,u),this.activeProgressBar.total),$!==void 0)this.activeProgressBar.message=$;if(this.shouldStyleConsole()&&!ni()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(u)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,u)},interrupt:(u,$="info")=>{if(!ni()&&_.stdout.isTTY)_.stdout.write(`
114
- `);if(this[$==="warning"?"warn":$](u),this.activeProgressBar&&this.shouldStyleConsole()&&!ni()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=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(i)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),f=Math.round(n-t),l=`${i} completed in ${f}ms`,c=new Date,u=this.formatConsoleTimestamp(c),y=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(r)y+=` ${JSON.stringify(r)}`;if(y+=`
115
- `,y=y.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:u,icon:this.options.showIcons===!1?"":G.green("✓"),tag:h,message:`${l}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ni())console.error(y.trim());if(this.shouldWriteToFile())await this.writeToFile(y)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,r=new jf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(ni())throw Error("createReadStream is not supported in browser environments");if(!on(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ny(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=nt.isBuffer(i)?i:nt.from(i,"base64"),f=n.subarray(0,16),l=n.subarray(n.length-16),c=n.subarray(16,n.length-16),u=As("aes-256-gcm",r,f);u.setAuthTag(l);let $=u.update(c),y=u.final(),h=$.length+y.length,w=nt.allocUnsafe(h);return $.copy(w,0),y.copy(w,$.length),w.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 ni()}isServerMode(){return!ni()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),n=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let u=f.split(`
116
- `),$=Math.max(...u.map((e)=>e.length))+2,y=`┌${"─".repeat($)}┐`,h=`└${"─".repeat($)}┘`,w=u.map((e)=>{return this.formatConsoleMessage({timestamp:r,message:G.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(y),showTimestamp:!1})),w.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(h),showTimestamp:!1}))}else if(!ni())console.error(`${n} ${this.environment}.INFO: [BOX] ${l}`);let c=`${n} ${this.environment}.INFO: [BOX] ${l}
117
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ni())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${G.cyan("?")} ${i} (y/n) `);let r=(n)=>{let f=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let r=i;if(t&&t.length>0){let $=/%([sdijfo%])/g,y=0;if(r=i.replace($,(h,w)=>{if(w==="%")return"%";if(y>=t.length)return h;let e=t[y++];switch(w){case"s":return String(e);case"d":case"i":return Number(e).toString();case"j":case"o":return JSON.stringify(e,null,2);default:return h}}),y<t.length)r+=` ${t.slice(y).map((h)=>typeof h==="object"?JSON.stringify(h,null,2):String(h)).join(" ")}`}let{consoleText:n,fileText:f}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let $=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",y=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${y}${$} ${G.cyan(n)}`)}let u=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
118
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(u)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),n=Math.round(i.barLength*r/100),f=i.barLength-n,l=G.green("━".repeat(n)),c=G.gray("━".repeat(f)),u=`[${l}${c}]`,$=`${r}%`.padStart(4),y=i.message?` ${i.message}`:"",h=this.options.showIcons===!1?"":t||r===100?G.green("✓"):G.blue("▶"),w=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",e=`\r${h}${w} ${u} ${$}${y}`,A=_.stdout.columns||80,m=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${m}`,_.stdout.write(i.lastRenderedLine),t)_.stdout.write(`
119
- `)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ni()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Pn(this.config.logDirectory),r=[];for(let n of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let l=yr(this.config.logDirectory,n);if(i.before)try{if((await ur(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}r.push(l)}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 vn(n),console.warn(`Deleted log file: ${n}`)}catch(f){console.error(`Failed to delete log file ${n}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var lU=new jf("stacks");class gi extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Vy extends gi{code="CONFIG_NOT_FOUND";constructor(i,t,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],f="";if(n.length===1)f=` or alias "${n[0]}"`;else if(n.length>1)f=` or aliases ${n.map((l)=>`"${l}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:r,searchPaths:t,searchPathCount:t.length})}}class Bf extends gi{code="CONFIG_LOAD_ERROR";constructor(i,t,r){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Dy extends gi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,r){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class by extends gi{code="CONFIG_MERGE_ERROR";constructor(i,t,r,n){super(`Failed to merge configuration from "${i}" with "${t}": ${r.message}`,{sourcePath:i,targetPath:t,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class dc extends gi{code="ENV_VAR_ERROR";constructor(i,t,r,n){super(`Failed to parse environment variable "${i}" with value "${t}" as ${r}`,{envKey:i,envValue:t,expectedType:r,configName:n})}}class Qy extends gi{code="FILE_SYSTEM_ERROR";constructor(i,t,r){super(`File system ${i} failed for "${t}": ${r.message}`,{operation:i,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class oy extends gi{code="TYPE_GENERATION_ERROR";constructor(i,t,r){super(`Failed to generate types from "${i}" to "${t}": ${r.message}`,{configDir:i,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Cf extends gi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:i,configName:r,validationErrors:t,errorCount:t.length})}}class Py extends gi{code="BROWSER_CONFIG_ERROR";constructor(i,t,r,n){super(`Failed to fetch configuration from "${i}": ${t} ${r}`,{endpoint:i,status:t,statusText:r,configName:n})}}class vy extends gi{code="PLUGIN_ERROR";constructor(i,t,r){super(`Plugin "${i}" failed during ${t}: ${r.message}`,{pluginName:i,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var er={configNotFound(i,t,r){return new Vy(i,t,r)},configLoad(i,t,r){return new Bf(i,t,r)},configValidation(i,t,r){return new Dy(i,t,r)},configMerge(i,t,r,n){return new by(i,t,r,n)},envVar(i,t,r,n){return new dc(i,t,r,n)},fileSystem(i,t,r){return new Qy(i,t,r)},typeGeneration(i,t,r){return new oy(i,t,r)},schemaValidation(i,t,r){return new Cf(i,t,r)},browserConfig(i,t,r,n){return new Py(i,t,r,n)},plugin(i,t,r){return new vy(i,t,r)}};async function za(i,t={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let u=0;u<=r;u++)try{return await i()}catch($){if(c=$ instanceof Error?$:Error(String($)),u===r||!f(c))break;if(n>0)await new Promise((y)=>setTimeout(y,n))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class gc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,r={}){let{prefix:n,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:u=!1,trackPerformance:$=!0}=r,y=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let h=n||this.generateEnvPrefix(i),w={...t};return this.processObject(w,[],h,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:u,configName:i}),{config:w,source:{type:"environment",priority:50,timestamp:new Date}}};if($)return Ic.track("applyEnvironmentVariables",y,{configName:i});return y()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],u=c.map((h)=>this.formatEnvKey(h,n.useCamelCase)),$=`${r}_${u.join("_")}`,y=n.useBackwardCompatibility?`${r}_${c.map((h)=>h.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,r,n);else{let h=pn.env[$]||(y?pn.env[y]:void 0);if(h!==void 0){if(n.verbose){let w=pn.env[$]?$:y}try{i[f]=this.parseEnvironmentValue(h,typeof l,$,n.customParsers,n.configName)}catch(w){if(w instanceof dc)throw w;throw er.envVar($,h,typeof l,n.configName)}}}}}parseEnvironmentValue(i,t,r,n,f){for(let[l,c]of Object.entries(n))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw er.envVar(r,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},r=i.toUpperCase();for(let[n,f]of Object.entries(pn.env))if(n.startsWith(r)&&f!==void 0)t[n]=f;return t}validateEnvironmentVariable(i,t,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))n.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(i,t,r,{})}catch(f){n.push(`Cannot parse value "${t}" as ${r}: ${f}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(i,t,r={}){let{prefix:n,format:f="text"}=r,l=n||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,r,n){for(let[f,l]of Object.entries(i)){let c=[...t,f],u=`${r}_${c.map(($)=>this.formatEnvKey($,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,r,n);else n.push({key:u,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let r=`Environment Variables for ${t}:
120
-
121
- `;for(let n of i)r+=`${n.key}
122
- `,r+=` Type: ${n.type}
123
- `,r+=` Description: ${n.description}
124
- `,r+=` Example: ${n.example}
125
-
126
- `;return r}formatAsMarkdown(i,t){let r=`# Environment Variables for ${t}
127
-
128
- `;r+=`| Variable | Type | Description | Example |
129
- `,r+=`|----------|------|-------------|----------|
130
- `;for(let n of i)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
131
- `;return r}}function Oa(i,t,r={}){return Zy(i,t,r,new WeakMap)}function Zy(i,t,r,n){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=r;if(t===null||t===void 0)return l?i:t;if(c){let u=c(i,t);if(u!==void 0)return u}if(Array.isArray(t)||Array.isArray(i))return py(i,t,f,n);if(!_i(t)||!_i(i))return t;return da(i,t,r,n)}function py(i,t,r,n){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(r){case"replace":return t;case"concat":return Ga(i,t);case"smart":return Ma(i,t,n);default:return t}return t}function Ga(i,t){let r=[...t];for(let n of i)if(!r.some((f)=>Jc(f,n)))r.push(n);return r}function Ma(i,t,r){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return Ha(i,t,r);if(t.every((n)=>typeof n==="string")&&i.every((n)=>typeof n==="string")){let n=[...t];for(let f of i)if(!n.includes(f))n.push(f);return n}return t}function Ha(i,t,r){let n=[...t];for(let f of i){if(!_i(f)){n.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let u of l)if(u in f){if(n.find((y)=>_i(y)&&(u in y)&&y[u]===f[u])){c=!0;break}}if(!c)n.push(f)}return n}function da(i,t,r,n){let f=t;if(_i(f)&&n.has(f))return n.get(f);let l={...i};if(_i(f))n.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let u=f[c],$=l[c];if(r.skipNullish&&(u===null||u===void 0))continue;if(u===null||u===void 0){l[c]=u;continue}if(_i(u)&&_i($))l[c]=Zy($,u,r,n);else if(Array.isArray(u)||Array.isArray($))l[c]=py($,u,r.arrayMergeMode||"smart",n);else l[c]=u}return l}function ih(i,t,r="replace"){return Oa(i,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Jc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let r=0;r<i.length;r++)if(!Jc(i[r],t[r]))return!1;return!0}if(_i(i)&&_i(t)){let r=Object.keys(i),n=Object.keys(t);if(r.length!==n.length)return!1;for(let f of r){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Jc(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class th{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,r={}){let{arrayStrategy:n="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:u=!1}=r;if(f){let y=uf.getWithFileCheck("file",i);if(y){if(u)console.log(`Configuration loaded from cache: ${i}`);return y}}let $=async()=>{if(!tf(i))return null;try{let y=`?t=${Date.now()}`,h=await import(i+y),w=h.default||h,e="default"in h,A=Object.keys(h).length>0;if(!e&&!A)throw new Bf(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof w!=="object"||w===null||Array.isArray(w))throw new Bf(i,Error("Configuration must export a valid object"),"unknown");let E={config:ih(t,w,n),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)uf.setWithFileCheck("file",E,i,l);return E}catch(y){throw y instanceof Error?er.configLoad(i,y):er.configLoad(i,Error(String(y)))}};if(c)return Ic.track("loadFromPath",$,{path:i});return $()}async tryLoadFromPaths(i,t,r={}){for(let n of i)try{let f=await this.loadFromPath(n,t,r);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(r.verbose)console.warn(`Failed to load config from ${n}:`,f)}return null}generateConfigPaths(i,t,r){let n=this.generateNamePatterns(i,r),f=[];for(let l of n)for(let c of this.extensions)f.push(Tc(t,`${l}${c}`));return f}generateNamePatterns(i,t){let r=[];if(r.push("config",".config"),i)r.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let n=t===void 0?[]:Array.isArray(t)?t:[t];for(let l of n){if(!l)continue;if(r.push(l,`.${l}.config`,`${l}.config`,`.${l}`),i)r.push(`${i}.${l}.config`,`.${i}.${l}.config`)}let f=new Set;return r.filter((l)=>{if(!l||f.has(l))return!1;return f.add(l),!0})}checkFileAccess(i){return za(async()=>{return tf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,r){let n=[];if(!tf(i))return n;if(t||r){let f=this.generateNamePatterns(t||"",r);for(let l of f)for(let c of this.extensions){let u=Tc(i,`${l}${c}`);if(await this.checkFileAccess(u))n.push(u)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let u=Tc(i,c);if(await this.checkFileAccess(u))n.push(u)}}catch{return[]}return n}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(i))}async validateConfigFile(i){let t=[];try{if(!tf(i))return t.push("Configuration file does not exist"),t;let r=await import(i),n=r.default||r;if(n===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)t.push("Configuration must be an object");else if(Array.isArray(n))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let r=new Map;return await Promise.allSettled(i.map(async(n)=>{try{let f=await this.loadFromPath(n,{},t);if(f)r.set(n,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${n}:`,f)}})),r}}var qa=/^https?:\/\//;class rh{async validateConfiguration(i,t,r={}){let{stopOnFirstError:n=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:u=!0,verbose:$=!1}=r,y=async()=>{let h=[],w=[],e={stopOnFirstError:n,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:u,verbose:$};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return h.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:h,warnings:w}}};if(u)return await Ic.track("validateConfiguration",y);return y()}async validateWithSchemaFile(i,t,r){try{if(!ga(t))throw new Cf(t,[{path:"",message:"Schema file does not exist"}]);let n=await import(t),f=n.default||n;if(Array.isArray(f))return this.validateWithRules(i,f,r);else return this.validateWithJSONSchema(i,f,r)}catch(n){throw new Cf(t,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(i,t,r){let n=[],f=[];return this.validateObjectAgainstSchema(i,t,"",n,f,r),{isValid:n.length===0,errors:n,warnings:f}}validateObjectAgainstSchema(i,t,r,n,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,u=Array.isArray(t.type)?t.type:[t.type];if(!u.includes(c)){if(n.push({path:r,message:`Expected type ${u.join(" or ")}, got ${c}`,expected:u.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(n.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)n.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)n.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))n.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)n.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)n.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let u=r?`${r}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,u,n,f,l),l.stopOnFirstError&&n.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let u of t.required)if(!(u in c)){if(n.push({path:r?`${r}.${u}`:u,message:`Missing required property '${u}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[u,$]of Object.entries(t.properties))if(u in c){let y=r?`${r}.${u}`:u;if(this.validateObjectAgainstSchema(c[u],$,y,n,f,l),l.stopOnFirstError&&n.length>0)return}}if(t.additionalProperties===!1){let u=new Set(Object.keys(t.properties||{}));for(let $ of Object.keys(c))if(!u.has($))f.push({path:r?`${r}.${$}`:$,message:`Additional property '${$}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,r){let n=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),u=this.validateWithRule(c,l,l.path);if(n.push(...u),r.stopOnFirstError&&n.length>0)break}catch(c){n.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:f}}validateWithRule(i,t,r){let n=[];if(t.required&&(i===void 0||i===null))return n.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(i===void 0||i===null)return n;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)n.push({path:r,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)n.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)n.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))n.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))n.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)n.push({path:r,message:t.message||f,rule:"custom"})}return n}getValueByPath(i,t){if(!t)return i;let r=t.split("."),n=i;for(let f of r)if(n&&typeof n==="object"&&f in n)n=n[f];else return;return n}generateRulesFromInterface(i){let t=[],r=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,f,l,c]=n;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:qa},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ft=new jf("bunfig",{showTags:!0});function La(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class nh{fileLoader=new th;envProcessor=new gc;validator=new rh;async loadConfig(i){let t=Date.now(),{cache:r,performance:n,schema:f,validate:l,...c}=i;try{if(r?.enabled){let $=this.checkCache(c.name||"",c);if($)return $}let u;try{u=await this.loadConfigurationStrategies(c,!0,r)}catch($){let y=c.__strictErrorHandling;if($ instanceof Error&&$.name==="ConfigNotFoundError"){if(y)throw $;u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if($ instanceof Error&&$.name==="ConfigLoadError"){let h=$.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"),w=!h&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")||$.message.includes("errors building")),e=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");if(y&&(e||h))throw $;if(w&&(!y||!e))u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!y)u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${$.message}`]};else throw $}else u={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${$ instanceof Error?$.message:String($)}`]}}if(f||l)await this.validateConfiguration(u.config,f,l,c.name);if(r?.enabled&&u)this.cacheResult(c.name||"",u,r,c);if(n?.enabled){let $={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(n.onMetrics)n.onMetrics($);if(n.slowThreshold&&$.duration>n.slowThreshold)ft.warn(`Slow configuration loading detected: ${$.duration}ms for ${c.name}`);u.metrics=$}return u}catch(u){if(u instanceof Error&&u.name==="ConfigNotFoundError")throw u;let $=Date.now()-t;throw ft.error(`Configuration loading failed after ${$}ms:`,[u instanceof Error?u:Error(String(u))]),u}}async loadConfigurationStrategies(i,t=!1,r){let{name:n="",alias:f,cwd:l,configDir:c,defaultConfig:u,checkEnv:$=!0,arrayStrategy:y="replace",verbose:h=!1}=i,w=l||Uf.cwd(),e=[],A=await this.loadLocalConfiguration(n,f,w,c,u,y,h,$,r);if(A)return e.push(...this.getLocalSearchPaths(n,f,w,c)),this.finalizeResult(A,e,$,n,h);let m=await this.loadHomeConfiguration(n,f,u,y,h,$);if(m)return e.push(...this.getHomeSearchPaths(n,f)),this.finalizeResult(m,e,$,n,h);let s=await this.loadPackageJsonConfiguration(n,f,w,u,y,h,$);if(s)return e.push(Ji(w,"package.json")),this.finalizeResult(s,e,$,n,h);if(e.push(...this.getAllSearchPaths(n,f,w,c)),t)throw er.configNotFound(n,e,f);return{...await this.applyEnvironmentVariables(n,u,$,h),warnings:[`No configuration file found for "${n}"${La(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,r,n,f,l,c,u,$){let y=u?rf(i,f,c):f,h=this.getLocalDirectories(r,n);for(let w of h){if(c)ft.info(`Searching for configuration in: ${w}`);let e=this.fileLoader.generateConfigPaths(i,w,t),A=await this.fileLoader.tryLoadFromPaths(e,y,{arrayStrategy:l,verbose:c,cacheTtl:$?.ttl,useCache:!$?.ttl||$.ttl>100});if(A){if(c)ft.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,r,n,f,l){if(!i)return null;let c=l?rf(i,r,f):r,u=[Ji(ir(),".config",i),Ji(ir(),".config"),ir()];for(let $ of u){if(f)ft.info(`Checking home directory: ${$}`);let y=this.fileLoader.generateConfigPaths(i,$,t),h=await this.fileLoader.tryLoadFromPaths(y,c,{arrayStrategy:n,verbose:f});if(h){if(f)ft.success(`Configuration loaded from home directory: ${h.source.path}`);return h}}return null}async loadPackageJsonConfiguration(i,t,r,n,f,l,c){let u=c?rf(i,n,l):n;try{let $=Ji(r,"package.json");if(!OA($))return null;let y={};try{y=JSON.parse(GA($,"utf8"))}catch(e){if(l)ft.warn("Failed to parse package.json:",[e instanceof Error?e:Error(String(e))]);return null}let h=y[i],w=i;if(!h&&t){let e=Array.isArray(t)?t:[t];for(let A of e){if(!A)continue;if(y[A]){h=y[A],w=A;break}}}if(h&&typeof h==="object"&&!Array.isArray(h)){if(l)ft.success(`Configuration loaded from package.json: ${w}`);return{config:ih(u,h,f),source:{type:"package.json",path:$,priority:30,timestamp:new Date}}}}catch($){if(l)ft.warn("Failed to load package.json:",[$ instanceof Error?$:Error(String($))])}return null}async applyEnvironmentVariables(i,t,r,n){if(!r||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:rf(i,t,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,r,n,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,r,n){let f=[];if(r){let l=r(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw er.configValidation(n||"unknown",f,n)}checkCache(i,t){let r=this.generateCacheKey(i,t);return uf.get(r)||null}cacheResult(i,t,r,n){let f=this.generateCacheKey(i,n);uf.set(f,t,void 0,r.ttl)}generateCacheKey(i,t){let r=[i];if(t.alias){let n=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${n}`)}if(t.cwd)r.push(`cwd:${t.cwd}`);if(t.configDir)r.push(`configDir:${t.configDir}`);if("checkEnv"in t)r.push(`checkEnv:${t.checkEnv}`);return r.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ji(i,"config"),Ji(i,".config"),t?Ji(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,r,n){let f=[];return f.push(...this.getLocalSearchPaths(i,t,r,n)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ji(r,"package.json")),f}getLocalSearchPaths(i,t,r,n){let f=this.getLocalDirectories(r,n),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let r=[Ji(ir(),".config",i),Ji(ir(),".config"),ir()],n=[];for(let f of r)n.push(...this.fileLoader.generateConfigPaths(i,f,t));return n}async loadConfigWithResult(i){return this.loadConfig(i)}}var hU=new nh;function rf(i,t,r=!1){let n=new gc,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,u=[]){let $={...c};for(let[y,h]of Object.entries(c)){let w=[...u,y],e=[`${f}_${w.join("_").toUpperCase()}`,`${f}_${w.map((s)=>s.toUpperCase()).join("")}`,`${f}_${w.map((s)=>s.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,m;for(let s of e)if(A=Uf.env[s],A!==void 0){m=s;break}if(A!==void 0&&m)if(typeof h==="boolean")$[y]=["true","1","yes"].includes(A.toLowerCase());else if(typeof h==="number"){let s=Number(A);if(!Number.isNaN(s))$[y]=s}else if(Array.isArray(h))try{$[y]=JSON.parse(A)}catch{$[y]=A.split(",").map((s)=>s.trim())}else $[y]=A;else if(h&&typeof h==="object"&&!Array.isArray(h))$[y]=l(h,w)}return $}return l(t)}var wU=Ji(Uf.cwd(),"config"),eU=Ji(Uf.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",xa={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Lc(qc(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Lc(qc(),".stacks","ssl","stacks.localhost.crt"),keyPath:Lc(qc(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var fh=xa;import{execSync as Gr}from"node:child_process";import{homedir as ba}from"node:os";import{join as Qa}from"node:path";function ka(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function It(i){try{return qn(i)}catch{return null}}function xc(i){try{return Pl(i)||null}catch{return null}}function kc(i,t){try{return t.every((r)=>Zl(i,r))}catch{return!1}}function Va(i,t,r=443){return vl(i,t,r)}function Da(i){let t=[];for(let r of i.split(`
132
- `)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)t.push(n[1].toUpperCase())}return t}var Yt="-d -r trustRoot -p ssl -p basic",_t="/Library/Keychains/System.keychain",Vc="rpx.localhost";function Mr(){return Qa(ba(),"Library/Keychains/login.keychain-db")}function Dc(){return[_t,Mr()]}function lh(i,t=Vc){let r=Gr(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let f of r.split(`
133
- `)){let l=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(l)n.push(l[1].toUpperCase())}return n}function Ff(i){if(process.platform!=="darwin")return;let t=It(i.caPath);if(!t)return;let r=i.commonName??Vc,n=i.keychains??Dc();for(let f of n)for(let l of lh(f,r)){if(l===t)continue;try{if(f.startsWith("/Library"))Or(`security delete-certificate -Z ${l} "${f}"`);else Gr(`security delete-certificate -Z ${l} "${f}"`,{stdio:"ignore"});a("ssl",`Removed stale Root CA ${l} from ${f}`,i.verbose)}catch{}}}function Hr(i,t,r){if(process.platform!=="darwin")return dr(i,r);try{let f=Gr(`security verify-cert -c "${i}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return a("ssl",`verify-cert ${t}: ${f?"trusted":"not trusted"}`,r?.verbose),f}catch{return!1}}function dr(i,t){let r=It(i);if(!r)return!1;for(let n of Dc())try{let f=Gr(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let l of f.split(`
134
- `))if(l.toUpperCase().includes("SHA-256")){if(l.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return a("ssl",`Root CA fingerprint found in ${n}`,t?.verbose),!0}}catch{}return!1}function bc(i,t){if(process.platform!=="darwin")return!1;let r=t.serverName;Ff({caPath:i,commonName:t.commonName,verbose:t.verbose});let n=Mr();try{Gr(`security add-trusted-cert ${Yt} -k "${n}" "${i}"`,{stdio:"ignore"})}catch{}try{Or(`security add-trusted-cert ${Yt} -k ${_t} "${i}"`)}catch{return!1}return Hr(i,r,{verbose:t.verbose})||dr(i,{verbose:t.verbose})}var Bt=null,vc=b(Ar(),".stacks","ssl","rpx.localhost.crt");function eh(i,t){return[...new Set(i.filter(Boolean))].map((r)=>({serverName:r,cert:t.cert,key:t.key}))}function Ah(i,t,r){let n=b(Ar(),".stacks","ssl"),f=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:vc,keyPath:b(n,"rpx.localhost.key"),caCertPath:b(n,"rpx.localhost.ca.crt"),commonName:t},verbose:r,regenerateUntrustedCerts:!0,proxies:f.map((l)=>({from:"localhost:1",to:l,cleanUrls:!1}))}}var oa="rpx-root-ca.crt",Pa="rpx-root-ca.key";function Zc(i){return{caCertPath:b(i,oa),caKeyPath:b(i,Pa)}}function dU(i){return{certPath:b(i,"rpx.localhost.crt"),keyPath:b(i,"rpx.localhost.key"),caCertPath:b(i,"rpx.localhost.ca.crt"),rootCA:Zc(i)}}async function va(i,t){try{let[r,n]=await Promise.all([P.readFile(i.caCertPath,"utf8"),P.readFile(i.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return a("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:r,privateKey:n}}catch(r){return a("ssl",`No existing Root CA at ${i.caCertPath} (${r.code||r}), will create one`,t),null}}function ch(i){let t=new Set;t.add(i);let r=i.split(".");if(r.length>=2)t.add(`*.${r.slice(1).join(".")}`);return Array.from(t)}function sh(i){let r=Pc(i).replace(/\*/g,"wildcard"),n=b(Ar(),".stacks","ssl"),f=n;if(typeof i?.https==="object")return f=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:n,{caCertPath:i.https.caCertPath||b(f,`${r}.ca.crt`),certPath:i.https.certPath||b(f,`${r}.crt`),keyPath:i.https.keyPath||b(f,`${r}.key`)};return{caCertPath:b(f,`${r}.ca.crt`),certPath:b(f,`${r}.crt`),keyPath:b(f,`${r}.key`)}}function $h(i){let t=new Set;if(Nf(i))i.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";ch(n).forEach((f)=>t.add(f))});else if(yh(i)){let r=i.to||"rpx.localhost";ch(r).forEach((n)=>t.add(n))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function gU(i){a("ssl","Loading SSL configuration",i.verbose);let t={...fh,...i};if(i.https=t0(t),!i.https?.keyPath&&!i.https?.certPath)return a("ssl","No SSL configuration provided",i.verbose),null;if(i.https?.keyPath&&!i.https?.certPath||!i.https?.keyPath&&i.https?.certPath){let r=!i.https?.keyPath?"keyPath":"certPath";throw a("ssl",`Invalid SSL configuration - missing ${r}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{a("ssl","Reading SSL certificate files",i.verbose);let r=await P.readFile(i.https?.keyPath,"utf8"),n=await P.readFile(i.https?.certPath,"utf8");return a("ssl","SSL configuration loaded successfully",i.verbose),{key:r,cert:n}}catch(r){return a("ssl",`Failed to read certificates: ${r}`,i.verbose),null}}catch(r){throw a("ssl",`SSL configuration error: ${r}`,i.verbose),r}}async function qU(i,t){if(qi.platform==="darwin")return Za(i,t);if(qi.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)n(!0);else r(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(l)=>{n(!l)})})})}catch{return!1}return!1}async function Za(i,t){if(qi.platform!=="darwin")return!1;let r=t?.serverName??"rpx.localhost",n=t?.verbose??!1;try{if(Hr(i,r,{verbose:n}))return a("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return a("ssl","Trusting Root CA for browsers (login + system keychains)",n),bc(i,{serverName:r,verbose:n})}catch{return!1}}async function ah(i){if(Bt&&!i.forceRegenerate){a("ssl","Using cached SSL configuration",i.verbose);return}pc();let t=Nf(i)?i.proxies.map((h)=>h.to):[i.to];a("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let r=t0(i,i.verbose),n=r.basePath||b(Ar(),".stacks","ssl");await P.mkdir(n,{recursive:!0});let f=Zc(n),l=await va(f,i.verbose),c=!1;if(!l){if(i.verbose)j.info("Generating Root CA certificate (one-time)...");l=await Ql(r);try{await Promise.all([P.writeFile(f.caCertPath,l.certificate),P.writeFile(f.caKeyPath,l.privateKey,{mode:384})]),c=!0,a("ssl",`Persisted Root CA at ${f.caCertPath}`,i.verbose)}catch(h){throw a("ssl",`Error saving Root CA files: ${h}`,i.verbose),Error(`Failed to save Root CA files: ${h}`)}}else a("ssl",`Reusing existing Root CA from ${f.caCertPath}`,i.verbose);if(i.verbose)j.info(`Generating host certificate for: ${t.join(", ")}`);let u=await ol({...r,rootCA:{certificate:l.certificate,privateKey:l.privateKey}});try{await Promise.all([P.writeFile(r.certPath,u.certificate),P.writeFile(r.keyPath,u.privateKey),P.writeFile(r.caCertPath,l.certificate)]),a("ssl","Certificate files saved successfully",i.verbose)}catch(h){throw a("ssl",`Error saving certificate files: ${h}`,i.verbose),Error(`Failed to save certificate files: ${h}`)}if(c?!1:await mh(f.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(a("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)j.success("Root CA is already trusted in system trust store");if(Bt={key:u.privateKey,cert:u.certificate,ca:l.certificate},i.verbose)j.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)j.info("Adding certificate to system trust store (may require sudo permission)...");let y=!1;if(qi.platform==="darwin")try{Ff({caPath:f.caCertPath,verbose:i.verbose});let h=Mr();try{Qc(`security add-trusted-cert ${Yt} -k "${h}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Or(`security add-trusted-cert ${Yt} -k ${_t} "${f.caCertPath}"`),i.verbose)j.success("Successfully added Root CA to system trust store");y=!0;let w=b(n,"trust-rpx-cert.sh"),e=`#!/bin/bash
135
- echo "Trusting RPX Root CA"
136
- sudo security add-trusted-cert ${Yt} -k ${_t} "${f.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 P.writeFile(w,e,{mode:493})}catch(h){if(i.verbose)j.warn(`Could not add Root CA to trust store automatically: ${h}`);let w=b(n,"trust-rpx-cert.sh"),e=`#!/bin/bash
140
- echo "Trusting RPX Root CA"
141
- sudo security add-trusted-cert ${Yt} -k ${_t} "${f.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 P.writeFile(w,e,{mode:493}),i.verbose)j.info(`Created a trust helper script at: ${w}`),j.info(`If you're still having certificate issues, run: sh ${w}`)}else if(qi.platform==="linux")try{let{exec:h}=await import("node:child_process"),w="/usr/local/share/ca-certificates/rpx",e=`
145
- mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
146
- cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
147
- update-ca-certificates
148
- echo "RPX Root CA installed. Please restart your browser."
149
- `,A=b(oc.tmpdir(),`rpx-trust-${Date.now()}.sh`);await P.writeFile(A,e,{mode:493}),await new Promise((m)=>{h(`sudo bash "${A}"`,(s)=>{if(s){if(i.verbose)j.warn(`Could not trust certificates: ${s}`);m(!1)}else{if(i.verbose)j.success("Successfully added certificates to system trust store");m(!0)}})}),await P.unlink(A).catch(()=>{}),y=!0}catch(h){if(i.verbose)j.warn(`Failed to trust certificates: ${h}`)}else if(qi.platform==="win32")try{let h=`
150
- $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.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
- `,w=b(oc.tmpdir(),"rpx-trust.ps1");if(await P.writeFile(w,h),Qc(`powershell -ExecutionPolicy Bypass -File "${w}"`),i.verbose)j.success("Successfully added certificate to Windows trust store");y=!0}catch(h){if(i.verbose)j.warn(`Could not trust certificate: ${h}`)}else try{await pl(u,l.certificate,r),y=!0}catch(h){if(i.verbose)j.warn(`Could not add certificate to trust store: ${h}`)}if(Bt={key:u.privateKey,cert:u.certificate,ca:l.certificate},i.verbose)j.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!y&&i.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 pc(){Bt=null}async function i0(i){if(!i)return null;if(Bt)return Bt;let t=t0(i);try{let[r,n,f]=await Promise.all([P.access(t.keyPath).then(()=>!0).catch(()=>!1),P.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?P.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return a("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${t.keyPath}, ${t.certPath}`,i.verbose),null;let l="regenerateUntrustedCerts"in i,c=i.regenerateUntrustedCerts,u=l?c!==!1:!0;a("ssl",`Trust check: hasFlag=${l}, flagValue=${c}, shouldCheckTrust=${u}`,i.verbose);let $=t.basePath||b(Ar(),".stacks","ssl"),y=Zc($);if(!(u?await mh(y.caCertPath,i):!0))return a("ssl","Root CA exists but is not trusted, will regenerate",i.verbose),null;let[w,e,A]=await Promise.all([P.readFile(t.keyPath,"utf8"),P.readFile(t.certPath,"utf8"),f&&t.caCertPath?P.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(A&&!A.includes("-----BEGIN CERTIFICATE-----"))return a("ssl","Invalid root CA certificate content, will regenerate",i.verbose),null;if(Nf(i))try{let{X509Certificate:m}=await import("node:crypto"),E=new m(e).subjectAltName||"",B=i.proxies.map((F)=>F.to).filter((F)=>!E.includes(`DNS:${F}`));if(B.length>0)return a("ssl",`Certificate missing SANs for: ${B.join(", ")}, will regenerate`,i.verbose),null}catch(m){a("ssl",`Could not verify cert SANs: ${m}`,i.verbose)}return a("ssl","Successfully loaded existing certificates",i.verbose),Bt={key:w,cert:e,ca:A},Bt}catch(r){return a("ssl",`Error checking existing certificates: ${r}`,i.verbose),null}}function t0(i,t){let r=Pc(i);a("ssl",`Primary domain: ${r}`,t);let n=sh(i),f=b(Ar(),".stacks","ssl");if(typeof i.https==="object"){let l=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:f,c={domain:r,hostCertCN:r,basePath:l,caCertPath:i.https.caCertPath||n.caCertPath,certPath:i.https.certPath||n.certPath,keyPath:i.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:i.https.commonName||r,organizationName:i.https.organizationName||"Local Development",countryName:i.https.countryName||"US",stateName:i.https.stateName||"California",localityName:i.https.localityName||"Playa Vista",validityDays:i.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from($h(i)).map((u)=>({type:2,value:u}))};if(uh(i.https.rootCA))c.rootCA=i.https.rootCA;return c}return{domain:r,hostCertCN:r,basePath:f,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from($h(i)).map((l)=>({type:2,value:l}))}}async function LU(i,t){let r=sh({to:i,verbose:t}),n=[r.caCertPath,r.certPath,r.keyPath];a("certificates","Attempting to clean up relating certificates",t),await Promise.all(n.map((f)=>hh(f,t)))}async function mh(i,t){try{if(a("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),qi.platform==="darwin"){if(t?.serverName)return Hr(i,t.serverName,{verbose:t?.verbose});return dr(i,{verbose:t?.verbose})}else if(qi.platform==="win32")try{let r=xc(i)||"";if(!r)return a("ssl","Could not extract certificate subject",t?.verbose),!1;let n=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(Qc(n).toString().includes(r))return a("ssl","Certificate found in trusted root store",t?.verbose),!0;return a("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(r){return a("ssl",`Error checking certificate trust on Windows: ${r}`,t?.verbose),!1}else if(qi.platform==="linux")try{let r=It(i);if(!r)return a("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let n=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of n){let l;try{l=await P.readdir(f)}catch{continue}for(let c of l){let u=It(wh.join(f,c));if(u&&u===r)return a("ssl",`Certificate fingerprint found in ${f}`,t?.verbose),!0}}return a("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(r){return a("ssl",`Error checking certificate trust on Linux: ${r}`,t?.verbose),!1}return a("ssl",`Platform ${qi.platform} not supported for certificate trust check`,t?.verbose),!1}catch(r){return a("ssl",`Error checking if certificate is trusted: ${r}`,t?.verbose),!1}}import{createHash as Th,timingSafeEqual as Eh}from"node:crypto";import{readFileSync as pa}from"node:fs";var im="/.well-known/acme-challenge/";function gr(i,t){let r=Buffer.from(i,"utf8"),n=Buffer.from(t,"utf8");if(r.length!==n.length)return Eh(r,r),!1;return Eh(r,n)}function tm(i,t){let r=(e)=>Th("md5").update(e).digest(),n=Buffer.from(i,"utf8"),f=Buffer.from(t,"utf8"),l=r(Buffer.concat([n,f,n])),c=[n,Buffer.from("$apr1$","utf8"),f];for(let e=n.length;e>0;e-=16)c.push(l.subarray(0,Math.min(e,16)));for(let e=n.length;e>0;e>>=1)c.push(e&1?Buffer.from([0]):n.subarray(0,1));let u=r(Buffer.concat(c));for(let e=0;e<1000;e++){let A=[];if(A.push(e&1?n:u.subarray(0,16)),e%3)A.push(f);if(e%7)A.push(n);A.push(e&1?u.subarray(0,16):n),u=r(Buffer.concat(A))}let $="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",y=(e,A)=>{let m="",s=e;for(let E=0;E<A;E++)m+=$[s&63],s>>=6;return m},h=u,w="";return w+=y(h[0]<<16|h[6]<<8|h[12],4),w+=y(h[1]<<16|h[7]<<8|h[13],4),w+=y(h[2]<<16|h[8]<<8|h[14],4),w+=y(h[3]<<16|h[9]<<8|h[15],4),w+=y(h[4]<<16|h[10]<<8|h[5],4),w+=y(h[11],2),`$apr1$${t}$${w}`}function rm(i,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(i,t)}catch{return!1}if(t.startsWith("$apr1$")){let n=t.split("$")[2]??"";return gr(tm(i,n),t)}if(t.startsWith("{SHA}")){let r=Th("sha1").update(i,"utf8").digest("base64");return gr(`{SHA}${r}`,t)}return gr(i,t)}function nm(i){let t=new Map;for(let r of i.split(`
157
- `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let f=n.indexOf(":");if(f<=0)continue;t.set(n.slice(0,f),n.slice(f+1))}return t}function Yh(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",r=[];if(i.username)r.push({username:i.username,password:i.password??""});for(let l of i.users??[])if(l?.username)r.push({username:l.username,password:l.password??""});let n;if(i.htpasswdFile)try{n=nm(pa(i.htpasswdFile,"utf8"))}catch{n=void 0}if(r.length===0&&(!n||n.size===0))return;return{realm:t,verify:(l,c)=>{let u=!1;for(let $ of r)if(gr(l,$.username)&&gr(c,$.password))u=!0;if(n){let $=n.get(l);if($&&rm(c,$))u=!0}return u}}}function Bh(i,t,r){if(t.startsWith(im))return;let n=i.headers.get("authorization")??"",f=n.indexOf(" "),l=f===-1?n:n.slice(0,f),c=f===-1?"":n.slice(f+1).trim();if(l.toLowerCase()==="basic"&&c){let $="";try{$=Buffer.from(c,"base64").toString("utf8")}catch{$=""}let y=$.indexOf(":");if(y>=0&&r.verify($.slice(0,y),$.slice(y+1)))return}let u=r.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${u}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:fm}=Bun,qr=Symbol("rpx.pool.fallback"),Wf=Symbol("rpx.pool.stale");var lm=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function cm(i){return lm.has(i.toUpperCase())}var n0=Symbol("rpx.pool.timeout"),Kt=Symbol("rpx.pool.busy");function $m(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function um(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function ym(){let i=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(i)&&i>0?i:0}function hm(){let i=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(i)&&i>0?i:0}var Uh=1048576;function wm(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var r0=30000,em=16384,Rh=262144,Am=2097152,sm=524288,am=8192,mm=4096,Em=new TextEncoder,Sh=new TextDecoder,Tm=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class jh{socket=null;buf=new Uint8Array(em);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(i){let t=this.socket,r=t.write(i);while(r<i.length){if(this.closed)throw Wf;await new Promise((n)=>{this.drainWaiter=n}),r+=t.write(i.subarray(r))}}wakeDrain(){let i=this.drainWaiter;if(i)this.drainWaiter=null,i()}push(i){if(this.bodyQueue){let t=i.length<=this.bodyRemaining?i.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(i.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<i.length)this.appendToBuf(i.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(i),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>Am)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=sm)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(i){let t=this.len+i.length;if(t>this.buf.length){let r=new Uint8Array(Math.max(this.buf.length*2,t));r.set(this.buf.subarray(0,this.len)),this.buf=r}this.buf.set(i,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let i=this.waiter;if(i)this.waiter=null,i()}waitForData(i){if(this.len>i||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((i)=>{this.waiter=i})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class Fh{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=$m();maxWaiters;checkoutIdleMs=ym();inUse=new Set;constructor(i,t,r,n=""){this.host=i;this.port=t;this.maxTotal=r;this.key=n;this.maxWaiters=um(r)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new jh;return fm({hostname:this.host,port:this.port,socket:{data:(t,r)=>i.push(r),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let r=t;r.setNoDelay?.(!0);let n=hm();if(n>0)r.timeout?.(n);return i.socket=t,i})}acquireIdleSync(){while(this.idle.length){let i=this.idle.pop();if(!i.closed)return i.socket?.ref(),i.pos=0,i.len=0,this.trackCheckout(i),i;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Kt;let i=await this.waitForSlot();if(i===Kt)throw Kt;if(i)return i.pos=0,i.len=0,this.trackCheckout(i),i}this.open++;try{let i=await this.dial();return this.trackCheckout(i),i}catch(i){throw this.open--,this.wakeWaiter(),i}}waitForSlot(){return new Promise((i)=>{let t=!1,r=(l)=>{if(t)return;t=!0,clearTimeout(f),i(l)},n=(l)=>r(l),f=setTimeout(()=>{let l=this.waiters.indexOf(n);if(l!==-1)this.waiters.splice(l,1);r(Kt)},this.queueWaitMs);f.unref?.(),this.waiters.push(n)})}release(i){if(this.inUse.delete(i),i.closed){this.open--,this.wakeWaiter();return}i.clearStreaming(),i.compact(),i.fresh=!1;let t=this.waiters.shift();if(t){i.socket?.ref(),this.trackCheckout(i),t(i);return}i.idleSince=Date.now(),i.socket?.unref(),this.idle.push(i),this.ensureSweeper()}destroy(i){this.inUse.delete(i),i.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let i=this.waiters.shift();if(i)i(null)}ensureSweeper(){if(this.sweeper)return;let i=this.checkoutIdleMs>0?Math.min(r0,this.checkoutIdleMs):r0;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-r0;if(this.idle.length){let r=[];for(let n of this.idle)if(n.closed||n.idleSince<=t)n.destroy(),this.open--;else r.push(n);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=i-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){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&Xf.get(this.key)===this)Xf.delete(this.key)}}}var Xf=new Map;function Ym(i,t){let r=Xf.get(i);if(!r){let n=i.lastIndexOf(":"),f=n===-1?i:i.slice(0,n),l=n===-1?80:Number(i.slice(n+1));r=new Fh(f,l,t,i),Xf.set(i,r)}return r}function Ch(i,t,r){for(let n=r+3;n<t;n++)if(i[n]===10&&i[n-1]===13&&i[n-2]===10&&i[n-3]===13)return n-3;return-1}function Bm(i,t,r){let n=Sh.decode(i.subarray(t,r)),f=n.indexOf(`\r
158
- `),l=f===-1?n:n.slice(0,f),c=l.indexOf(" "),u=Number.parseInt(l.slice(c+1,c+5),10),$=l.startsWith("HTTP/1.0"),y=[],h=-1,w=!1,e=$,A=!1,m=!1,s=f===-1?n.length:f+2;while(s<n.length){let E=n.indexOf(`\r
159
- `,s);if(E===-1)E=n.length;let T=n.slice(s,E);if(s=E+2,T==="")continue;let B=T.indexOf(":");if(B===-1)continue;let F=T.slice(0,B),N=T.slice(B+1).trim(),R=F.charCodeAt(0)|32;if(R===99||R===116||R===107){let W=F.toLowerCase();if(W==="content-length"){let k=/^\d+$/.test(N)?Number(N):Number.NaN;if(!Number.isSafeInteger(k)||h>=0&&h!==k)m=!0;else h=k;continue}if(W==="transfer-encoding"){if(N.toLowerCase().includes("chunked"))w=!0;continue}if(W==="connection"){let k=N.toLowerCase();if(k.includes("close"))e=!0;if(k.includes("keep-alive"))A=!0;continue}if(W==="keep-alive")continue}y.push([F,N])}if($&&A)e=!1;if(w&&h>=0)h=-1;return{status:u,headerEnd:r,headers:y,contentLength:h,chunked:w,closeConn:e,malformed:m}}function Cm(i,t){return t||i===204||i===304}async function Nh(i){let{hostPort:t,method:r,path:n,reqHeaders:f,forwardedHost:l,originOverride:c,body:u}=i,$=r==="HEAD";if(f.get("expect")||f.get("upgrade"))throw qr;let y=null;if(u){let A=f.get("content-length"),m=A?Number.parseInt(A,10):Number.NaN;if(Number.isNaN(m)||m>Uh)throw qr;if(y=await Wm(u),y===null)throw qr}let h=Nm(r,n,f,t,l,c,y),w=h;if(y&&y.length)w=new Uint8Array(h.length+y.length),w.set(h),w.set(y,h.length);let e=Ym(t,i.maxPerHost??wm());for(let A=0;;A++){if(A>0)await new Promise((s)=>{setTimeout(s,A)});let m;try{m=e.acquireIdleSync()??await e.acquireOrDial()}catch(s){if(s!==Kt&&A<4)continue;throw s}try{let s=m.socket.write(w);if(s<w.length)await m.writeAll(w.subarray(s));return await Rm(e,m,$)}catch(s){let E=s===Wf&&A<4&&(m.fresh||cm(r));if(e.destroy(m),E)continue;if(s===Wf)throw Error("upstream closed connection");throw s}}}async function Um(i){let t=Ch(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw n0;if(i.len===i.pos)throw Wf;throw Error("upstream closed mid-header")}if(i.len-i.pos>Rh)throw Error("upstream header block too large");await i.waitForData(i.len),t=Ch(i.buf,i.len,i.pos)}return t}async function Rm(i,t,r){let n;for(;;){let l=await Um(t);if(n=Bm(t.buf,t.pos,l),t.pos=l+4,n.status>=100&&n.status<200)continue;break}if(n.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let f=n.headers;if(Cm(n.status,r))return Wh(i,t,n.closeConn),new Response(null,{status:n.status,headers:f});if(n.chunked)return new Response(Fm(i,t,n.closeConn),{status:n.status,headers:f});if(n.contentLength>=0){if(t.len-t.pos>=n.contentLength){let c=t.pos+n.contentLength,u=t.len>c,$=null;if(n.contentLength>=am)$=t.buf.subarray(t.pos,c),t.buf=new Uint8Array(mm);else if(n.contentLength>0)$=t.buf.slice(t.pos,c);if(t.pos=0,t.len=0,n.closeConn||u)i.destroy(t);else i.release(t);return new Response($,{status:n.status,headers:f})}return new Response(Sm(i,t,n.contentLength,n.closeConn),{status:n.status,headers:f})}return new Response(jm(t),{status:n.status,headers:f})}function Wh(i,t,r){if(r||t.pos!==t.len)i.destroy(t);else i.release(t)}function Sm(i,t,r,n){let f=t.len-t.pos,l=f>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=r-f,t.queuedBytes=0,t.streamingBody=!0;let c=(u)=>{if(t.bodyQueue=null,n||t.len>0)i.destroy(t);else i.release(t);u.close()};return new ReadableStream({start(u){if(l)u.enqueue(l);if(t.bodyRemaining===0&&t.bodyQueue.length===0)c(u)},async pull(u){for(;;){let $=t.bodyQueue;if($&&$.length>0){let y=$.shift();if(t.queuedBytes-=y.length,t.resumeIfDrained(),u.enqueue(y),t.bodyRemaining===0&&$.length===0)c(u);return}if(t.bodyRemaining===0){if(t.bodyQueue)c(u);return}if(t.closed){t.bodyQueue=null,i.destroy(t),u.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,i.destroy(t)}})}function jm(i){return i.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(i.len>i.pos){t.enqueue(i.buf.slice(i.pos,i.len)),i.pos=i.len,i.resumeIfDrained();return}if(i.closed){i.destroy(),t.close();return}await i.waitForData(i.len)}},cancel(){i.destroy()}})}function Fm(i,t,r){t.streamingBody=!0;let n=0,f=!1;async function l(){for(;;){for(let c=t.pos;c+1<t.len;c++)if(t.buf[c]===13&&t.buf[c+1]===10){let u=Sh.decode(t.buf.subarray(t.pos,c));return t.pos=c+2,u}if(t.closed)throw Error("upstream closed mid-chunk-header");if(t.len-t.pos>Rh)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({async pull(c){for(;;){if(n>0){if(t.len===t.pos){if(t.closed){i.destroy(t),c.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let h=Math.min(n,t.len-t.pos);if(c.enqueue(t.buf.slice(t.pos,t.pos+h)),t.pos+=h,n-=h,t.resumeIfDrained(),n===0)f=!0;return}if(f)await l(),f=!1;let u=await l(),$=u.indexOf(";"),y=Number.parseInt($===-1?u:u.slice(0,$),16);if(!Number.isInteger(y)||y<0){i.destroy(t),c.error(Error("upstream sent malformed chunk size"));return}if(y===0){for(;;)if(await l()==="")break;Wh(i,t,r),c.close();return}n=y}},cancel(){i.destroy(t)}})}function Nm(i,t,r,n,f,l,c){let u=`${i} ${t} HTTP/1.1\r
160
- host: ${n}\r
161
- x-forwarded-for: 127.0.0.1\r
162
- x-forwarded-proto: https\r
163
- x-forwarded-host: ${f}\r
164
- `;if(l!==void 0)u+=`origin: ${l}\r
165
- `;let $=!1;for(let[y,h]of r){let w=y.toLowerCase();if(Tm.has(w))continue;if(l!==void 0&&w==="origin")continue;if(w==="content-length")$=!0;u+=`${y}: ${h}\r
166
- `}if(u+=`connection: keep-alive\r
167
- `,c&&!$)u+=`content-length: ${c.length}\r
168
- `;return u+=`\r
169
- `,Em.encode(u)}async function Wm(i){let t=i.getReader(),r=[],n=0;for(;;){let{done:c,value:u}=await t.read();if(c)break;if(u){if(n+=u.length,n>Uh)return t.cancel().catch(()=>{}),null;r.push(u)}}if(r.length===1)return r[0];let f=new Uint8Array(n),l=0;for(let c of r)f.set(c,l),l+=c.length;return f}function PU(i){let t=typeof i==="string"?{to:i}:i,r=(t.to??"").trim();if(r&&!/^[a-z][\w+.-]*:\/\//i.test(r))r=`https://${r}`;return r=r.replace(/\/+$/,""),{to:r,status:t.status??301,preservePath:t.preservePath??!0}}function Xh(i,t,r){if(!i.preservePath)return i.to||"/";let n=`${t}${r}`;return n==="/"?`${i.to}/`:`${i.to}${n}`}import*as Ki from"node:path";function Jh(i,t){if(typeof i==="string")return{dir:i,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:i.dir,spa:i.spa??!1,pathRewriteStyle:i.pathRewriteStyle??"directory",maxAge:i.maxAge??0,cleanUrls:t}}var Xm={".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 Jm(i){let t=Ki.extname(i).toLowerCase();return Xm[t]??"application/octet-stream"}function Im(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=Ki.posix.normalize(`/${t}`);if(r.includes(".."))return null;return r.replace(/^\/+/,"")}function _m(i,t){let r=Im(i);if(r===null)return null;let n=Ki.posix.extname(r);if(t.cleanUrls&&n===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ki.join(t.dir,r),redirectTo:f||"/"}}if(r===""||i.endsWith("/"))return{filePath:Ki.join(t.dir,r,"index.html")};if(n!=="")return{filePath:Ki.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:Ki.join(t.dir,`${r}.html`)};return{filePath:Ki.join(t.dir,r,"index.html")}}async function Ih(i,t){let r=_m(i,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(r.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":Jm(r.filePath),"Cache-Control":n}});if(t.spa){let l=Ki.join(t.dir,"index.html"),c=Bun.file(l);if(await c.exists())return new Response(c,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}function Km(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var zm=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function Om(i){let t=i.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function zh(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let r=i.slice(t.length);return r===""?"/":r}return i}function _h(i,t,r){let n=t.sourceHost??"",l=t.stripBasePathPrefix??!1?zh(i,t.basePath):i,c=Kh(l,t.pathRewrites);if(c)n=c.targetHost,l=c.targetPath,a("request",`Path rewrite: ${i} → ${n}${l}`,r);return{targetHost:n,targetPath:l}}function Gm(i){let t=i.indexOf("://"),r=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let n=i.indexOf("?",r);if(n===-1)return{pathname:i.slice(r),search:""};return{pathname:i.slice(r,n),search:i.slice(n)}}function f0(i,t,r){let n=async(f,l)=>{let{pathname:c,search:u}=Gm(f.url),$=Om(f),y=i($,c);if(!y&&r){let m=await r($,c,f);if(m instanceof Response)return m;if(m&&m.retry)y=i($,c)}if(!y)return a("request",`No route found for host: ${$}`,t),new Response(`No proxy configured for ${$}`,{status:404});if(y.auth){let m=Bh(f,c,y.auth);if(m)return a("request",`401 challenge for ${$}${c}`,t),m}if(y.redirect){let m=Xh(y.redirect,c,u);return a("request",`${y.redirect.status} redirect ${$}${c} → ${m}`,t),new Response(null,{status:y.redirect.status,headers:{location:m}})}if(y.static){let s=y.stripBasePathPrefix??!0?zh(c,y.basePath):c;return Ih(s,y.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!l||!y.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:m,targetPath:s}=_h(c,y,t),E=`ws://${m}${s}${u}`,T={};for(let[N,R]of f.headers)if(!zm.has(N.toLowerCase())&&N.toLowerCase()!=="host")T[N]=R;T.host=m,T["x-forwarded-for"]="127.0.0.1",T["x-forwarded-proto"]="https",T["x-forwarded-host"]=$;let B={targetUrl:E,forwardHeaders:T};if(l.upgrade(f,{data:B})){a("ws",`upgraded ${$}${s} → ${E}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}if(!y.sourceHost)return new Response(`No upstream configured for ${$}`,{status:502});if(y.cleanUrls&&c.endsWith(".html")){let m=c.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let{targetHost:h,targetPath:w}=_h(c,y,t),e=y.changeOrigin?`http://${y.sourceHost}`:void 0,A=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD";try{return await Nh({hostPort:h,method:f.method,path:`${w}${u}`,reqHeaders:f.headers,forwardedHost:$,originOverride:e,body:f.body})}catch(m){if(m===n0)return a("request",`Upstream timeout for ${$}`,t),new Response("Gateway Timeout",{status:504});if(m===Kt)return a("request",`Upstream pool saturated for ${$}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(m===qr||!A)try{let s=new Headers(f.headers);if(s.set("host",h),s.set("x-forwarded-for","127.0.0.1"),s.set("x-forwarded-proto","https"),s.set("x-forwarded-host",$),e!==void 0)s.set("origin",e);return await fetch(`http://${h}${w}${u}`,{method:f.method,headers:s,body:f.body,redirect:"manual"})}catch(s){return a("request",`Proxy error for ${$}: ${s}`,t),new Response(`Proxy Error: ${s}`,{status:502})}return a("request",`Proxy error for ${$}: ${m}`,t),new Response(`Proxy Error: ${m}`,{status:502})}};return async(f,l)=>{try{return await n(f,l)}catch(c){return a("request",`Unhandled proxy handler error: ${c}`,t),new Response("Bad Gateway",{status:502})}}}function l0(i){let t=new WeakMap,r=Km();return{open(n){let{targetUrl:f,forwardHeaders:l}=n.data,c;try{c=new WebSocket(f,{headers:l})}catch($){a("ws",`failed to open upstream ${f}: ${$}`,i),n.close(1011,"upstream connect failed");return}c.binaryType="arraybuffer";let u={upstream:c,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(n,u),c.addEventListener("open",()=>{u.upstreamOpen=!0;for(let $ of u.pending)c.send($);u.pending=[],u.pendingBytes=0}),c.addEventListener("message",($)=>{n.send($.data)}),c.addEventListener("close",($)=>{try{n.close($.code||1000,$.reason||"")}catch{}}),c.addEventListener("error",()=>{a("ws",`upstream error for ${f}`,i);try{n.close(1011,"upstream error")}catch{}})},message(n,f){let l=t.get(n);if(!l)return;let c=typeof f==="string"?f:new Uint8Array(f);if(l.upstreamOpen){l.upstream.send(c);return}let u=typeof c==="string"?Buffer.byteLength(c):c.byteLength;if(l.pendingBytes+u>r){a("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,i);try{n.close(1009,"buffer limit")}catch{}try{l.upstream.close(1011,"client buffer overflow")}catch{}t.delete(n);return}l.pending.push(c),l.pendingBytes+=u},close(n,f,l){let c=t.get(n);if(!c)return;t.delete(n);try{c.upstream.close(f||1000,l||"")}catch{}}}}import*as Gh from"node:fs";import*as Mh from"node:path";var Oh="/.well-known/acme-challenge/";function Hh(i,t){if(!i||!t.startsWith(Oh))return null;let r=t.slice(Oh.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return Gh.readFileSync(Mh.join(i,r),"utf8")}catch{return null}}function Jf(i){return i.startsWith("*.")}function c0(i,t){if(!Jf(t))return!1;let r=t.slice(1);return i.length>r.length&&i.endsWith(r)}function dh(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[l,c]of i){if(!Jf(l))continue;if(c0(t,l)){let u=l.length-1;if(u>f)f=u,n=c}}return n}function zt(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function Mm(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function $0(i){let t=new Map;for(let n of i){let f=zt(n.path),l=t.get(n.host);if(!l)l=new Map,t.set(n.host,l);l.set(f,n.route)}let r=new Map;for(let[n,f]of t){let l=[];for(let[c,u]of f)l.push({path:c,route:u});l.sort((c,u)=>u.path.length-c.path.length),r.set(n,l)}return r}function u0(i,t){let r=i.get(t);if(r!==void 0)return r;let n,f=-1;for(let[l,c]of i){if(!Jf(l))continue;if(c0(t,l)){let u=l.length-1;if(u>f)f=u,n=c}}return n}function y0(i,t,r){let n=u0(i,t);if(!n)return;for(let f of n)if(Mm(r,f.path))return f.route;return}import*as Lr from"node:fs/promises";import*as h0 from"node:path";function Hm(i){if(!i.endsWith(".crt"))return null;let t=i.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function dm(i,t,r,n){try{let[f,l]=await Promise.all([Lr.readFile(t,"utf8"),Lr.readFile(r,"utf8")]);return{serverName:i,cert:f,key:l}}catch(f){return a("sni",`skipping ${i}: ${f.message}`,n),null}}async function w0(i,t){let r=new Map;if(i.certsDir){let f=[];try{f=await Lr.readdir(i.certsDir)}catch(l){a("sni",`certsDir read failed (${i.certsDir}): ${l.message}`,t)}for(let l of f){let c=Hm(l);if(!c)continue;let u=l.slice(0,-4);r.set(c,{certPath:h0.join(i.certsDir,l),keyPath:h0.join(i.certsDir,`${u}.key`)})}}if(i.domains)for(let[f,l]of Object.entries(i.domains))r.set(f,l);let n=[];for(let[f,l]of r){let c=await dm(f,l.certPath,l.keyPath,t);if(c)n.push(c)}return n}import*as Ct from"node:fs/promises";import*as e0 from"node:path";var gm=60000,gh=4096;function qm(i,t){if(!t||t.length===0)return!1;return t.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return i===n||i.endsWith(`.${n}`)})}function qh(i){if(!i||i.length>253)return!1;if(i.includes("/")||i.includes(":")||i.includes(" "))return!1;if(i.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(i)}class If{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??zn,this.issuer=i.issuer??zl,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??gm;for(let t of i.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(i){return this.certs.has(i)}async isApproved(i){if(!qh(i))return!1;if(qm(i,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(i)}catch(t){return a("on-demand",`ask(${i}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(i){if(!this.config.enabled)return!1;if(this.certs.has(i))return!0;if(!qh(i))return!1;let t=this.inFlight.get(i);if(t)return t;let r=this.negativeCache.get(i);if(r!==void 0&&Date.now()<r)return a("on-demand",`${i} negatively cached for ${r-Date.now()}ms`,this.verbose),!1;let n=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,n),n}async issue(i){if(this.certs.has(i))return!0;if(await this.loadFromDisk(i))return!0;if(!await this.isApproved(i))return a("on-demand",`refused issuance for ${i} (not approved)`,this.verbose),this.cacheNegative(i),!1;try{a("on-demand",`issuing cert for ${i} (staging=${this.config.staging??!1})`,this.verbose);let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(i,t.fullChainPem,t.keyPem);let r={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,r),this.negativeCache.delete(i),a("on-demand",`issued + installed cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(i),a("on-demand",`issuance for ${i} failed: ${t.message}`,this.verbose),!1}}cacheNegative(i){if(this.negativeCache.size>=gh){let t=Date.now();for(let[r,n]of this.negativeCache)if(n<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=gh){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:r}=this.pathsFor(i);try{let[n,f]=await Promise.all([Ct.readFile(t,"utf8"),Ct.readFile(r,"utf8")]),l={serverName:i,cert:n,key:f};return this.certs.set(i,l),a("on-demand",`adopted existing on-disk cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(i){return{certPath:e0.join(this.certsDir,`${i}.crt`),keyPath:e0.join(this.certsDir,`${i}.key`)}}async persist(i,t,r){await Ct.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:f}=this.pathsFor(i);await Promise.all([Ct.writeFile(n,t,"utf8"),Ct.writeFile(f,r,{encoding:"utf8",mode:384})])}}import{existsSync as Lm,readdirSync as xm,readFileSync as km,statSync as Vm}from"node:fs";import{homedir as kh}from"node:os";import{isAbsolute as Dm,join as sr}from"node:path";var Vh=["~/Code"],Dh=["localhost","test"],bm=1800000,A0={dirExists:(i)=>{try{return Vm(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return Lm(i)}catch{return!1}},readText:(i)=>{try{return km(i,"utf8")}catch{return null}}};function s0(i,t){if(i==="~")return t;if(i.startsWith("~/"))return sr(t,i.slice(2));return i}function Qm(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function Lh(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function om(i,t){for(let r of t){let n=`.${r}`;if(i.endsWith(n)){let f=i.slice(0,-n.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function Pm(i,t){let r=t.readText(sr(i,"rpx.site.json"));if(r)try{let f=JSON.parse(r);if(f&&typeof f==="object")return f}catch{}let n=t.readText(sr(i,"package.json"));if(n)try{let f=JSON.parse(n);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function vm(i){let t=i.selfRegisters??!1;return{command:i.command,env:i.env,urlEnv:i.urlEnv,selfRegisters:t,routes:i.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function Zm(i,t){let r=Pm(i,t);if(r?.command)return vm(r);let n=t.fileExists(sr(i,"buddy")),f=t.readText(sr(i,"package.json")),l=null;if(f)try{l=JSON.parse(f)}catch{l=null}let c={...l?.dependencies??{},...l?.devDependencies??{}};if(n||Object.keys(c).some(($)=>$==="stacks"||$.startsWith("@stacksjs/")))return{command:n?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(l?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function a0(i,t={}){let r={dirExists:t.dirExists??A0.dirExists,fileExists:t.fileExists??A0.fileExists,readText:t.readText??A0.readText},n=t.detect??Zm,f=t.homeDir??kh(),l=i.tlds??Dh,c=(i.roots??Vh).map((e)=>s0(e,f)),u=i.idleTimeoutMs??bm,$=new Map;for(let e of i.sites??[])$.set(e.to,e);let y=(e)=>e.idleTimeoutMs??u;function h(e){let A=dh($,e);if(!A)return null;let m=Dm(A.dir)?A.dir:s0(A.dir,f),s=A.selfRegisters??!1,E=A.routes??[];if(!s&&E.length===0)E=n(m,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let T=xh({...A.env??{}},void 0,e);return{host:e,id:Lh(e),dir:m,command:A.command,env:T,routes:E,selfRegisters:s,idleTimeoutMs:y(A),source:"config"}}function w(e){let A=om(e,l);if(!A)return null;for(let m of c){let s=sr(m,A);if(!r.dirExists(s))continue;let E=n(s,r);if(!E)continue;let T=E.selfRegisters??!1;return{host:e,id:Lh(e),dir:s,command:E.command,env:xh({...E.env??{}},E.urlEnv,e),routes:T?[]:E.routes??[],selfRegisters:T,idleTimeoutMs:u,source:"discovered"}}return null}return{resolve(e){let A=Qm(e);if(!A)return null;return h(A)??w(A)}}}function pm(i){try{return xm(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function TR(i,t={}){let r=t.homeDir??kh(),n=i.tlds??Dh,f=(i.roots??Vh).map((w)=>s0(w,r)),l=t.readdir??pm,c=a0(i,t),u=[],$=new Set,y=(w)=>{if(w&&!$.has(w.host))$.add(w.host),u.push(w)};for(let w of i.sites??[])if(!w.to.includes("*"))y(c.resolve(w.to));let h=n[0]??"localhost";for(let w of f)for(let e of l(w))y(c.resolve(`${e}.${h}`));return u}function xh(i,t,r){if(!t)return i;let n=`https://${r}`;for(let f of t)if(i[f]===void 0)i[f]=n;return i}import{closeSync as Zh,openSync as fE,readFileSync as lE}from"node:fs";import*as ph from"node:fs/promises";import{spawn as cE}from"node:child_process";import{homedir as $E}from"node:os";import*as kr from"node:path";import*as xi from"node:process";import*as _f from"node:net";function Qh(i,t,r){return a("port",`Checking if port ${i} is in use on ${t}`,r),new Promise((n)=>{let f=_f.createServer(),l=setTimeout(()=>{a("port",`Checking port ${i} timed out, assuming it's in use`,r),f.close(),n(!0)},3000);f.once("error",(c)=>{if(clearTimeout(l),c.code==="EADDRINUSE")a("port",`Port ${i} is in use`,r),n(!0);else a("port",`Error checking port ${i}: ${c.message}`,r),n(!0)}),f.once("listening",()=>{clearTimeout(l),a("port",`Port ${i} is available`,r),f.close(),n(!1)});try{f.listen(i,t)}catch(c){clearTimeout(l),a("port",`Exception checking port ${i}: ${c}`,r),n(!0)}})}async function m0(i,t,r,n=50){a("port",`Finding available port starting from ${i} (max attempts: ${n})`,r);let f=i,l=0;while(l<n){if(l++,!await Qh(f,t,r))return a("port",`Found available port: ${f} after ${l} attempts`,r),f;a("port",`Port ${f} is in use, trying ${f+1} (attempt ${l}/${n})`,r),f++}throw Error(`Unable to find available port after ${n} attempts starting from ${i}`)}function bh(i,t,r=5000,n){return a("port",`Testing connection to ${t}:${i}`,n),new Promise((f)=>{let l=_f.connect({host:t,port:i,timeout:r});l.once("connect",()=>{a("port",`Successfully connected to ${t}:${i}`,n),l.end(),f(!0)}),l.once("timeout",()=>{a("port",`Connection to ${t}:${i} timed out`,n),l.destroy(),f(!1)}),l.once("error",(c)=>{a("port",`Failed to connect to ${t}:${i}: ${c.message}`,n),l.destroy(),f(!1)})})}class oh{usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,r=50){this.hostname=i,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await Qh(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await bh(i,this.hostname,3000,this.verbose))return a("port",`Port ${i} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(i+1,t)}return this.usedPorts.add(i),i}async findNextAvailablePort(i,t=!1){let r=await m0(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await bh(r,this.hostname,3000,this.verbose))if(r<i+this.maxRetries)return this.findNextAvailablePort(r+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(r),r}releasePort(i){a("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var CR=new oh;import*as Kf from"node:fs";import*as Yi from"node:fs/promises";import{homedir as iE}from"node:os";import*as E0 from"node:path";import*as zf from"node:process";var tE=/^[a-zA-Z0-9._-]+$/;function Ut(){return E0.join(iE(),".stacks","rpx","registry.d")}function T0(i){return typeof i==="string"&&i.length>0&&i.length<=128&&tE.test(i)}function Y0(i,t){if(!T0(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return E0.join(i,`${t}.json`)}function Li(i){if(!Number.isInteger(i)||i<=0)return!1;try{return zf.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function Ph(i){if(!i||typeof i!=="object")return!1;let t=i,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,n=typeof t.from==="string"&&t.from.length>0,f=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",l=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&T0(t.id)&&(n||f)&&typeof t.to==="string"&&t.to.length>0&&l&&r&&typeof t.createdAt==="string"}async function rE(i){await Yi.mkdir(i,{recursive:!0})}async function vh(i,t=Ut(),r){if(!Ph(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await rE(t);let n=Y0(t,i.id),f=`${n}.tmp.${zf.pid}.${Date.now()}`,l=JSON.stringify(i,null,2);try{await Yi.writeFile(f,l,{encoding:"utf8",mode:420}),await Yi.rename(f,n),a("registry",`wrote entry ${i.id} → ${n}`,r)}catch(c){throw await Yi.unlink(f).catch(()=>{}),c}}async function B0(i,t=Ut(),r){let n=Y0(t,i);try{await Yi.unlink(n),a("registry",`removed entry ${i}`,r)}catch(f){if(f.code!=="ENOENT")throw f}}async function nE(i,t=Ut(),r){let n=Y0(t,i);try{let f=await Yi.readFile(n,"utf8"),l=JSON.parse(f);if(!Ph(l))return a("registry",`entry ${i} failed validation, removing`,r),await Yi.unlink(n).catch(()=>{}),null;return l}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return a("registry",`entry ${i} has invalid JSON, removing`,r),await Yi.unlink(n).catch(()=>{}),null;throw f}}async function yt(i=Ut(),t){let r;try{r=await Yi.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let n=[];for(let f of r){if(!f.endsWith(".json"))continue;let l=f.slice(0,-5);if(!T0(l))continue;let c=await nE(l,i,t);if(c)n.push(c)}return n}async function xr(i=Ut(),t){let r=await yt(i,t),n=0;for(let f of r){if(f.pid===void 0)continue;if(!Li(f.pid))a("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await B0(f.id,i,t).catch(()=>{}),n++}return n}function Of(i,t={}){let r=t.dir??Ut(),n=t.debounceMs??100,f=t.pollMs??Math.max(n*2,250),l=t.verbose;Kf.mkdirSync(r,{recursive:!0});let c=null,u=!1,$=null,y=!1,h=(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,B)=>T.id.localeCompare(B.id)))},w=()=>{if(c=null,u)return;yt(r,l).then((E)=>{return $=h(E),i(E)}).catch((E)=>{a("registry",`watcher onChange failed: ${E}`,l)})},e=()=>{if(u)return;if(c)clearTimeout(c);c=setTimeout(w,n)},m=setInterval(()=>{if(u||y)return;y=!0,yt(r,l).then((E)=>{if(h(E)!==$)e()}).catch((E)=>{a("registry",`watcher poll failed: ${E}`,l)}).finally(()=>{y=!1})},f),s=Kf.watch(r,{persistent:!0},(E,T)=>{if(T&&/\.tmp\.\d+\.\d+$/.test(T))return;e()});return s.on("error",(E)=>{a("registry",`watcher error: ${E}`,l)}),e(),{close:()=>{if(u=!0,c)clearTimeout(c);clearInterval(m),s.close()}}}var uE=120000,yE=200,hE=30000,wE=3000,eE=4000;class U0{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(i){this.resolver=i.resolver,this.registryDir=i.registryDir??Ut(),this.rpxDir=i.rpxDir??kr.join($E(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??uE,this.pollIntervalMs=i.pollIntervalMs??yE,this.restartDelayMs=i.restartDelayMs??wE,this.killGraceMs=i.killGraceMs??eE,this.launch=i.launcher??sE(this.verbose),this.probePort=i.probePort??AE,this.pickPort=i.pickPort??((r)=>m0(r,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??vh,this.removeEntry=i.removeEntry??B0;let t=i.reapIntervalMs??hE;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(i){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(i);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(i),t=void 0;if(!t){let r=this.resolver.resolve(i);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:i};if(t.status==="failed")return{kind:"failed",host:i,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:i,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(i){try{this.onSiteActivating?.(i.host)}catch{}let t=new Map;if(!i.selfRegisters)for(let u of i.routes){if(t.has(u.portEnv))continue;let $=await this.pickPort(u.defaultPort??3000);t.set(u.portEnv,$)}let r=kr.join(this.rpxDir,"sites",`${i.id}.log`);await ph.mkdir(kr.dirname(r),{recursive:!0}).catch(()=>{});let n=this.buildEnv(i,t),f=null,l;try{f=this.launch({command:i.command,cwd:i.dir,env:n,logPath:r})}catch(u){l=`failed to spawn: ${u.message}`}let c={site:i,status:l?"failed":"starting",handle:f,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:l?this.now():0,error:l,logPath:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,c),l)return j.warn(`rpx: site ${i.host} ${l}`),c;return j.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),f.exited.then((u)=>this.onProcessExit(c,u)).catch(()=>{}),c.ready=this.driveReadiness(c).catch((u)=>{a("sites",`readiness loop for ${i.host} threw: ${u}`,this.verbose)}),c}async onProcessExit(i,t){if(i.exited=!0,this.stopped||this.sites.get(i.site.host)!==i)return;if(i.status==="ready"){j.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let r of i.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(i.status==="starting")this.fail(i,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(i){let{site:t}=i,r=this.now()+this.startupTimeoutMs,n=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<r&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await n()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",j.success(`rpx: ${t.host} ready`);return}await C0(this.pollIntervalMs)}if(i.status==="starting")this.fail(i,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(i,t){let r=i.routes.filter((f)=>f.readyGate??zt(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),n=r.length>0?r:[...t.values()];return async()=>{for(let f of n)if(!await this.probePort(f))return!1;return n.length>0}}async publishRoutes(i){let{site:t,ports:r}=i;if(t.selfRegisters||t.routes.length===0)return;let n=t.routes.find(($)=>zt($.path)==="/")??t.routes[0],f=r.get(n.portEnv);if(f===void 0)return;let l=[];for(let $ of t.routes){if($===n)continue;let y=r.get($.portEnv);if(y===void 0)continue;l.push({from:zt($.path),to:`localhost:${y}`,stripPrefix:$.stripPrefix??!1})}let c={id:t.id,from:`localhost:${f}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:l.length>0?l:void 0,pid:i.handle?.pid};await this.writeEntry(c,this.registryDir,this.verbose),i.routeIds=[t.id];let u=this.now()+2000;while(this.now()<u&&!this.isHostRoutable(t.host))await C0(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),j.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let r={};for(let[n,f]of Object.entries(xi.env))if(typeof f==="string")r[n]=f;Object.assign(r,i.env);for(let[n,f]of t)r[n]=String(f);return r.RPX_SITE_HOST=i.host,r.RPX_SITE_URL=`https://${i.host}`,r}readLogTail(i,t=40){try{return lE(i.logPath,"utf8").split(`
170
- `).slice(-t).join(`
171
- `).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),j.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let r=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof r.unref==="function")r.unref();await Promise.race([t.exited.catch(()=>{}),C0(this.killGraceMs+500)]),clearTimeout(r)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,r]of this.sites){let n=r.site.idleTimeoutMs;if(n<=0)continue;let f=i-r.lastAccess;if((r.status==="ready"||i-r.startedAt>this.startupTimeoutMs)&&f>n)a("sites",`reaping ${t} (idle ${Math.round(f/1000)}s)`,this.verbose),await this.stop(t)}}list(){let i=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:i-t.startedAt,idleMs:i-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((i)=>this.stop(i)))}}function C0(i){return new Promise((t)=>setTimeout(t,i))}async function AE(i){let t=new AbortController,r=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${i}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(r)}}function sE(i){let t=aE();return({command:r,cwd:n,env:f,logPath:l})=>{let c=fE(l,"a");try{let u=cE("sh",["-c",r],{cwd:n,env:f,detached:!0,stdio:["ignore",c,c],...t?{uid:t.uid,gid:t.gid}:{}}),$=u.pid;if($===void 0)throw Error("spawn returned no pid");let y=new Promise((h)=>{u.once("exit",(w)=>{h(w)}),u.once("error",()=>{h(null)})}).finally(()=>{try{Zh(c)}catch{}});return a("sites",`spawned pid ${$}: sh -c ${r} (cwd ${n})`,i),{pid:$,exited:y,stop:(h="SIGTERM")=>{try{xi.kill(-$,h)}catch{try{u.kill(h)}catch{}}}}}catch(u){try{Zh(c)}catch{}throw u}}}function aE(){if(xi.platform==="win32")return null;if(!(typeof xi.getuid==="function"&&xi.getuid()===0))return null;let t=Number.parseInt(xi.env.SUDO_UID??"",10),r=Number.parseInt(xi.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(r)||r<=0)return null;return{uid:t,gid:r}}function ar(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var mE=`
172
- :root { color-scheme: light dark }
173
- * { box-sizing: border-box }
174
- body {
175
- margin: 0; min-height: 100vh; display: grid; place-items: center;
176
- font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
177
- background: #0b0c0f; color: #e7e9ee;
178
- }
179
- .card { width: min(92vw, 540px); padding: 2.25rem 2.5rem; }
180
- .row { display: flex; align-items: center; gap: .75rem; }
181
- h1 { font-size: 1.15rem; margin: 0; font-weight: 600; letter-spacing: -.01em }
182
- p { margin: .5rem 0 0; color: #9aa1ad }
183
- code { color: #cbd2dc; background: #16181d; padding: .1rem .4rem; border-radius: 5px }
184
- pre {
185
- margin: 1.25rem 0 0; padding: 1rem; max-height: 40vh; overflow: auto;
186
- background: #16181d; border: 1px solid #23262d; border-radius: 8px;
187
- font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color: #aeb6c2;
188
- white-space: pre-wrap; word-break: break-word;
189
- }
190
- .spinner {
191
- width: 16px; height: 16px; border-radius: 50%;
192
- border: 2px solid #3a3f4b; border-top-color: #8ab4f8;
193
- animation: spin .8s linear infinite;
194
- }
195
- .dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
196
- @keyframes spin { to { transform: rotate(360deg) } }
197
- `;function iw(i,t,r){return`<!doctype html>
198
- <html lang="en">
199
- <head>
200
- <meta charset="utf-8">
201
- <meta name="viewport" content="width=device-width, initial-scale=1">
202
- ${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
203
- <title>${ar(i)}</title>
204
- <style>${mE}</style>
205
- </head>
206
- <body><main class="card">${t}</main></body>
207
- </html>`}function tw(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),r=i.logTail?`<pre>${ar(i.logTail)}</pre>`:"",n=`
208
- <div class="row"><div class="spinner"></div><h1>Starting ${ar(i.host)}…</h1></div>
209
- <p>rpx is booting this site's dev server on demand. This page reloads itself —
210
- it'll switch to the app as soon as it's ready (usually a few seconds).</p>
211
- <p>Booting for ${t}s.</p>
212
- ${r}`;return new Response(iw(`Starting ${i.host}`,n,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function rw(i){let t=i.logTail?`<pre>${ar(i.logTail)}</pre>`:"<p>No output was captured.</p>",r=`
213
- <div class="row"><div class="dot"></div><h1>${ar(i.host)} failed to start</h1></div>
214
- <p>${ar(i.error)}</p>
215
- ${t}
216
- <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(iw(`${i.host} failed`,r,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var EE=5000;function Bi(){return Di.join(uw(),".stacks","rpx")}function Mf(i=Bi()){return Di.join(i,"daemon.pid")}async function Er(i=Bi()){try{let t=await Ai.readFile(Mf(i),"utf8"),r=Number.parseInt(t.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(t){if(t.code==="ENOENT")return null;throw t}}async function TE(i=Bi()){let t=await Er(i);return t!==null&&Li(t)}async function yw(i=Bi()){await Ai.mkdir(i,{recursive:!0});let t=Mf(i);while(!0){try{let n=await Ai.open(t,"wx");try{await n.write(`${Y.pid}
217
- `)}finally{await n.close()}return t}catch(n){if(n.code!=="EEXIST")throw n}let r=await Er(i);if(r!==null&&Li(r))throw Error(`rpx daemon already running (pid=${r})`);await Ai.unlink(t).catch(()=>{})}}async function mr(i=Bi()){await Ai.unlink(Mf(i)).catch(()=>{})}function hw(i){let t=i.cleanUrls??!1,r=zt(i.path),n=Yh(i.auth);if(i.static)return{static:Jh(i.static,t),cleanUrls:t,basePath:r,auth:n};let f=i.from??"localhost:1";return{sourceHost:new URL(f.startsWith("http")?f:`http://${f}`).host,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:r,auth:n}}function YE(i){return i.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??i[0]??"rpx.localhost"}async function Gf(i,t,r=[],n=!1){let f=await yt(t,i.verbose),l=[...new Set([...f.map((h)=>h.to).filter(Boolean),...r])],c=YE(l),u=[...new Set([c,...l,"rpx.localhost"])],$=Ah(l,c,i.verbose);if(typeof i.https==="object"&&typeof $.https==="object")$.https={...$.https,...i.https};let y=await i0($);if(y&&(n||!kc(vc,u)))a("daemon",`regenerating shared cert for host(s): ${u.join(", ")}`,i.verbose),pc(),y=null;if(!y)a("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await ah({...$,forceRegenerate:!0}),y=await i0($);if(!y)throw Error("failed to bootstrap TLS for rpx daemon");return y}async function BE(i,t,r,n){let f=Y.env.SUDO_PASSWORD,l=Y.env.HOME??uw(),c=[Y.execPath,...Y.argv.slice(1)],u=[`HOME=${l}`,`PATH=${Y.env.PATH??""}`];if(n)u.push("RPX_VERBOSE=1");for(let[m,s]of Object.entries(Y.env))if(s!==void 0&&m!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(m))u.push(`${m}=${s}`);let $=f?["-S","-p","","env",...u,...c]:["-n","env",...u,...c];a("daemon",`elevating daemon via sudo for privileged ports ${t}/${r}`,n);let y=$w("sudo",$,{detached:!0,stdio:["pipe","ignore","ignore"]}),h=null,w=null;if(y.once("error",(m)=>{h=m}),y.once("exit",(m)=>{w=m??0}),f&&y.stdin)y.stdin.write(`${f}
218
- `),y.stdin.end();y.unref();let e=Mf(i),A=Date.now()+15000;while(Date.now()<A){if(h)throw h;let m=await Er(i);if(m!==null&&Li(m)){if(n)j.success(`rpx daemon elevated to root (pid=${m}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:e,done:Promise.resolve(),stop:async()=>{try{Y.kill(m,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(w!==null&&w!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${w}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((s)=>setTimeout(s,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${i})`)}var nw=!1;function R0(){if(nw)return;nw=!0,Y.on("uncaughtException",(i)=>{j.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),Y.on("unhandledRejection",(i)=>{j.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function ww(i,t,r){let n;try{n=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let f=(i.headers.get("host")??n.hostname).split(":")[0];if(n.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let l=t.challengeStore.handlePath(n.pathname);if(l!==void 0)return new Response(l,{status:200,headers:{"content-type":"text/plain"}})}if(r){let l=Hh(r,n.pathname);if(l!=null)return new Response(l,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(f))t.ensureCert(f).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${f}${n.pathname}${n.search}`}})}async function iS(i={}){R0();let t=i.verbose??!1,r=i.rpxDir??Bi(),n=i.registryDir??Di.join(r,"registry.d"),f=i.httpsPort??443,l=i.httpPort??80,c=i.hostname??"0.0.0.0",u=i.gcIntervalMs??EE;if(Y.env.RPX_DAEMON_WORKER==="1")return RE({rpxDir:Y.env.RPX_WORKER_RPXDIR??r,registryDir:Y.env.RPX_WORKER_REGISTRYDIR??n,httpsPort:Number.parseInt(Y.env.RPX_WORKER_HTTPSPORT??"",10)||f,hostname:Y.env.RPX_WORKER_HOSTNAME??c,verbose:Y.env.RPX_WORKER_VERBOSE==="1"||t});let $=f>0&&f<1024||l>0&&l<1024,y=typeof Y.getuid==="function"&&Y.getuid()===0;if(Y.platform!=="win32"&&$&&!y)return BE(r,f,l,t);let h=Math.max(1,i.workers??(Number.parseInt(Y.env.RPX_WORKERS??"",10)||1));if(h>1){if(i.onDemandSites?.enabled)j.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return SE(i,{rpxDir:r,registryDir:n,httpsPort:f,httpPort:l,hostname:c,verbose:t,gcIntervalMs:u,workers:h})}let w=await yw(r),e=new Map,A=(C,X)=>y0(e,C,X);function m(C){e=$0(C.map((et)=>({host:et.to,path:et.path,route:hw(et)})));let X=Array.from(e.keys());a("daemon",`routing table now covers ${X.length} host(s): ${X.join(", ")||"<empty>"}`,t)}await xr(n,t).catch((C)=>{a("daemon",`initial gc failed: ${C}`,t)});let s=await yt(n,t);m(s),await Yr({rpxDir:r,verbose:t}).catch((C)=>{a("daemon",`DNS reconcile on start failed: ${C}`,t)}),await Vr(s,{rpxDir:r,verbose:t,ownerPid:Y.pid}).catch((C)=>{a("daemon",`DNS setup on start failed: ${C}`,t)});let E=[];if(i.productionCerts){if(E=await w0(i.productionCerts,t),t&&E.length>0)j.info(`SNI: serving ${E.length} real cert(s): ${E.map((C)=>C.serverName).join(", ")}`)}let T=new Set,B=null,F;if(i.onDemandSites?.enabled){if(B=new U0({resolver:a0(i.onDemandSites),registryDir:n,rpxDir:r,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(C)=>u0(e,C)!==void 0,onSiteActivating:(C)=>{Nt(C)}}),F=async(C)=>{let X=await B.onRequest(C);switch(X.kind){case"ready":return{retry:!0};case"starting":return tw({host:X.host,sinceMs:X.sinceMs,logTail:X.logTail});case"failed":return rw({host:X.host,error:X.error,logTail:X.logTail});case"unknown":default:return}},t)j.info("rpx: on-demand sites enabled")}let N=f0(A,t,F),R=l0(t),W=null;if(E.length===0)W=await Gf(i,n);let k=i.onDemandTls,fi=k?.enabled?new If({config:k,certsDir:k.certsDir??i.productionCerts?.certsDir??Di.join(r,"on-demand-certs"),initial:E,verbose:t,onCertAdded:(C)=>{Gt(C)}}):null;function ki(C){if(C.length>0)return C.map((X)=>({serverName:X.serverName,cert:X.cert,key:X.key}));return{key:W.key,cert:W.cert,ca:W.ca,requestCert:!1,rejectUnauthorized:!1}}function Qr(C){return Bun.serve({port:f,hostname:c,reusePort:cw(),tls:ki(C),fetch(X,et){return N(X,et)},websocket:R,error(X){return a("daemon",`https server error: ${X}`,t),new Response(`Server Error: ${X.message}`,{status:500})}})}let St=(C)=>[...new Set(C.map((X)=>X.to).filter(Boolean))],Ot=(C)=>{if(!W)return E;return eh([...St(C),...T,"rpx.localhost"],W)},wt=Qr(fi?fi.sniEntries():E.length>0?E:Ot(s)),jt=null,Ft=!1;async function Gt(C){if(Vi)return;if(jt=C,Ft)return;Ft=!0;try{while(!Vi&&jt){let X=jt;jt=null,a("daemon",`rebuilding :443 with ${X.length} SNI cert(s)`,t),wt.stop(!1);let et,kf=!1,K0=60,Fw=500;for(let Vf=0;!Vi&&!kf;Vf++)try{wt=Qr(X),kf=!0;break}catch(Nw){if(et=Nw,Vf>=K0)break;await new Promise((Ww)=>setTimeout(Ww,Math.min(25*2**Math.min(Vf,4),Fw)))}if(!kf)j.error(`rpx: CRITICAL — could not rebind :443 after ${K0} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${et?.message}`)}}finally{Ft=!1}}let bi=null;if(l>0)bi=Bun.serve({port:l,hostname:c,fetch(C){return ww(C,fi,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)j.success(`rpx daemon listening on https://${c}:${f}${bi?` (http→https on :${l})`:""}`),j.info(`pid file: ${w}`),j.info(`registry: ${n}`);async function J(C){if(Vi||E.length>0||fi||!W)return;try{W=await Gf(i,n,[...T]),await Gt(Ot(C))}catch(X){a("daemon",`TLS sync on registry change failed: ${X}`,t)}}async function Nt(C){if(Vi||E.length>0||fi||!W||!C)return;if(T.has(C))return;T.add(C);try{W=await Gf(i,n,[...T],!0);let X=await yt(n,t);await Gt(Ot(X))}catch(X){a("daemon",`dev cert refresh for ${C} failed: ${X}`,t)}}let Lf=Of((C)=>{m(C),J(C),Vr(C,{rpxDir:r,verbose:t,ownerPid:Y.pid}).catch((X)=>{a("daemon",`DNS sync on registry change failed: ${X}`,t)})},{dir:n,verbose:t}),Mt=setInterval(()=>{xr(n,t).then((C)=>{if(C>0)a("daemon",`gc reaped ${C} stale entries`,t)}).catch((C)=>{a("daemon",`periodic gc failed: ${C}`,t)})},u);if(typeof Mt.unref==="function")Mt.unref();let Vi=!1,Br,Ht=new Promise((C)=>{Br=C});async function xf(){if(Vi)return Ht;if(Vi=!0,clearInterval(Mt),Lf.close(),await B?.stopAll().catch((C)=>{a("daemon",`site supervisor stopAll failed: ${C}`,t)}),wt.stop(!1),bi?.stop(!1),await Tr({rpxDir:r,verbose:t}).catch((C)=>{a("daemon",`DNS teardown failed: ${C}`,t)}),await mr(r),t)j.info("rpx daemon stopped");return Br(),Ht}let _0=(C)=>{a("daemon",`received ${C}, shutting down`,t),xf().catch(()=>{})};return Y.once("SIGINT",_0),Y.once("SIGTERM",_0),{stop:xf,done:Ht,httpsPort:typeof wt.port==="number"?wt.port:f,httpPort:bi&&typeof bi.port==="number"?bi.port:l,pidPath:w,ensureCert:(C)=>fi?fi.ensureCert(C):Promise.resolve(!1),listSites:()=>B?.list()??[]}}function S0(i){return Di.join(i,"cluster-sni.json")}async function fw(i,t,r){let n=S0(i),f=`${n}.${Y.pid}.tmp`;await Ai.writeFile(f,JSON.stringify({sni:t,dev:r}),"utf8"),await Ai.rename(f,n)}async function lw(i){try{return JSON.parse(await Ai.readFile(S0(i),"utf8"))}catch{return{sni:[],dev:null}}}function CE(i){if(i.sni.length>0)return i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key}));if(i.dev)return{key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function UE(){let i=Y.execPath,t=Y.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let r=Di.basename(i).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&Y.argv[1])return[i,Y.argv[1],"daemon:start"];return[i,"daemon:start"]}async function RE(i){R0();let{rpxDir:t,registryDir:r,httpsPort:n,hostname:f,verbose:l}=i,c=new Map,u=(R,W)=>y0(c,R,W),$=(R)=>{c=$0(R.map((W)=>({host:W.to,path:W.path,route:hw(W)})))};$(await yt(r,l));let y=f0(u,l),h=l0(l),w=!1,e=(R)=>Bun.serve({port:n,hostname:f,reusePort:!0,tls:CE(R),fetch(W,k){return y(W,k)},websocket:h,error(W){return a("daemon",`worker https error: ${W}`,l),new Response(`Server Error: ${W.message}`,{status:500})}}),A=e(await lw(t));async function m(){if(w)return;let R=await lw(t),W=null;for(let fi=0;fi<20&&!w;fi++)try{W=e(R);break}catch{await new Promise((ki)=>setTimeout(ki,25))}if(!W){a("daemon","worker reloadTls: could not bind new listener; keeping current",l);return}let k=A;A=W,k.stop(!1)}let s=Of((R)=>$(R),{dir:r,verbose:l}),E=()=>{m().catch(()=>{})};Y.on("SIGHUP",E);let T,B=new Promise((R)=>{T=R});async function F(){if(w)return B;return w=!0,Y.off("SIGHUP",E),s.close(),A.stop(!1),T(),B}let N=()=>{F().then(()=>Y.exit(0)).catch(()=>Y.exit(0))};if(Y.once("SIGTERM",N),Y.once("SIGINT",N),l)j.success(`rpx worker (pid ${Y.pid}) serving :${n}`);return{stop:F,done:B,httpsPort:typeof A.port==="number"?A.port:n,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function SE(i,t){R0();let{rpxDir:r,registryDir:n,httpsPort:f,httpPort:l,hostname:c,verbose:u,gcIntervalMs:$,workers:y}=t,h=await yw(r),w=[];if(i.productionCerts)w=await w0(i.productionCerts,u);let e=null;if(w.length===0)e=await Gf(i,n);let A=e?{key:e.key,cert:e.cert,ca:Array.isArray(e.ca)?e.ca.join(`
219
- `):e.ca}:null,m=!1,s=[];function E(J){for(let Nt of s)try{Nt.kill(J)}catch{}}async function T(J){await fw(r,J,A),E("SIGHUP")}let B=i.onDemandTls,F=B?.enabled?new If({config:B,certsDir:B.certsDir??i.productionCerts?.certsDir??Di.join(r,"on-demand-certs"),initial:w,verbose:u,onCertAdded:(J)=>{T(J)}}):null;await fw(r,F?F.sniEntries():w,A);let N=await yt(n,u);await Yr({rpxDir:r,verbose:u}).catch((J)=>{a("daemon",`DNS reconcile on start failed: ${J}`,u)}),await Vr(N,{rpxDir:r,verbose:u,ownerPid:Y.pid}).catch((J)=>{a("daemon",`DNS setup on start failed: ${J}`,u)}),await xr(n,u).catch(()=>{});let R=Of((J)=>{Vr(J,{rpxDir:r,verbose:u,ownerPid:Y.pid}).catch((Nt)=>{a("daemon",`DNS sync on registry change failed: ${Nt}`,u)})},{dir:n,verbose:u}),W=setInterval(()=>{xr(n,u).catch(()=>{})},$);W.unref?.();let k=null;if(l>0)k=Bun.serve({port:l,hostname:c,fetch(J){return ww(J,F,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let fi=10,ki=60000,Qr=30000,St=0,Ot=Date.now();function wt(){if(m)return;let J={...Y.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:n,RPX_WORKER_HTTPSPORT:String(f),RPX_WORKER_HOSTNAME:c,RPX_WORKER_VERBOSE:u?"1":"0"},Nt=Bun.spawn(UE(),{env:J,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(Lf,Mt){if(m)return;let Vi=s.indexOf(Lf);if(Vi!==-1)s.splice(Vi,1);let Br=Date.now();if(Br-Ot>ki)Ot=Br,St=0;if(St++,St>fi){j.error(`rpx: worker keeps exiting (code ${Mt}); giving up after ${fi} restarts in ${Math.round(ki/1000)}s`);return}let Ht=Math.min(Qr,100*2**Math.min(St,8));a("daemon",`worker exited (code ${Mt}); respawning in ${Ht}ms (restart ${St}/${fi})`,u),setTimeout(wt,Ht).unref?.()}});s.push(Nt)}for(let J=0;J<y;J++)wt();if(u)j.success(`rpx coordinator listening on https://${c}:${f} via ${y} worker(s)${k?` (http→https on :${l})`:""}`),j.info(`pid file: ${h}`);let jt,Ft=new Promise((J)=>{jt=J});async function Gt(){if(m)return Ft;if(m=!0,clearInterval(W),R.close(),k?.stop(!1),E("SIGTERM"),await Promise.race([Promise.all(s.map((J)=>J.exited)),new Promise((J)=>setTimeout(J,3000))]),E("SIGKILL"),await Tr({rpxDir:r,verbose:u}).catch((J)=>{a("daemon",`DNS teardown failed: ${J}`,u)}),await mr(r),await Ai.unlink(S0(r)).catch(()=>{}),u)j.info("rpx coordinator stopped");return jt(),Ft}let bi=(J)=>{a("daemon",`coordinator received ${J}, shutting down`,u),Gt().catch(()=>{})};return Y.once("SIGINT",bi),Y.once("SIGTERM",bi),{stop:Gt,done:Ft,httpsPort:f,httpPort:l,pidPath:h,ensureCert:(J)=>F?F.ensureCert(J):Promise.resolve(!1),listSites:()=>[]}}function jE(){let i=Y.execPath,t=Di.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&Y.argv[1])return[i,Y.argv[1],"daemon:start"];return[i,"daemon:start"]}async function tS(i={}){let t=i.rpxDir??Bi(),r=i.verbose??!1;await Yr({rpxDir:t,verbose:r}).catch((h)=>{a("daemon",`DNS reconcile before ensureDaemonRunning: ${h}`,r)});let n=await Er(t);if(n!==null&&Li(n))return a("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)a("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await mr(t);await Ai.mkdir(t,{recursive:!0});let f=i.spawnCommand??jE();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");a("daemon",`spawning daemon: ${f.join(" ")}`,r);let l=$w(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:i.spawnCwd??Y.cwd(),env:i.spawnEnv?{...Y.env,...i.spawnEnv}:Y.env});l.unref();let c=null;l.once("error",(h)=>{c=h});let u=i.startupTimeoutMs??5000,$=i.pollIntervalMs??50,y=Date.now()+u;while(Date.now()<y){if(c)throw c;let h=await Er(t);if(h!==null&&Li(h))return a("daemon",`daemon registered with pid=${h}`,r),{pid:h,spawned:!0};await new Promise((w)=>setTimeout(w,$))}if(c)throw c;throw Error(`rpx daemon failed to start within ${u}ms (rpxDir=${t})`)}async function rS(i={}){let t=i.rpxDir??Bi(),r=i.verbose??!1,n=i.timeoutMs??5000,f=i.pollIntervalMs??50,l=i.forceAfterTimeout??!0,c=await Er(t);if(c===null||!Li(c)){if(c!==null)await mr(t);return await Yr({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:c,forced:!1}}try{Y.kill(c,"SIGTERM")}catch($){if($.code==="ESRCH")return await mr(t),{stopped:!1,pid:c,forced:!1};throw $}let u=Date.now()+n;while(Date.now()<u){if(!Li(c))return a("daemon",`daemon pid=${c} stopped cleanly`,r),{stopped:!0,pid:c,forced:!1};await new Promise(($)=>setTimeout($,f))}if(!l)throw Error(`rpx daemon (pid=${c}) did not exit within ${n}ms`);a("daemon",`daemon pid=${c} did not exit, escalating to SIGKILL`,r);try{Y.kill(c,"SIGKILL")}catch($){if($.code!=="ESRCH")throw $}return await mr(t),await Tr({rpxDir:t,verbose:r}).catch(($)=>{a("daemon",`DNS teardown after SIGKILL: ${$}`,r)}),{stopped:!0,pid:c,forced:!0}}async function nS(i={}){let t=i.rpxDir??Bi();if(await TE(t))return;await Yr({rpxDir:t,verbose:i.verbose})}import*as Rt from"node:fs/promises";import{homedir as FE}from"node:os";import*as j0 from"node:path";var Hf=1,NE="dns-state.json",ew=["com","test","dev","app","page","local","localhost","example","invalid"];function Aw(){return j0.join(FE(),".stacks","rpx")}function F0(i=Aw()){return j0.join(i,NE)}async function df(i=Aw()){try{let t=await Rt.readFile(F0(i),"utf8"),r=JSON.parse(t);if(r.version!==Hf||!Array.isArray(r.resolvers))return null;return{version:Hf,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(t){if(t.code==="ENOENT")return null;throw t}}async function sw(i,t){await Rt.mkdir(i,{recursive:!0}),await Rt.writeFile(F0(i),`${JSON.stringify(t,null,2)}
220
- `,"utf8")}async function N0(i){await Rt.rm(F0(i),{force:!0})}function aw(i){let t=i.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function WE(i){let t=aw(i);if(!t)return null;let r=t.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function W0(i){let t=new Set;for(let r of i){let n=WE(r);if(n)t.add(n)}return Array.from(t).sort()}function X0(i){let t=new Set;for(let r of i){let n=aw(r);if(n)t.add(n)}return Array.from(t).sort()}var qf=15353,XE="# managed-by: rpx",Yw="/etc/resolver",Ci=null,gf=new Set;function Bw(i){return{id:i.readUInt16BE(0),flags:i.readUInt16BE(2),qdcount:i.readUInt16BE(4),ancount:i.readUInt16BE(6),nscount:i.readUInt16BE(8),arcount:i.readUInt16BE(10)}}function Cw(i,t,r=0){let n=[],f=t,l=0;while(!0){if(f>=i.length||++l>128)break;let c=i[f];if(c===0){f++;break}if((c&192)===192){if(f+1>=i.length||r>=10)break;let u=i.readUInt16BE(f)&16383,{name:$}=Cw(i,u,r+1);if($)n.push($);f+=2;break}if(f++,f+c>i.length)break;n.push(i.subarray(f,f+c).toString("ascii")),f+=c}return{name:n.join("."),newOffset:f}}function JE(i,t){let{name:r,newOffset:n}=Cw(i,t),f=i.readUInt16BE(n),l=i.readUInt16BE(n+2);return{question:{name:r,type:f,class:l},newOffset:n+4}}function Dr(i){let t=i.split("."),r=[];for(let n of t)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function IE(i,t,r){let n=[],f=Buffer.alloc(12);f.writeUInt16BE(i,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),n.push(f),n.push(Dr(t.name));let l=Buffer.alloc(4);l.writeUInt16BE(t.type,0),l.writeUInt16BE(t.class,2),n.push(l),n.push(Dr(t.name));let c=Buffer.alloc(10);if(c.writeUInt16BE(t.type,0),c.writeUInt16BE(1,2),c.writeUInt32BE(300,4),t.type===1){c.writeUInt16BE(4,8),n.push(c);let u=r.split(".").map(($)=>Number.parseInt($,10));n.push(Buffer.from(u))}else if(t.type===28)c.writeUInt16BE(16,8),n.push(c),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,Dr(t.name),l]);return Buffer.concat(n)}function _E(i,t){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(i,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(Dr(t.name));let f=Buffer.alloc(4);return f.writeUInt16BE(t.type,0),f.writeUInt16BE(t.class,2),r.push(f),Buffer.concat(r)}async function KE(i,t){if(ht.platform!=="darwin")return!1;let r=X0(i);if(r.length===0)return!1;if(Ci){for(let n of r)gf.add(n);return a("dns","DNS server already running — merged domains",t),!0}return gf=new Set(r),new Promise((n)=>{Ci=mw.createSocket("udp4"),Ci.on("error",(f)=>{a("dns",`DNS server error: ${f.message}`,t),Ci?.close(),Ci=null,n(!1)}),Ci.on("message",(f,l)=>{try{let c=Bw(f),{question:u}=JE(f,12);a("dns",`Query for ${u.name} type ${u.type} from ${l.address}`,t);let $=u.name.toLowerCase(),y=!1;for(let w of gf)if($===w||$.endsWith(`.${w}`)){y=!0;break}let h;if(y&&(u.type===1||u.type===28))h=IE(c.id,u,"127.0.0.1"),a("dns",`Responding with localhost for ${u.name}`,t);else h=_E(c.id,u),a("dns",`NXDOMAIN for ${u.name}`,t);Ci?.send(h,l.port,l.address)}catch(c){a("dns",`Error processing DNS query: ${c}`,t)}}),Ci.on("listening",()=>{let f=Ci?.address();a("dns",`DNS server listening on ${f?.address}:${f?.port}`,t),n(!0)});try{Ci.bind(qf,"127.0.0.1")}catch(f){a("dns",`Failed to bind DNS server: ${f}`,t),n(!1)}})}function Uw(i){if(Ci)a("dns","Stopping DNS server",i),Ci.close(),Ci=null,gf=new Set}function eS(){return Ci!==null}async function zE(i,t=500){let r=i.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((n)=>{let f=mw.createSocket("udp4"),l=setTimeout(()=>{f.close(),n(!1)},t);f.on("message",(u)=>{clearTimeout(l),f.close();try{let $=Bw(u);n($.ancount>0)}catch{n(!1)}}),f.on("error",()=>{clearTimeout(l),f.close(),n(!1)});let c=OE(r,1);f.send(c,qf,"127.0.0.1",(u)=>{if(u)clearTimeout(l),f.close(),n(!1)})})}function OE(i,t){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let n=Buffer.concat([Dr(i),Buffer.from([0,t,0,1])]);return Buffer.concat([r,n])}function GE(){return`${XE}
221
- nameserver 127.0.0.1
222
- port ${qf}
223
- `}function br(i){return Tw.join(Yw,i)}function ME(i){return i.includes("127.0.0.1")&&i.includes(String(qf))}async function HE(i){try{return await Ew.readFile(br(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function J0(i){if(ht.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:r,isProcessElevated:n}=await import("./chunk-q6q2dhrg.js");if(!n()&&!r()){a("dns","Cannot flush DNS cache without SUDO_PASSWORD",i);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),a("dns","DNS cache flushed",i)}catch(f){a("dns",`Could not flush DNS cache: ${f}`,i)}}function Rw(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function dE(i,t){Rw(i);let{execSudoSync:r}=await import("./chunk-q6q2dhrg.js"),n=GE().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${Yw} && printf "%b" "${n}" > ${br(i)}'`;r(f),a("dns",`Created ${br(i)}`,t)}async function gE(i,t){Rw(i);let{execSudoSync:r}=await import("./chunk-q6q2dhrg.js");r(`rm -f ${br(i)}`),a("dns",`Removed ${br(i)}`,t)}async function AS(i,t){return jw({domains:t??[],verbose:i})}async function qE(i,t){if(ht.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-q6q2dhrg.js");if(!n()&&!r())return a("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let f of i)await dE(f,t);return await J0(t),!0}catch(f){return a("dns",`Failed to create resolver file: ${f}`,t),!1}}async function I0(i,t){if(ht.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:n}=await import("./chunk-q6q2dhrg.js");if(!n()&&!r())return;try{for(let f of i)await gE(f,t);await J0(t)}catch(f){a("dns",`Failed to remove resolver files: ${f}`,t)}}async function Sw(i){if(ht.platform!=="darwin")return[];let t=[];for(let r of ew){let n=await HE(r);if(n&&ME(n))await I0([r],i),t.push(r)}return t}async function jw(i){let t=i.rpxDir??Bi(),r=X0(i.domains);if(r.length===0)return!1;let n=W0(r),f=await KE(r,i.verbose);if(!f){let u=r[0];if(u&&await zE(u))f=!0;else a("dns","Dev DNS server not available on 127.0.0.1:15353",i.verbose)}if(!f)return!1;if(!await qE(n,i.verbose))return!1;let c={version:Hf,resolvers:n,domains:r,ownerPid:i.ownerPid??ht.pid,updatedAt:new Date().toISOString()};return await sw(t,c),!0}async function Vr(i,t={}){let r=i.map(($)=>$.to).filter(Boolean),n=t.rpxDir??Bi(),f=W0(r),u=((await df(n))?.resolvers??[]).filter(($)=>!f.includes($));if(u.length>0)await I0(u,t.verbose);if(f.length===0){Uw(t.verbose),await N0(n);return}await jw({domains:r,rpxDir:n,verbose:t.verbose,ownerPid:t.ownerPid??ht.pid})}async function Tr(i={}){let t=i.rpxDir??Bi();Uw(i.verbose);let n=(await df(t))?.resolvers??[];await I0(n,i.verbose),await Sw(i.verbose),await N0(t)}async function sS(i){await Tr({verbose:i})}async function Yr(i={}){let t=i.rpxDir??Bi(),r=await df(t),n=r?.ownerPid!=null&&Li(r.ownerPid);if(r&&!n){a("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,i.verbose),await Tr(i);return}let f=await Sw(i.verbose);if(f.length>0)a("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,i.verbose);await J0(i.verbose)}
224
- export{j as a,fh as b,ka as c,It as d,xc as e,kc as f,Va as g,Da as h,Yt as i,_t as j,Vc as k,Mr as l,Dc as m,lh as n,Ff as o,Hr as p,dr as q,bc as r,vc as s,eh as t,Ah as u,Zc as v,dU as w,gU as x,qU as y,ah as z,pc as A,i0 as B,t0 as C,LU as D,mh as E,nm as F,Yh as G,Bh as H,PU as I,Xh as J,Jh as K,Jm as L,Im as M,_m as N,Ih as O,zh as P,f0 as Q,l0 as R,Oh as S,Hh as T,Jf as U,c0 as V,dh as W,zt as X,Mm as Y,$0 as Z,u0 as _,y0 as $,Hm as aa,w0 as ba,qm as ca,qh as da,If as ea,s0 as fa,Lh as ga,om as ha,Pm as ia,Zm as ja,a0 as ka,TR as la,Qh as ma,m0 as na,oh as oa,CR as pa,Ut as qa,T0 as ra,Li as sa,vh as ta,B0 as ua,nE as va,yt as wa,xr as xa,Of as ya,U0 as za,ar as Aa,tw as Ba,rw as Ca,Hf as Da,ew as Ea,aw as Fa,WE as Ga,W0 as Ha,X0 as Ia,qf as Ja,XE as Ka,KE as La,Uw as Ma,eS as Na,zE as Oa,br as Pa,ME as Qa,AS as Ra,Sw as Sa,jw as Ta,Vr as Ua,Tr as Va,sS as Wa,Yr as Xa,Bi as Ya,Mf as Za,Er as _a,TE as $a,yw as ab,mr as bb,iS as cb,jE as db,tS as eb,rS as fb,nS as gb};