@stacksjs/rpx 0.11.45 → 0.11.47

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.
@@ -0,0 +1,311 @@
1
+ import{$b as Pc,Pb as Qy,Qb as W,Rb as ll,Sb as hm,Ub as Dt,Vb as m,Wb as hl,_b as ad,bc as ks,cc as cd,ec as Bd,fc as ld}from"./chunk-pcyc92vj.js";import Am from"node:dgram";import*as Rm from"node:fs/promises";import*as km from"node:path";import*as Et from"node:process";import{spawn as vm}from"node:child_process";import*as ye from"node:fs/promises";import{homedir as bm}from"node:os";import*as it from"node:path";import*as E from"node:process";var x={info:(...e)=>console.log("[info]",...e),success:(...e)=>console.log("[success]",...e),warn:(...e)=>console.warn("[warn]",...e),error:(...e)=>console.error("[error]",...e),debug:(...e)=>console.debug("[debug]",...e),log:(...e)=>console.log(...e),start:(...e)=>console.log("[start]",...e),box:(...e)=>console.log("[box]",...e)};import{execSync as xc}from"node:child_process";import ee from"node:fs/promises";import*as Tc from"node:os";import{homedir as Or}from"node:os";import*as fd from"node:path";import{join as X}from"node:path";import*as Ye from"node:process";var ka={};Qy(ka,{AcmeClient:()=>Xr,AcmeError:()=>Jr,CERT_CONSTANTS:()=>De,DEFAULT_PROFILE_IDENTIFIER_PREFIX:()=>Bn,DEFAULT_REQUEST_TIMEOUT_MS:()=>Tn,EXPORT_MIME_TYPES:()=>va,FileHttp01Store:()=>Wo,Http01Store:()=>jt,LETS_ENCRYPT_PRODUCTION_DIRECTORY:()=>qo,LETS_ENCRYPT_STAGING_DIRECTORY:()=>Go,LINUX_DISTRO_STORES:()=>wr,LOG_CATEGORIES:()=>b,PATH_CONSTANTS:()=>Ef,PorkbunDnsProvider:()=>Ko,TLSX_UUID_NAMESPACE:()=>ba,TRUST_PLATFORMS:()=>wa,addCertToSystemTrustStore:()=>Nu,addCertToSystemTrustStoreAndSaveCert:()=>Hn,base64urlDecode:()=>Yr,base64urlDecodeToString:()=>bf,base64urlEncode:()=>Gr,buildCsr:()=>ea,buildCsrBase64url:()=>ta,buildMobileConfig:()=>Ca,calculateValidityDates:()=>_n,certFileBase:()=>fu,cleanupTrustStore:()=>Ou,config:()=>O,createRootCA:()=>fi,debugLog:()=>v,defaultConfig:()=>Dn,defaultHttp01Store:()=>ai,derBitString:()=>fn,derContext:()=>un,derInteger:()=>Xo,derNull:()=>Cf,derOctetString:()=>Zo,derOid:()=>At,derPrintableString:()=>Sf,derSequence:()=>ke,derSet:()=>ln,derUtf8String:()=>Qo,detectLinuxDistroFamily:()=>Ea,dns01RecordName:()=>Jo,exportCA:()=>vu,fetchWithTimeout:()=>or,findFoldersWithFile:()=>ti,findLinuxCaBundle:()=>xa,generateCertificate:()=>yr,generateCertificateExtensions:()=>Su,generateRandomSerial:()=>Cu,generateSubjectAltNames:()=>In,getCertCommonName:()=>gr,getCertSha256Fingerprint:()=>mr,getCertificateFromCertPemOrPath:()=>mt,getConfig:()=>au,getPrimaryDomain:()=>ga,getSudoPassword:()=>ma,installCA:()=>Vn,installCAIntoLinuxSystemStore:()=>Ta,isCertExpired:()=>mu,isCertTrusted:()=>ku,isCertTrustedOnLinux:()=>Kn,isCertValidForDomain:()=>Mn,jwkFromKey:()=>Ho,jwkThumbprint:()=>Vo,linuxAnchorFileName:()=>Un,listCertsInDirectory:()=>lu,log:()=>z,makeNumberPositive:()=>da,normalizeCertPaths:()=>dr,obtainCertificate:()=>Pn,parseCertDetails:()=>du,parseOsRelease:()=>$a,pemBundleHasFingerprint:()=>ya,pemToDer:()=>On,readCertFromFile:()=>ha,readLinuxDistroFamily:()=>jn,redactSensitive:()=>ri,removeCAFromLinuxSystemStore:()=>Pa,removeCertFromSystemTrustStore:()=>Du,renewalOutputBase:()=>uu,runCommand:()=>Te,safeStringify:()=>li,sha256FingerprintOfDer:()=>Fn,signJws:()=>zo,splitApexAndSubdomain:()=>cn,splitPemCertificates:()=>pa,splitPemChain:()=>Yo,storeCACertificate:()=>Wn,storeCertificate:()=>Aa,trustInstructions:()=>bu,uninstallCA:()=>Fu,uuidV5:()=>si,validateBrowserCompatibility:()=>yu,validateCertificate:()=>pu,verifyServerChain:()=>Ln,waitForTxtRecord:()=>Uo,willCertExpireSoon:()=>gu});import{createRequire as Um}from"node:module";import{Resolver as eo}from"node:dns/promises";import Tl from"node:process";import{createHash as Km,sign as Wm}from"node:crypto";import{createHash as Hm}from"node:crypto";import{sign as Vm}from"node:crypto";import{generateKeyPairSync as $f,X509Certificate as eg}from"node:crypto";import to from"node:os";import ro from"node:path";import{existsSync as Al,statSync as Rl}from"fs";import{existsSync as rg,mkdirSync as QS,readdirSync as e$,readFileSync as ig,writeFileSync as t$}from"fs";import{homedir as Yt}from"os";import{dirname as n$,resolve as Me}from"path";import An from"process";import{existsSync as kl,statSync as Nl}from"fs";import{existsSync as xo,mkdirSync as ng,readdirSync as sg,writeFileSync as og}from"fs";import{homedir as Jt}from"os";import{dirname as Dl,resolve as ve}from"path";import Ut from"process";import{join as ag,relative as cg,resolve as Ol}from"path";import hn from"process";import{existsSync as xf,mkdirSync as m$,readdirSync as g$,writeFileSync as p$}from"fs";import{homedir as io}from"os";import{dirname as v$,resolve as we}from"path";import Zr from"process";import{join as lg,relative as fg,resolve as Fl}from"path";import dn from"process";import{existsSync as Tf,mkdirSync as E$,readdirSync as x$,writeFileSync as T$}from"fs";import{dirname as A$,resolve as mn}from"path";import To from"process";import{Buffer as Pt}from"buffer";import{createCipheriv as ug,createDecipheriv as hg,randomBytes as no}from"crypto";import{closeSync as so,createReadStream as Ll,createWriteStream as dg,existsSync as oo,fsyncSync as Ml,openSync as Bl,writeFileSync as mg}from"fs";import{access as gg,constants as Il,mkdir as pg,readdir as Ui,rename as _l,stat as Xt,unlink as Ki,writeFile as ao}from"fs/promises";import{join as Zt}from"path";import ue from"process";import{pipeline as yg}from"stream/promises";import{createGzip as jl}from"zlib";import Qt from"process";import ct from"process";import{Buffer as ot}from"buffer";import{createCipheriv as wg,createDecipheriv as vg,randomBytes as co}from"crypto";import{closeSync as lo,createReadStream as Ul,createWriteStream as bg,existsSync as Wi,fsyncSync as Kl,openSync as Wl,writeFileSync as Cg}from"fs";import{access as Sg,constants as Hl,mkdir as $g,readdir as Hi,rename as Vl,stat as er,unlink as Vi,writeFile as fo}from"fs/promises";import{isAbsolute as Eg,join as tr,resolve as xg}from"path";import j from"process";import{pipeline as Tg}from"stream/promises";import{createGzip as zl}from"zlib";import rr from"process";import lt from"process";import zi from"process";import{existsSync as Gi}from"fs";import{resolve as uo}from"path";import{existsSync as Pg}from"fs";import{existsSync as Ag,readdirSync as Rg}from"fs";import{extname as ho,resolve as Gl}from"path";import kg from"process";import{join as Ng,relative as Dg,resolve as ql}from"path";import gn from"process";import{Buffer as at}from"buffer";import{createCipheriv as Og,createDecipheriv as Fg,randomBytes as mo}from"crypto";import{closeSync as go,createReadStream as Yl,createWriteStream as Lg,existsSync as qi,fsyncSync as Jl,openSync as Xl,writeFileSync as Mg}from"fs";import{access as Bg,constants as Zl,mkdir as Ig,readdir as Yi,rename as Ql,stat as ir,unlink as Ji,writeFile as po}from"fs/promises";import{isAbsolute as _g,join as nr,resolve as jg}from"path";import U from"process";import{pipeline as Ug}from"stream/promises";import{createGzip as ef}from"zlib";import sr from"process";import ft from"process";import Xi from"process";import{existsSync as Zi}from"fs";import{resolve as yo}from"path";import{existsSync as Kg}from"fs";import{exec as uy}from"node:child_process";import ar from"node:fs";import Bo from"node:os";import xe from"node:path";import cu from"node:process";import{promisify as hy}from"node:util";import ii from"node:crypto";import _t from"node:fs";import wy from"node:tls";import by from"node:crypto";import Cy from"node:fs";import Ty from"node:crypto";import pr from"node:crypto";import Qe from"node:fs";import ur from"node:path";import Hy from"node:process";import ut from"node:fs";import jo from"node:path";import{execSync as Yy}from"node:child_process";import cr from"node:fs";import et from"node:os";var Wr=Um(import.meta.url),Tn=30000;async function or(e,t={},r=30000){try{return await fetch(e,{...t,signal:AbortSignal.timeout(r)})}catch(i){if(i&&typeof i==="object"&&i.name==="TimeoutError"){let n=Error(`ACME HTTP request to ${e} timed out after ${r}ms`);throw n.name="AcmeRequestTimeoutError",n}throw i}}async function Uo(e,t,r={}){let i=r.timeoutMs??120000,n=r.intervalMs??3000,s=e.split(".").slice(-2).join("."),o;try{let l=new eo,f=await l.resolveNs(s),u=(await Promise.all(f.map((h)=>l.resolve4(h).catch(()=>[])))).flat();if(u.length>0)o=new eo,o.setServers(u)}catch{}let a=Date.now()+i,c=o??new eo;for(;;){try{if((await c.resolveTxt(e)).some((l)=>l.join("")===t))return!0}catch{}if(Date.now()>=a)return!1;await new Promise((l)=>setTimeout(l,n))}}function cn(e){let t=e.split(".");if(t.length<=2)return{apex:e,subdomain:""};let r=t.slice(-2).join("."),i=t.slice(0,-2).join(".");return{apex:r,subdomain:i}}class Ko{apiKey;secretApiKey;baseUrl;requestTimeoutMs;constructor(e){let t=e?.apiKey??Tl.env.PORKBUN_API_KEY,r=e?.secretApiKey??Tl.env.PORKBUN_SECRET_KEY;if(!t||!r)throw Error("Porkbun credentials missing: set PORKBUN_API_KEY and PORKBUN_SECRET_KEY (or pass them in)");this.apiKey=t,this.secretApiKey=r,this.baseUrl=e?.baseUrl??"https://api.porkbun.com/api/json/v3",this.requestTimeoutMs=e?.requestTimeoutMs??Tn}async post(e,t){let r=await or(`${this.baseUrl}${e}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({apikey:this.apiKey,secretapikey:this.secretApiKey,...t})},this.requestTimeoutMs),i=await r.json().catch(()=>({}));if(!r.ok||i.status!=="SUCCESS")throw Error(`Porkbun API ${e} failed: ${i.message??`HTTP ${r.status}`}`);return i}async setTxt(e,t){let{apex:r,subdomain:i}=cn(e);await this.post(`/dns/create/${r}`,{type:"TXT",name:i,content:t,ttl:"600"})}async removeTxt(e,t){let{apex:r,subdomain:i}=cn(e),n=i?`${i}.${r}`:r,s=(await this.post(`/dns/retrieveByNameType/${r}/TXT/${i}`,{}).catch(()=>null))?.records??[];for(let o of s)if(o.content===t&&(o.name===n||o.name===r))await this.post(`/dns/delete/${r}/${o.id}`,{}).catch(()=>{})}}class jt{tokens=new Map;add(e,t){this.tokens.set(e,t)}get(e){return this.tokens.get(e)}remove(e){this.tokens.delete(e)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(e){let t=e.indexOf(jt.PATH_PREFIX);if(t===-1)return;let r=e.slice(t+jt.PATH_PREFIX.length);return this.get(r)}}var ai=new jt;class Wo extends jt{webroot;written=new Set;constructor(e){super();this.webroot=e,Wr("node:fs").mkdirSync(this.webroot,{recursive:!0})}filePath(e){let t=Wr("node:path");return t.join(this.webroot,t.basename(e))}add(e,t){super.add(e,t),Wr("node:fs").writeFileSync(this.filePath(e),t,"utf8"),this.written.add(e)}remove(e){super.remove(e);let t=Wr("node:fs");try{t.unlinkSync(this.filePath(e))}catch{}this.written.delete(e)}cleanup(){for(let e of[...this.written])this.remove(e)}}function Gr(e){return(typeof e==="string"?Buffer.from(e,"utf8"):Buffer.from(e)).toString("base64url")}function Yr(e){return Buffer.from(e,"base64url")}function bf(e){return Yr(e).toString("utf8")}function Ho(e){let t=e.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 Vo(e){let t=`{"crv":"${e.crv}","kty":"${e.kty}","x":"${e.x}","y":"${e.y}"}`;return Km("sha256").update(t).digest("base64url")}function zo(e){let{protectedHeader:t,payload:r,privateKey:i}=e,n=Gr(JSON.stringify(t)),s=r===""?"":Gr(JSON.stringify(r)),o=`${n}.${s}`,a=Wm("sha256",Buffer.from(o),{key:i,dsaEncoding:"ieee-p1363"});return{protected:n,payload:s,signature:Gr(a)}}var Go="https://acme-staging-v02.api.letsencrypt.org/directory",qo="https://acme-v02.api.letsencrypt.org/directory";class Jr extends Error{problem;httpStatus;constructor(e,t,r){super(e);this.name="AcmeError",this.problem=t,this.httpStatus=r}}class Xr{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(e){this.directoryUrl=e.directoryUrl,this.accountKey=e.accountKey,this.jwk=Ho(e.accountPublicKey),this.thumbprint=Vo(this.jwk),this.requestTimeoutMs=e.requestTimeoutMs??Tn}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let e=await or(this.directoryUrl,{},this.requestTimeoutMs);if(!e.ok)throw Error(`Failed to fetch ACME directory: HTTP ${e.status}`);return this.directoryCache=await e.json(),this.directoryCache}async newNonce(){let e=await this.directory(),t=(await or(e.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let e=this.nonce;return this.nonce=void 0,e}return this.newNonce()}async signedPost(e){let{url:t,payload:r,useJwk:i}=e,n={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(i)n.jwk=this.jwk;else n.kid=this.requireKid();let s=zo({protectedHeader:n,payload:r,privateKey:this.accountKey}),o=await or(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(s)},this.requestTimeoutMs),a=o.headers.get("replay-nonce");if(a)this.nonce=a;let c=o.headers.get("content-type")??"",l;if(c.includes("application/pem-certificate-chain")||c.startsWith("text/"))l=await o.text();else{let f=await o.text();l=f?JSON.parse(f):{}}if(o.status>=400){let f=l??{};throw new Jr(`ACME request to ${t} failed (HTTP ${o.status}): ${f.type??""} ${f.detail??""}`.trim(),f,o.status)}return{status:o.status,headers:o.headers,body:l,location:o.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(e={}){let t=await this.directory(),r={termsOfServiceAgreed:!0};if(e.email)r.contact=[`mailto:${e.email}`];let i=await this.signedPost({url:t.newAccount,payload:r,useJwk:!0});if(!i.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=i.location,this.accountKid}async newOrder(e){let t=await this.directory(),r={identifiers:e.map((n)=>({type:"dns",value:n}))},i=await this.signedPost({url:t.newOrder,payload:r});if(!i.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:i.body,orderUrl:i.location}}async getAuthorization(e){return(await this.signedPost({url:e,payload:""})).body}keyAuthorization(e){return`${e}.${this.thumbprint}`}dns01TxtValue(e){return Hm("sha256").update(this.keyAuthorization(e)).digest("base64url")}async notifyChallengeReady(e){await this.signedPost({url:e,payload:{}})}async pollAuthorization(e,t={}){let r=t.timeoutMs??60000,i=t.intervalMs??2000,n=Date.now()+r;while(Date.now()<n){let s=await this.getAuthorization(e);if(s.status==="valid")return;if(s.status==="invalid"){let o=s.challenges.find((a)=>a.status==="invalid");throw new Jr(`Authorization for ${s.identifier.value} became invalid: ${o?.error?.detail??"unknown reason"}`,o?.error??{},0)}await Pl(i),i=Math.min(i*1.5,1e4)}throw Error(`Timed out waiting for authorization ${e} to become valid`)}async finalizeOrder(e,t){return(await this.signedPost({url:e,payload:{csr:t}})).body}async getOrder(e){return(await this.signedPost({url:e,payload:""})).body}async pollOrder(e,t={}){let r=t.timeoutMs??60000,i=t.intervalMs??2000,n=Date.now()+r;while(Date.now()<n){let s=await this.getOrder(e);if(s.status==="valid"){if(!s.certificate)throw Error("ACME order is valid but has no certificate URL");return s.certificate}if(s.status==="invalid")throw Error(`ACME order ${e} became invalid`);await Pl(i),i=Math.min(i*1.5,1e4)}throw Error(`Timed out waiting for order ${e} to become valid`)}async downloadCertificate(e){let t=await this.signedPost({url:e,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(e,t){let r=e.challenges.find((i)=>i.type===t);if(!r)throw Error(`No ${t} challenge available for ${e.identifier.value}`);return r}}function Yo(e){let t=e.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=t[0];if(!r)return{certPem:`${e.trim()}
2
+ `,chainPem:""};let i=`${r.trim()}
3
+ `,n=t.slice(1).map((s)=>s.trim()).join(`
4
+ `);return{certPem:i,chainPem:n?`${n}
5
+ `:""}}function Jo(e){return`_acme-challenge.${e.startsWith("*.")?e.slice(2):e}`}function Pl(e){return new Promise((t)=>setTimeout(t,e))}function zm(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function dt(e,t){return Buffer.concat([Buffer.from([e]),zm(t.length),t])}function Xo(e){let t;if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=[],i=e;while(i>0)r.unshift(i&255),i>>=8;if(r[0]&128)r.unshift(0);t=Buffer.from(r)}else if(t=e.length===0?Buffer.from([0]):e,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return dt(2,t)}function At(e){let t=e.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${e}`);let r=[40*t[0]+t[1]];for(let i=2;i<t.length;i++){let n=t[i],s=[n&127];n=Math.floor(n/128);while(n>0)s.unshift(n&127|128),n=Math.floor(n/128);r.push(...s)}return dt(6,Buffer.from(r))}function Cf(){return Buffer.from([5,0])}function ke(...e){return dt(48,Buffer.concat(e))}function ln(...e){return dt(49,Buffer.concat(e))}function fn(e){return dt(3,Buffer.concat([Buffer.from([0]),e]))}function Zo(e){return dt(4,e)}function Sf(e){return dt(19,Buffer.from(e,"ascii"))}function Qo(e){return dt(12,Buffer.from(e,"utf8"))}function un(e,t,r){let i=128|(r?32:0)|e;return dt(i,t)}var Gm="1.2.840.10045.2.1",qm="1.2.840.10045.3.1.7",Ym="1.2.840.10045.4.3.2",Jm="2.5.4.3",Xm="1.2.840.113549.1.9.14",Zm="2.5.29.17";function Qm(e){let t=e.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let r=Yr(t.x),i=Yr(t.y);if(r.length!==32||i.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${i.length}`);return Buffer.concat([Buffer.from([4]),r,i])}function ea(e){let{domains:t,publicKey:r,privateKey:i}=e;if(t.length===0)throw Error("At least one domain is required to build a CSR");let n=ke(ln(ke(At(Jm),Qo(t[0])))),s=ke(ke(At(Gm),At(qm)),fn(Qm(r))),o=t.map((g)=>un(2,Buffer.from(g,"ascii"),!1)),a=ke(...o),c=ke(At(Zm),Zo(a)),l=ke(c),f=ke(At(Xm),ln(l)),u=un(0,f,!0),h=ke(Xo(0),n,s,u),d=Vm("sha256",h,i),p=ke(At(Ym));return ke(h,p,fn(d))}function ta(e){return ea(e).toString("base64url")}function tg(e){if(e){let{createPrivateKey:n,createPublicKey:s}=Wr("node:crypto"),o=n(e),a=s(o.export({format:"pem",type:"pkcs8"}));return{privateKey:o,publicKey:a,pem:e}}let{privateKey:t,publicKey:r}=$f("ec",{namedCurve:"P-256"}),i=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:r,pem:i}}async function Pn(e){let{domains:t,method:r}=e;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!e.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((u)=>u.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let i=e.directoryUrl??(e.staging===!1?qo:Go),n=tg(e.accountKeyPem),s=new Xr({directoryUrl:i,accountKey:n.privateKey,accountPublicKey:n.publicKey,requestTimeoutMs:e.requestTimeoutMs});await s.newAccount({email:e.email});let{order:o,orderUrl:a}=await s.newOrder(t),c=e.http01Store??ai,l=[],f=[];try{for(let P of o.authorizations){let D=await s.getAuthorization(P);if(D.status==="valid")continue;let N=Xr.selectChallenge(D,r);if(r==="dns-01"){let ae=Jo(D.identifier.value),J=s.dns01TxtValue(N.token);await e.dnsProvider.setTxt(ae,J),l.push({name:ae,value:J}),await Uo(ae,J,{timeoutMs:e.dnsPropagationTimeoutMs??120000})}else c.add(N.token,s.keyAuthorization(N.token)),f.push(N.token);await s.notifyChallengeReady(N.url),await s.pollAuthorization(P,{timeoutMs:e.timeoutMs})}let{privateKey:u,publicKey:h}=$f("ec",{namedCurve:"P-256"}),d=ta({domains:t,publicKey:h,privateKey:u});await s.finalizeOrder(o.finalize,d);let p=await s.pollOrder(a,{timeoutMs:e.timeoutMs}),g=await s.downloadCertificate(p),{certPem:y,chainPem:w}=Yo(g),C=w?`${y}${w}`:y,A=u.export({format:"pem",type:"pkcs8"}).toString(),T=new Date(new eg(y).validTo);return{certPem:y,keyPem:A,chainPem:w,fullChainPem:C,accountKeyPem:n.pem,notAfter:T}}finally{for(let{name:u,value:h}of l)await e.dnsProvider?.removeTxt(u,h).catch(()=>{});for(let u of f)c.remove(u)}}var De={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"},Ef={DEFAULT_CERT_DIR:".stacks/ssl",CERT_EXTENSION:".crt",KEY_EXTENSION:".crt.key",CA_CERT_EXTENSION:".ca.crt"},b={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"};class Pf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Al(e))return!0;return Rl(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=Al(r)?Rl(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.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 e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Af{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var pn=new Pf,ra=new Af,Wg=Object.defineProperty,Hg=(e)=>e;function Vg(e,t){this[e]=Hg.bind(null,t)}var zg=(e,t)=>{for(var r in t)Wg(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Vg.bind(t,r)})},Gg=(e,t)=>()=>(e&&(t=e(e=0)),t),Rf={};zg(Rf,{withErrorRecovery:()=>Df,tryLoadConfig:()=>pp,loadConfigWithResult:()=>mp,loadConfig:()=>Bf,isRetryableError:()=>cp,isConfigNotFoundError:()=>ap,isBunfigError:()=>Of,globalPerformanceMonitor:()=>ci,globalCache:()=>lr,getEnvOrDefault:()=>lp,generateConfigTypes:()=>yp,defaultGeneratedDir:()=>Vf,defaultConfigDir:()=>Hf,deepMergeWithArrayStrategy:()=>aa,deepMerge:()=>Ff,createLibraryConfig:()=>wp,config:()=>gp,bunfigPlugin:()=>vp,applyEnvVarsToConfig:()=>Hr,TypeGenerationError:()=>Oo,SchemaValidationError:()=>ei,PluginError:()=>Lo,PerformanceMonitor:()=>na,FileSystemError:()=>Do,ErrorFactory:()=>Rt,EnvVarError:()=>Sn,EnvProcessor:()=>Rn,ConfigValidator:()=>ca,ConfigValidationError:()=>ko,ConfigNotFoundError:()=>Cn,ConfigMergeError:()=>No,ConfigLoader:()=>la,ConfigLoadError:()=>Qr,ConfigFileLoader:()=>kn,ConfigCache:()=>ia,CacheUtils:()=>_f,BunfigError:()=>Ne,BrowserConfigError:()=>Fo,ArrayMergeStrategies:()=>Kf});class ia{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!kl(e))return!0;return Nl(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=kl(r)?Nl(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.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 e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class na{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function qg(e,t={}){let r=Object.keys(t).sort().map((i)=>`${i}:${t[i]}`).join("|");return r?`${e}:${r}`:e}function Yg(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Jg(e){return e.getStats().size*2}function sa(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.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(e)&&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 e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(q(e)&&"arr"in e&&Array.isArray(e.arr)&&q(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&q(t[0])&&q(e[0])){let i=[...t];for(let n of e)if(q(n)&&"name"in n){if(!i.find((s)=>q(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(q(n)&&"path"in n){if(!i.find((s)=>q(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>yn(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!q(t)||!q(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(q(n)&&q(r[i]))r[i]=sa(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&q(n[0])&&q(r[i][0])){let s=[...n];for(let o of r[i])if(q(o)&&"name"in o){if(!s.find((a)=>q(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(q(o)&&"path"in o){if(!s.find((a)=>q(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>yn(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function yn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!yn(e[r],t[r]))return!1;return!0}if(q(e)&&q(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!yn(e[n],t[n]))return!1}return!0}return!1}function q(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Xg(e,t){if(!Tf(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return sa(t,i)}catch{return null}}catch{return null}}async function Zg({name:e="",cwd:t,defaultConfig:r}){let i=t||To.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let a of n){let c=mn(i,`${o}${a}`),l=await Xg(c,r);if(l!==null)return l}try{let o=mn(i,"package.json");if(Tf(o)){let a=(await import(o))[e];if(a&&typeof a==="object"&&!Array.isArray(a))try{return sa(r,a)}catch{}}}catch{}return r}function Qg(e,t={}){let r=dn.cwd();while(r.includes("storage"))r=Fl(r,"..");let i=Fl(r,e||"");if(t?.relative)return fg(dn.cwd(),i);return i}async function ep(){try{let e=await Zg({name:"clarity",defaultConfig:nn,cwd:dn.cwd(),endpoint:"",headers:{}});return{...nn,...e}}catch{return nn}}function Z(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tp(){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 e=ct.type;if(e==="renderer"||e==="worker")return!1;return!!(ct.versions&&(ct.versions.node||ct.versions.bun))}return!1}class kf{async format(e){let t=await tp(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Qt.pid,hostname:t(),environment:Qt.env.NODE_ENV||"development",platform:Qt.platform,version:Qt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Qt.env.NODE_ENV||Qt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class wn{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(e,t={}){this.name=e,this.config={...Ao},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new kf,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??ue.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...sn,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...sn};return{...sn,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ao.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await gg(this.config.logDirectory,Il.F_OK|Il.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await pg(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:Pt.from(e);try{if(!oo(this.currentLogFile))await ao(this.currentLogFile,"",{mode:420});if(i=Bl(this.currentLogFile,"a",420),mg(i,a,{flag:"a"}),Ml(i),i!==void 0)so(i),i=void 0;if((await Xt(this.currentLogFile)).size===0){if(await ao(this.currentLogFile,a,{flag:"w",mode:420}),(await Xt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let l=c;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let f=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,f);let u=o*2**n;await new Promise((h)=>setTimeout(h,u)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{so(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(n===s-1){let l=a,f=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}n++;let c=o*2**(n-1);await new Promise((l)=>setTimeout(l,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 Zt(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 Zt(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Zt(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Z())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=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 i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return no(16).toString("hex")}generateKey(){return no(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=no(16),i=ug("aes-256-gcm",t,r),n=Pt.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:Pt.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=jl(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(Pt.from(Pt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Z())return;let e=await Xt(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Ui(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Xt(r).catch(()=>null))try{if(await _l(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Ki(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await ao(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Xt(r).catch(()=>null))await _l(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Ui(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ki(Zt(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Ll(e),i=dg(t),n=jl();await yg(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}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:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),oo(this.currentLogFile))try{let e=Bl(this.currentLogFile,"r+");Ml(e),so(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Z()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Ui(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ki(Zt(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?V.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=ue.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${V.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!Z()){let l=jf[e],f=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:V.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:V.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.error(u),a){let h=a.split(`
6
+ `);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:V.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!Z()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
7
+ `;if(a)c+=`${a}
8
+ `;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!Z()){let r=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:V.blue("◐"),tag:r,message:`${V.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
9
+ `,c=c.replace(this.ANSI_PATTERN,""),this.fancy&&!Z()){let l=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:V.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Z())console.error(c.trim());await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new wn(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(!oo(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ll(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){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 i=Pt.isBuffer(e)?e:Pt.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),o=i.slice(16,-16),a=hg("aes-256-gcm",r,n);return a.setAuthTag(s),Pt.concat([a.update(o),a.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}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(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!Z()){let s=e.split(`
10
+ `),o=Math.max(...s.map((f)=>f.length))+2,a=`┌${"─".repeat(o)}┐`,c=`└${"─".repeat(o)}┘`,l=s.map((f)=>{let u=" ".repeat(o-f.length-2);return`│ ${f}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:V.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:V.cyan(a)})),l.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:r,message:V.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:V.cyan(c),showTimestamp:!1}))}else if(!Z())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
11
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(Z())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${V.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();ue.stdin.removeListener("data",r);try{if(typeof ue.stdin.setRawMode==="function")ue.stdin.setRawMode(!1)}catch{}ue.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof ue.stdin.setRawMode==="function")ue.stdin.setRawMode(!0)}catch{}ue.stdin.resume(),ue.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let n=/%([sdijfo%])/g,s=0;if(r=e.replace(n,(o,a)=>{if(a==="%")return"%";if(s>=t.length)return o;let c=t[s++];switch(a){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return o}}),s<t.length)r+=` ${t.slice(s).map((o)=>typeof o==="object"?JSON.stringify(o,null,2):String(o)).join(" ")}`}if(this.fancy&&!Z()){let n=this.options.showTags!==!1&&this.name?V.gray(this.formatTag(this.name)):"",s=V.blue("◐");console.error(`${s} ${n} ${V.cyan(r)}`)}let i=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
12
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(i)}progress(e,t=""){if(!this.enabled||!this.fancy||Z()||e<=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:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(i,n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Z())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,i)),n!==void 0)this.activeProgressBar.message=n;let s=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,s)},finish:(i)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Z())return;if(this.activeProgressBar.current=this.activeProgressBar.total,i!==void 0)this.activeProgressBar.message=i;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(i,n="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Z())return;ue.stdout.write(`${"\r".padEnd(ue.stdout.columns||80)}\r`),this.log(n,i),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||Z()||!ue.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=V.green("━".repeat(i)),o=V.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?V.green("✓"):V.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${V.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=ue.stdout.columns||80,p=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${p}`,ue.stdout.write(e.lastRenderedLine),t)ue.stdout.write(`
13
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Z()||!ue.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Z()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Ui(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=Zt(this.config.logDirectory,i);if(e.before)try{if((await Xt(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 i of r)try{await Ki(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function rn(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&K(t[0])&&"id"in t[0]&&t[0].id===3&&K(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(K(t)&&K(e)&&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 e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(K(e)&&"arr"in e&&Array.isArray(e.arr)&&K(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&K(t[0])&&K(e[0])){let i=[...t];for(let n of e)if(K(n)&&"name"in n){if(!i.find((s)=>K(s)&&("name"in s)&&s.name===n.name))i.push(n)}else if(K(n)&&"path"in n){if(!i.find((s)=>K(s)&&("path"in s)&&s.path===n.path))i.push(n)}else if(!i.some((s)=>vn(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!K(t)||!K(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(K(n)&&K(r[i]))r[i]=rn(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&K(n[0])&&K(r[i][0])){let s=[...n];for(let o of r[i])if(K(o)&&"name"in o){if(!s.find((a)=>K(a)&&("name"in a)&&a.name===o.name))s.push(o)}else if(K(o)&&"path"in o){if(!s.find((a)=>K(a)&&("path"in a)&&a.path===o.path))s.push(o)}else if(!s.some((a)=>vn(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function oa(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:rn(e,t);if(Array.isArray(e))return r==="replace"?t:rn(e,t);if(!K(t)||!K(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=rn(o,s);else if(K(s)&&K(o))i[n]=oa(o,s,r);else i[n]=s}return i}function vn(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!vn(e[r],t[r]))return!1;return!0}if(K(e)&&K(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!vn(e[n],t[n]))return!1}return!0}return!1}function K(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function Qi(e,t,r="replace"){if(!xf(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return oa(t,n,r)}catch{return null}}catch{return null}}function rp(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${u.map(h).join("_")}`,p=`${i}_${u.map((g)=>g.toUpperCase()).join("_")}`;if(r)de.info(`Checking environment variable ${d} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))c[l]=s(f,u);else{let g=Zr.env[d]||Zr.env[p];if(g!==void 0){if(r)de.info(`Using environment variable ${g?d:p} for config ${e}.${u.join(".")}`);if(typeof f==="number")c[l]=Number(g);else if(typeof f==="boolean")c[l]=g.toLowerCase()==="true";else if(Array.isArray(f))try{let y=JSON.parse(g);if(Array.isArray(y))c[l]=y;else c[l]=g.split(",").map((w)=>w.trim())}catch{c[l]=g.split(",").map((y)=>y.trim())}else c[l]=g}}}return c}return s(n)}async function ip({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:a="replace"}){let c=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?rp(e,n,s):n,l=r||Zr.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(s)de.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let u=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],p=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,we(l,"config"),we(l,".config"),i?we(l,i):void 0].filter(Boolean)));for(let y of g){if(s)de.info(`Searching for configuration in: ${y}`);let w=[we(l,"config"),we(l,".config")].concat(i?[we(l,i)]:[]).includes(y)?[...u,...h,...d,...p]:[...h,...u,...p,...d];for(let C of w)for(let A of f){let T=we(y,`${C}${A}`),P=await Qi(T,c,a);if(P!==null){if(s)de.success(`Configuration loaded from: ${T}`);return P}}}if(e){let y=we(io(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)de.info(`Checking user config directory: ${y}`);for(let C of w)for(let A of f){let T=we(y,`${C}${A}`),P=await Qi(T,c,a);if(P!==null){if(s)de.success(`Configuration loaded from user config directory: ${T}`);return P}}}if(e){let y=we(io(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)de.info(`Checking user config directory for dotfile configs: ${y}`);for(let C of w)for(let A of f){let T=we(y,`${C}${A}`),P=await Qi(T,c,a);if(P!==null){if(s)de.success(`Configuration loaded from user config directory dotfile: ${T}`);return P}}}if(e){let y=io(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)de.info(`Checking user home directory for dotfile configs: ${y}`);for(let C of w)for(let A of f){let T=we(y,`${C}${A}`),P=await Qi(T,c,a);if(P!==null){if(s)de.success(`Configuration loaded from user home directory: ${T}`);return P}}}try{let y=we(l,"package.json");if(xf(y)){let w=await import(y),C=w[e];if(!C&&t){if(C=w[t],C&&s)de.success(`Using alias "${t}" configuration from package.json`)}if(C&&typeof C==="object"&&!Array.isArray(C))try{if(s)de.success(`Configuration loaded from package.json: ${C===w[e]?e:t}`);return oa(c,C,a)}catch(A){if(s)de.warn("Failed to merge package.json config:",A)}}}catch(y){if(s)de.warn("Failed to load package.json:",y)}if(s)de.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function np(e,t={}){let r=hn.cwd();while(r.includes("storage"))r=Ol(r,"..");let i=Ol(r,e||"");if(t?.relative)return cg(hn.cwd(),i);return i}async function sp(){try{let e=await ip({name:"clarity",alias:"logging",defaultConfig:on,cwd:hn.cwd()});return{...on,...e||{}}}catch{return on}}function te(){if(lt.env.NODE_ENV==="test"||lt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function op(){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 e=lt.type;if(e==="renderer"||e==="worker")return!1;return!!(lt.versions&&(lt.versions.node||lt.versions.bun))}return!1}class Nf{async format(e){let t=await op(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:rr.pid,hostname:t(),environment:rr.env.NODE_ENV||"development",platform:rr.platform,version:rr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:rr.env.NODE_ENV||rr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class bn{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(e,t={}){this.name=e,this.config={...Ro},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Nf,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??j.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...an,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...an};return{...an,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ro.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!te()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Sg(this.config.logDirectory,Hl.F_OK|Hl.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await $g(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:ot.from(e);try{if(!Wi(this.currentLogFile))await fo(this.currentLogFile,"",{mode:420});if(i=Wl(this.currentLogFile,"a",420),Cg(i,a,{flag:"a"}),Kl(i),i!==void 0)lo(i),i=void 0;if((await er(this.currentLogFile)).size===0){if(await fo(this.currentLogFile,a,{flag:"w",mode:420}),(await er(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let l=c;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let f=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,f);let u=o*2**n;await new Promise((h)=>setTimeout(h,u)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{lo(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(n===s-1){let l=a,f=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}n++;let c=o*2**(n-1);await new Promise((l)=>setTimeout(l,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 tr(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 tr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return tr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(te())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=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 i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return co(16).toString("hex")}generateKey(){return co(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=co(16),i=wg("aes-256-gcm",t,r),n=ot.isBuffer(e)?e:ot.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),l=ot.allocUnsafe(16+a+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),c.copy(l,16+a),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=zl(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(ot.from(ot.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(te())return;if(!this.shouldWriteToFile())return;let e=await er(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Hi(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await er(r).catch(()=>null))try{if(await Vl(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Vi(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await fo(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await er(r).catch(()=>null))await Vl(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Hi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await Vi(tr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Ul(e),i=bg(t),n=zl();await Tg(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Wi(this.currentLogFile))try{let e=Wl(this.currentLogFile,"r+");Kl(e),lo(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!te()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Hi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Vi(tr(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?M.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||te())return!1;let e=typeof j.env.NO_COLOR<"u",t=j.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof j.stderr<"u"&&j.stderr.isTTY||typeof j.stdout<"u"&&j.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=j.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${M.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=M.underline(M.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>M.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>M.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>M.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>M.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>M.strikethrough(i)),t}supportsHyperlinks(){if(te())return!1;let e=j.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=j.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Eg(t)||t.startsWith("./")||t.startsWith("../"))t=xg(t);else return null;return Wi(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Uf[e],h=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:M.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:M.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.error(d),a){let p=a.split(`
14
+ `);for(let g of p)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:M.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!te()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
15
+ `;if(a)f+=`${a}
16
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!te()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!te()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!te()&&j.stdout.isTTY)j.stdout.write(`
17
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!te()&&j.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":M.blue("◐"),tag:r,message:`${M.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
18
+ `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":M.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!te())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new bn(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(te())throw Error("createReadStream is not supported in browser environments");if(!Wi(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ul(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){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 i=ot.isBuffer(e)?e:ot.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=vg("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),l=a.final(),f=c.length+l.length,u=ot.allocUnsafe(f);return c.copy(u,0),l.copy(u,c.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return te()}isServerMode(){return!te()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
19
+ `),c=Math.max(...a.map((h)=>h.length))+2,l=`┌${"─".repeat(c)}┐`,f=`└${"─".repeat(c)}┘`,u=a.map((h)=>this.formatConsoleMessage({timestamp:r,message:M.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(f),showTimestamp:!1}))}else if(!te())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
20
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(te())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${M.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();j.stdin.removeListener("data",r);try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!1)}catch{}j.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof j.stdin.setRawMode==="function")j.stdin.setRawMode(!0)}catch{}j.stdin.resume(),j.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,a=0;if(r=e.replace(o,(c,l)=>{if(l==="%")return"%";if(a>=t.length)return c;let f=t[a++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${M.blue("◐")} `;console.error(`${a}${o} ${M.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
21
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!j.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=M.green("━".repeat(i)),o=M.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?M.green("✓"):M.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=j.stdout.columns||80,p=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${p}`,j.stdout.write(e.lastRenderedLine),t)j.stdout.write(`
22
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||te()||!j.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(te()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Hi(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=tr(this.config.logDirectory,i);if(e.before)try{if((await er(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 i of r)try{await Vi(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Df(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Of(e){return e instanceof Ne}function ap(e){return e instanceof Cn}function cp(e){if(Of(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>e.message.toLowerCase().includes(t.toLowerCase()))}class Rn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return ci.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((f)=>this.formatEnvKey(f,i.useCamelCase)),c=`${r}_${a.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let f=zi.env[c]||(l?zi.env[l]:void 0);if(f!==void 0){if(i.verbose){let u=zi.env[c]?c:l}try{e[n]=this.parseEnvironmentValue(f,typeof s,c,i.customParsers,i.configName)}catch(u){if(u instanceof Sn)throw u;throw Rt.envVar(c,f,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Rt.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(zi.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
23
+
24
+ `;for(let i of e)r+=`${i.key}
25
+ `,r+=` Type: ${i.type}
26
+ `,r+=` Description: ${i.description}
27
+ `,r+=` Example: ${i.example}
28
+
29
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
30
+
31
+ `;r+=`| Variable | Type | Description | Example |
32
+ `,r+=`|----------|------|-------------|----------|
33
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
34
+ `;return r}}function lp(e,t){let r=If("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function Ff(e,t,r={}){return Lf(e,t,r,new WeakMap)}function Lf(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Mf(e,t,n,i);if(!Be(t)||!Be(e))return t;return dp(e,t,r,i)}function Mf(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return fp(e,t);case"smart":return up(e,t,i);default:return t}return t}function fp(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Po(n,i)))r.push(i);return r}function up(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Be(t[0])&&Be(e[0]))return hp(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function hp(e,t,r){let i=[...t];for(let n of e){if(!Be(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((c)=>Be(c)&&(a in c)&&c[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function dp(e,t,r,i){let n=t;if(Be(n)&&i.has(n))return i.get(n);let s={...e};if(Be(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(Be(a)&&Be(c))s[o]=Lf(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=Mf(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function aa(e,t,r="replace"){return Ff(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Po(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Po(e[r],t[r]))return!1;return!0}if(Be(e)&&Be(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Po(e[n],t[n]))return!1}return!0}return!1}function Be(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class kn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let l=lr.getWithFileCheck("file",e);if(l){if(a)console.log(`Configuration loaded from cache: ${e}`);return l}}let c=async()=>{if(!Gi(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,d=Object.keys(f).length>0;if(!h&&!d)throw new Qr(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Qr(e,Error("Configuration must export a valid object"),"unknown");let p={config:aa(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)lr.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?Rt.configLoad(e,l):Rt.configLoad(e,Error(String(l)))}};if(o)return ci.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(uo(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Df(async()=>Gi(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Gi(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=uo(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=uo(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}looksLikeConfigFile(e){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(e))}async validateConfigFile(e){let t=[];try{if(!Gi(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class ca{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return f.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(a)return await ci.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Pg(t))throw new ei(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new ei(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let l=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:Wf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class la{fileLoader=new kn;envProcessor=new Rn;validator=new ca;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let l=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(l)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let f=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),u=!f&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),h=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw c;if(u&&(!l||!h))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)He.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw He.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||Ut.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,u,o,a,l,f,c,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,u,o)),this.finalizeResult(d,h,c,i,f);let p=await this.loadHomeConfiguration(i,n,a,l,f,c);if(p)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(p,h,c,i,f);let g=await this.loadPackageJsonConfiguration(i,n,u,a,l,f,c);if(g)return h.push(ve(u,"package.json")),this.finalizeResult(g,h,c,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,o)),t)throw Rt.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,a,c,f),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let l=a?Hr(e,n,o):n,f=this.getLocalDirectories(r,i);for(let u of f){if(o)He.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)He.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?Hr(e,r,n):r,a=[ve(Jt(),".config",e),ve(Jt(),".config"),Jt()];for(let c of a){if(n)He.info(`Checking home directory: ${c}`);let l=this.fileLoader.generateConfigPaths(e,c,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(f){if(n)He.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?Hr(e,i,s):i;try{let c=ve(r,"package.json");if(!xo(c))return null;let l=await import(c),f=l[e],u=e;if(!f&&t)f=l[t],u=t;if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)He.success(`Configuration loaded from package.json: ${u}`);return{config:aa(a,f,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)He.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:Hr(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw Rt.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return lr.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);lr.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];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(e,t){return Array.from(new Set([e,ve(e,"config"),ve(e,".config"),t?ve(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(ve(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[ve(Jt(),".config",e),ve(Jt(),".config"),Jt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function tf(e){let t=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),r=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return t||r}async function mp(e){return ht.loadConfig({...e,__strictErrorHandling:!0})}async function Bf(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await ht.loadConfig(e);else i=await ht.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)He.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await ht.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}async function gp(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await ht.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&tf(r)))return(await ht.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await ht.loadConfig({...e,cwd:e.cwd||Ut.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&tf(t)))return(await ht.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function pp(e,t,r="replace"){let i=new kn;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function Hr(e,t,r=!1){let i=new Rn,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((g)=>g.toUpperCase()).join("")}`,`${n}_${u.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,p;for(let g of h)if(d=Ut.env[g],d!==void 0){p=g;break}if(d!==void 0&&p)if(typeof f==="boolean")c[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof f==="number"){let g=Number(d);if(!Number.isNaN(g))c[l]=g}else if(Array.isArray(f))try{c[l]=JSON.parse(d)}catch{c[l]=d.split(",").map((g)=>g.trim())}else c[l]=d;else if(f&&typeof f==="object"&&!Array.isArray(f))c[l]=s(f,u)}return c}return s(t)}function yp(e){let t=ve(Ut.cwd(),e.configDir),r=ve(Ut.cwd(),e.generatedDir),i=ve(r,"config-types.ts");if(!xo(Dl(i)))ng(Dl(i),{recursive:!0,mode:511});let n=xo(t)?sg(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${zp}
35
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
36
+ `;og(i,s,{mode:438})}function wp(e){let t=null,r=null,i=()=>{if(!r)r=Bf(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)He.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,o){if(t)return t[o];let a=n[o];return i(),a},has(s,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(s,o,a){if(!t)t={...n};return t[o]=a,!0}})}function vp(e){let t=Gl(kg.cwd(),e?.configDir||"./config");function r(){if(!Ag(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Rg(t).filter((c)=>n.has(ho(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:l}of o){let f=ho(l).toLowerCase(),u=a.get(c);if(!u){a.set(c,l);continue}let h=ho(u).toLowerCase();if(s.indexOf(f)<s.indexOf(h))a.set(c,l)}return Array.from(a.entries()).map(([c,l])=>({base:c,file:l})).sort((c,l)=>c.base.localeCompare(l.base))}function i(){let n=r(),s=n.map((c)=>c.base),o=s.length?s.map((c)=>`'${c}'`).join(" | "):"string",a=n.length?`{
37
+ ${n.map((c)=>{let l=Gl(t,c.file).replace(/\\/g,"/");return` '${c.base}': typeof import('${l}').default`}).join(`,
38
+ `)}
39
+ }`:"Record<string, any>";return`export type ConfigNames = ${o}
40
+ export type ConfigByName = ${a}
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(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var If,lr,ci,_f,bp,Cp,rf,nn,Ao,he,V,Sp,nf,$p,sf,Ep,xp,wo,Tp,of,af,vo,Pp,Ap,Rp,kp,sn,jf,Np,de,Dp,Op,cf,on,Ro,re,M,Fp,lf,Lp,ff,Mp,Bp,bo,Ip,uf,hf,_p,Co,jp,Up,Kp,Wp,Hp,an,Uf,Vp,zp="0.15.6",Ne,Cn,Qr,ko,No,Sn,Do,Oo,ei,Fo,Lo,Rt,Kf,Wf,He,ht,Hf,Vf,Gp=Gg(async()=>{If=import.meta.require,lr=new ia,ci=new na,_f={createKey:qg,isEquivalent:Yg,estimateMemoryUsage:Jg},bp=mn(To.cwd(),"config"),Cp=mn(To.cwd(),"src/generated"),rf=dn.env.CLARITY_LOG_DIR||lg(Qg(),"logs"),nn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:rf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ao=await ep(),he={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},V=he,Sp=he.red,nf=he.green,$p=he.yellow,sf=he.blue,Ep=he.magenta,xp=he.cyan,wo=he.white,Tp=he.gray,of=he.bgRed,af=he.bgYellow,vo=he.bold,Pp=he.dim,Ap=he.italic,Rp=he.underline,kp=he.reset,sn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jf={debug:"\uD83D\uDD0D",info:sf("ℹ"),success:nf("✓"),warning:af(wo(vo(" WARN "))),error:of(wo(vo(" ERROR ")))},Np=new wn("stacks"),de=new wn("bunfig",{showTags:!0}),Dp=we(Zr.cwd(),"config"),Op=we(Zr.cwd(),"src/generated"),cf=hn.env.CLARITY_LOG_DIR||ag(np(),"logs"),on={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:cf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ro=await sp(),re={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},M=re,Fp=re.red,lf=re.green,Lp=re.yellow,ff=re.blue,Mp=re.magenta,Bp=re.cyan,bo=re.white,Ip=re.gray,uf=re.bgRed,hf=re.bgYellow,_p=re.bgGray,Co=re.bold,jp=re.dim,Up=re.italic,Kp=re.underline,Wp=re.strikethrough,Hp=re.reset,an={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Uf={debug:"\uD83D\uDD0D",info:ff("ℹ"),success:lf("✓"),warning:hf(bo(Co(" WARN "))),error:uf(bo(Co(" ERROR ")))},Vp=new bn("stacks"),Ne=class extends Error{timestamp;context;constructor(e,t={}){super(e);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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}},Cn=class extends Ne{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r?` or alias "${r}"`:"";super(`Configuration "${e}"${i} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}},Qr=class extends Ne{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}},ko=class extends Ne{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}},No=class extends Ne{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Sn=class extends Ne{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}},Do=class extends Ne{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Oo=class extends Ne{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}},ei=class extends Ne{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}},Fo=class extends Ne{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}},Lo=class extends Ne{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}},Rt={configNotFound(e,t,r){return new Cn(e,t,r)},configLoad(e,t,r){return new Qr(e,t,r)},configValidation(e,t,r){return new ko(e,t,r)},configMerge(e,t,r,i){return new No(e,t,r,i)},envVar(e,t,r,i){return new Sn(e,t,r,i)},fileSystem(e,t,r){return new Do(e,t,r)},typeGeneration(e,t,r){return new Oo(e,t,r)},schemaValidation(e,t,r){return new ei(e,t,r)},browserConfig(e,t,r,i){return new Fo(e,t,r,i)},plugin(e,t,r){return new Lo(e,t,r)}},Kf={replace:"replace",concat:"concat",smart:"smart"},Wf=/^https?:\/\//,He=new bn("bunfig",{showTags:!0}),ht=new la,Hf=ve(Ut.cwd(),"config"),Vf=ve(Ut.cwd(),"src/generated")});function qp(e,t={}){let r=gn.cwd();while(r.includes("storage"))r=ql(r,"..");let i=ql(r,e||"");if(t?.relative)return Dg(gn.cwd(),i);return i}var Yp=gn.env.CLARITY_LOG_DIR||Ng(qp(),"logs"),zf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Yp,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},$n={...zf},vE=(async()=>{try{let{loadConfig:e}=await Gp().then(()=>Rf),t=await e({name:"clarity",alias:"logging",defaultConfig:zf,cwd:gn.cwd()});if(t)Object.assign($n,t)}catch{}return $n})();function ie(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Jp(){if(ft.env.NODE_ENV==="test"||ft.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ft<"u"){let e=ft.type;if(e==="renderer"||e==="worker")return!1;return!!(ft.versions&&(ft.versions.node||ft.versions.bun))}return!1}class Gf{async format(e){let t=await Jp(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:sr.pid,hostname:t(),environment:sr.env.NODE_ENV||"development",platform:sr.platform,version:sr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:sr.env.NODE_ENV||sr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ce={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},I=ce,bE=ce.red,Xp=ce.green,CE=ce.yellow,Zp=ce.blue,SE=ce.magenta,$E=ce.cyan,df=ce.white,EE=ce.gray,Qp=ce.bgRed,ey=ce.bgYellow,xE=ce.bgGray,mf=ce.bold,TE=ce.dim,PE=ce.italic,AE=ce.underline,RE=ce.strikethrough,kE=ce.reset,So={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ty={debug:"\uD83D\uDD0D",info:Zp("ℹ"),success:Xp("✓"),warning:ey(df(mf(" WARN "))),error:Qp(df(mf(" ERROR ")))};class Nn{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(e,t={}){this.name=e,this.config={...$n},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Gf,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??U.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...So,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...So};return{...So,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:$n.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ie()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let i,n=0,s=3,o=1000;while(n<s)try{try{try{await Bg(this.config.logDirectory,Zl.F_OK|Zl.W_OK)}catch(c){if(c instanceof Error&&"code"in c)if(c.code==="ENOENT")await Ig(this.config.logDirectory,{recursive:!0,mode:493});else if(c.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw c;else throw c}}catch(c){throw console.error("Debug: [writeToFile] Failed to create log directory:",c),c}let a=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:at.from(e);try{if(!qi(this.currentLogFile))await po(this.currentLogFile,"",{mode:420});if(i=Xl(this.currentLogFile,"a",420),Mg(i,a,{flag:"a"}),Jl(i),i!==void 0)go(i),i=void 0;if((await ir(this.currentLogFile)).size===0){if(await po(this.currentLogFile,a,{flag:"w",mode:420}),(await ir(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(c){let l=c;if(l.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(l.code)){if(n<s-1){let f=typeof l.message==="string"?l.message:"Unknown error";console.error(`Network error during write attempt ${n+1}/${s}:`,f);let u=o*2**n;await new Promise((h)=>setTimeout(h,u)),n++;continue}}if(l?.code&&["ENOSPC","EDQUOT"].includes(l.code))throw Error(`Disk quota exceeded or no space left on device: ${l.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",l),l}finally{if(i!==void 0)try{go(i)}catch(c){console.error("Debug: [writeToFile] Error closing file descriptor:",c)}}}catch(a){if(n===s-1){let l=a,f=typeof l.message==="string"?l.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),a}n++;let c=o*2**(n-1);await new Promise((l)=>setTimeout(l,c))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(i){throw console.error("Debug: [writeToFile] Error in operation:",i),i}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 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 e=new Date().toISOString().split("T")[0];return nr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ie())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.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 e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((i)=>{console.error("Error rotating keys:",i)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=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 i=Array.from(this.encryptionKeys.entries()).sort(([,o],[,a])=>a.createdAt.getTime()-o.createdAt.getTime()),n=typeof e.maxKeys==="number"?e.maxKeys:1,s=Math.max(1,n);if(i.length>s)for(let[o]of i.slice(s))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return mo(16).toString("hex")}generateKey(){return mo(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=mo(16),i=Og("aes-256-gcm",t,r),n=at.isBuffer(e)?e:at.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),l=at.allocUnsafe(16+a+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),c.copy(l,16+a),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=ef(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(at.from(at.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ie())return;if(!this.shouldWriteToFile())return;let e=await ir(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Yi(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await ir(r).catch(()=>null))try{if(await Ql(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Ji(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await po(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await ir(r).catch(()=>null))await Ql(r,s)}if(this.currentLogFile=i,t.maxFiles){let n=(await Yi(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,o)=>o.localeCompare(s));for(let s of n.slice(t.maxFiles))await Ji(nr(this.config.logDirectory,s))}}}async compressLogFile(e,t){let r=Yl(e),i=Lg(t),n=ef();await Ug(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),qi(this.currentLogFile))try{let e=Xl(this.currentLogFile,"r+");Jl(e),go(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ie()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await Yi(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await Ji(nr(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?I.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ie())return!1;let e=typeof U.env.NO_COLOR<"u",t=U.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof U.stderr<"u"&&U.stderr.isTTY||typeof U.stdout<"u"&&U.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=U.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${I.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=I.underline(I.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>I.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>I.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>I.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>I.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>I.strikethrough(i)),t}supportsHyperlinks(){if(ie())return!1;let e=U.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=U.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(_g(t)||t.startsWith("./")||t.startsWith("../"))t=jg(t);else return null;return qi(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":ty[e],h=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:I.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:I.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.error(d),a){let p=a.split(`
44
+ `);for(let g of p)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:I.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!ie()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
45
+ `;if(a)f+=`${a}
46
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(n,s)=>{},finish:(n)=>{},interrupt:(n,s)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!ie()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(n,s)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,n),this.activeProgressBar.total),s!==void 0)this.activeProgressBar.message=s;if(this.shouldStyleConsole()&&!ie()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(n)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,n)},interrupt:(n,s="info")=>{if(!ie()&&U.stdout.isTTY)U.stdout.write(`
47
+ `);if(this[s==="warning"?"warn":s](n),this.activeProgressBar&&this.shouldStyleConsole()&&!ie()&&U.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":I.blue("◐"),tag:r,message:`${I.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),c=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)c+=` ${JSON.stringify(r)}`;if(c+=`
48
+ `,c=c.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":I.green("✓"),tag:l,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ie())console.error(c.trim());if(this.shouldWriteToFile())await this.writeToFile(c)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new Nn(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(ie())throw Error("createReadStream is not supported in browser environments");if(!qi(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Yl(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){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 i=at.isBuffer(e)?e:at.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=Fg("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),l=a.final(),f=c.length+l.length,u=at.allocUnsafe(f);return c.copy(u,0),l.copy(u,c.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ie()}isServerMode(){return!ie()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
49
+ `),c=Math.max(...a.map((h)=>h.length))+2,l=`┌${"─".repeat(c)}┐`,f=`└${"─".repeat(c)}┘`,u=a.map((h)=>this.formatConsoleMessage({timestamp:r,message:I.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:I.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:I.cyan(f),showTimestamp:!1}))}else if(!ie())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
50
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(ie())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${I.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();U.stdin.removeListener("data",r);try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!1)}catch{}U.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof U.stdin.setRawMode==="function")U.stdin.setRawMode(!0)}catch{}U.stdin.resume(),U.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,a=0;if(r=e.replace(o,(c,l)=>{if(l==="%")return"%";if(a>=t.length)return c;let f=t[a++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let o=this.options.showTags!==!1&&this.name?I.gray(this.formatTag(this.name)):"",a=this.options.showIcons===!1?"":`${I.blue("◐")} `;console.error(`${a}${o} ${I.cyan(i)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
51
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!U.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=I.green("━".repeat(i)),o=I.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?I.green("✓"):I.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${I.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=U.stdout.columns||80,p=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${p}`,U.stdout.write(e.lastRenderedLine),t)U.stdout.write(`
52
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ie()||!U.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ie()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Yi(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let n=nr(this.config.logDirectory,i);if(e.before)try{if((await ir(n)).mtime>=e.before)continue}catch(s){console.error(`Failed to get stats for file ${n}:`,s);continue}r.push(n)}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 i of r)try{await Ji(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var NE=new Nn("stacks");class ze extends Error{timestamp;context;constructor(e,t={}){super(e);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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class qf extends ze{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class En extends ze{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Yf extends ze{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Jf extends ze{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class fa extends ze{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}}class Xf extends ze{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Zf extends ze{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class xn extends ze{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Qf extends ze{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}}class eu extends ze{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var fr={configNotFound(e,t,r){return new qf(e,t,r)},configLoad(e,t,r){return new En(e,t,r)},configValidation(e,t,r){return new Yf(e,t,r)},configMerge(e,t,r,i){return new Jf(e,t,r,i)},envVar(e,t,r,i){return new fa(e,t,r,i)},fileSystem(e,t,r){return new Xf(e,t,r)},typeGeneration(e,t,r){return new Zf(e,t,r)},schemaValidation(e,t,r){return new xn(e,t,r)},browserConfig(e,t,r,i){return new Qf(e,t,r,i)},plugin(e,t,r){return new eu(e,t,r)}};async function ry(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class ua{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return ra.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((f)=>this.formatEnvKey(f,i.useCamelCase)),c=`${r}_${a.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let f=Xi.env[c]||(l?Xi.env[l]:void 0);if(f!==void 0){if(i.verbose){let u=Xi.env[c]?c:l}try{e[n]=this.parseEnvironmentValue(f,typeof s,c,i.customParsers,i.configName)}catch(u){if(u instanceof fa)throw u;throw fr.envVar(c,f,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw fr.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(Xi.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
53
+
54
+ `;for(let i of e)r+=`${i.key}
55
+ `,r+=` Type: ${i.type}
56
+ `,r+=` Description: ${i.description}
57
+ `,r+=` Example: ${i.example}
58
+
59
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
60
+
61
+ `;r+=`| Variable | Type | Description | Example |
62
+ `,r+=`|----------|------|-------------|----------|
63
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
64
+ `;return r}}function iy(e,t,r={}){return tu(e,t,r,new WeakMap)}function tu(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return ru(e,t,n,i);if(!Ie(t)||!Ie(e))return t;return ay(e,t,r,i)}function ru(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return ny(e,t);case"smart":return sy(e,t,i);default:return t}return t}function ny(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Mo(n,i)))r.push(i);return r}function sy(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Ie(t[0])&&Ie(e[0]))return oy(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function oy(e,t,r){let i=[...t];for(let n of e){if(!Ie(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((c)=>Ie(c)&&(a in c)&&c[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function ay(e,t,r,i){let n=t;if(Ie(n)&&i.has(n))return i.get(n);let s={...e};if(Ie(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(Ie(a)&&Ie(c))s[o]=tu(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=ru(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function iu(e,t,r="replace"){return iy(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mo(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Mo(e[r],t[r]))return!1;return!0}if(Ie(e)&&Ie(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Mo(e[n],t[n]))return!1}return!0}return!1}function Ie(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class nu{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let l=pn.getWithFileCheck("file",e);if(l){if(a)console.log(`Configuration loaded from cache: ${e}`);return l}}let c=async()=>{if(!Zi(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,d=Object.keys(f).length>0;if(!h&&!d)throw new En(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new En(e,Error("Configuration must export a valid object"),"unknown");let p={config:iu(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)pn.setWithFileCheck("file",p,e,s);return p}catch(l){throw l instanceof Error?fr.configLoad(e,l):fr.configLoad(e,Error(String(l)))}};if(o)return ra.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(yo(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return ry(async()=>Zi(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Zi(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=yo(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=yo(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}looksLikeConfigFile(e){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(e))}async validateConfigFile(e){let t=[];try{if(!Zi(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}var cy=/^https?:\/\//;class su{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return f.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(a)return await ra.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!Kg(t))throw new xn(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new xn(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let l=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:cy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Ze=new Nn("bunfig",{showTags:!0});function ly(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class ou{fileLoader=new nu;envProcessor=new ua;validator=new su;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let l=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(l)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let f=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),u=!f&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),h=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw c;if(u&&(!l||!h))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)Ze.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw Ze.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||An.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,u,o,a,l,f,c,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,u,o)),this.finalizeResult(d,h,c,i,f);let p=await this.loadHomeConfiguration(i,n,a,l,f,c);if(p)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(p,h,c,i,f);let g=await this.loadPackageJsonConfiguration(i,n,u,a,l,f,c);if(g)return h.push(Me(u,"package.json")),this.finalizeResult(g,h,c,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,o)),t)throw fr.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,a,c,f),warnings:[`No configuration file found for "${i}"${ly(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let l=a?en(e,n,o):n,f=this.getLocalDirectories(r,i);for(let u of f){if(o)Ze.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)Ze.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?en(e,r,n):r,a=[Me(Yt(),".config",e),Me(Yt(),".config"),Yt()];for(let c of a){if(n)Ze.info(`Checking home directory: ${c}`);let l=this.fileLoader.generateConfigPaths(e,c,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(f){if(n)Ze.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?en(e,i,s):i;try{let c=Me(r,"package.json");if(!rg(c))return null;let l={};try{l=JSON.parse(ig(c,"utf8"))}catch(h){if(s)Ze.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=l[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){f=l[d],u=d;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)Ze.success(`Configuration loaded from package.json: ${u}`);return{config:iu(a,f,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)Ze.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:en(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw fr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return pn.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);pn.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}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(e,t){return Array.from(new Set([e,Me(e,"config"),Me(e,".config"),t?Me(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Me(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Me(Yt(),".config",e),Me(Yt(),".config"),Yt()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}var $o=new ou;async function fy(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await $o.loadConfig(e);else i=await $o.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Ze.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let o=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await $o.applyEnvironmentVariables(o.name||"",t,!0,o.verbose||!1))?.config??t;return t}}function en(e,t,r=!1){let i=new ua,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((g)=>g.toUpperCase()).join("")}`,`${n}_${u.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,p;for(let g of h)if(d=An.env[g],d!==void 0){p=g;break}if(d!==void 0&&p)if(typeof f==="boolean")c[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof f==="number"){let g=Number(d);if(!Number.isNaN(g))c[l]=g}else if(Array.isArray(f))try{c[l]=JSON.parse(d)}catch{c[l]=d.split(",").map((g)=>g.trim())}else c[l]=d;else if(f&&typeof f==="object"&&!Array.isArray(f))c[l]=s(f,u)}return c}return s(t)}var DE=Me(An.cwd(),"config"),OE=Me(An.cwd(),"src/generated"),Dn={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:ro.join(to.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:ro.join(to.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:ro.join(to.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},Eo=null;async function au(){if(!Eo)Eo=await fy({name:"tlsx",alias:"tls",defaultConfig:Dn});return Eo}var O=Dn,z={info:(...e)=>console.log(...e),warn:(...e)=>console.warn(...e),success:(...e)=>console.log(...e),error:(...e)=>console.error(...e),debug:(...e)=>console.debug(...e)};function ha(e){return ar.readFileSync(e,"utf8")}function lu(e){let t=Bo.platform(),r;if(!e)if(t==="darwin")r="/etc/ssl/certs";else if(t==="win32")r="C:\\Windows\\System32\\certsrv\\CertEnroll";else if(t==="linux")r="/etc/ssl/certs";else throw Error(`Unsupported platform: ${t}`);else r=e;let i=ar.readdirSync(r).filter((s)=>s.endsWith(".crt")).map((s)=>xe.join(r,s)),n=xe.join(Bo.homedir(),".stacks","ssl");if(ar.existsSync(n))i.push(...ar.readdirSync(n).filter((s)=>s.endsWith(".crt")).map((s)=>xe.join(n,s)));return i}function da(e){let t=Number.parseInt(e[0],16);if(t<8)return e;return t-=8,t.toString()+e.substring(1)}function ti(e,t){let r=[];function i(n){let s;try{s=ar.readdirSync(n)}catch{return}for(let o of s){let a=xe.join(n,o);try{if(ar.statSync(a).isDirectory())i(a);else if(o===t)r.push(n)}catch{continue}}}return i(e),r}function v(e,t,r){if(r||O.verbose)console.debug(`[tlsx:${e}] ${t}`)}var dy=hy(uy);function ma(){return cu.env.SUDO_PASSWORD}var gf="[redacted]",my=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),gy=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function py(e){let t=e.toLowerCase();return my.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function ri(e){if(Array.isArray(e))return e.map((r)=>ri(r));if(typeof e==="string")return gy.test(e)?gf:e;if(!e||typeof e!=="object")return e;let t={};for(let[r,i]of Object.entries(e)){if(py(r)){t[r]=gf;continue}t[r]=ri(i)}return t}function li(e){return JSON.stringify(ri(e))}function yy(e){let t=ma();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(e))return e;let r=t.replace(/'/g,"'\\''"),i=e.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${i}`}async function Te(e,t={}){let r=yy(e);try{let{stdout:i,stderr:n}=await dy(r,{cwd:t.cwd||cu.cwd(),timeout:t.timeout||30000});return{stdout:i.trim(),stderr:n.trim()}}catch(i){let n=Error(`Failed to execute command: ${e}
65
+ Error: ${i.message}`);throw n.stack=i.stack,n}}function ga(e){if(e.domain)return e.domain;if(e.domains?.length)return e.domains[0];throw Error("Either domain or domains must be specified")}function dr(e){let t=xe.join(Bo.homedir(),".stacks","ssl"),r=e.basePath&&e.basePath.trim()!==""?e.basePath:O.basePath&&O.basePath.trim()!==""?O.basePath:t,i=e.certPath?xe.isAbsolute(e.certPath)?e.certPath:xe.join(r,e.certPath):xe.join(r,O.certPath),n=e.keyPath?xe.isAbsolute(e.keyPath)?e.keyPath:xe.join(r,e.keyPath):xe.join(r,O.keyPath),s=e.caCertPath?xe.isAbsolute(e.caCertPath)?e.caCertPath:xe.join(r,e.caCertPath):xe.join(r,O.caCertPath);return{certPath:i,keyPath:n,caCertPath:s,basePath:r}}function fu(e){return e.startsWith("*.")?`_wildcard.${e.slice(2)}`:e}function uu(e){return e.replace(/\.crt$/,"")}function mt(e){let t;if(e.startsWith("-----BEGIN CERTIFICATE-----"))t=e;else t=ha(e);return new ii.X509Certificate(t)}function mr(e){return mt(e).fingerprint256.replace(/:/g,"").toUpperCase()}var vy=/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g;function pa(e){return e.match(vy)??[]}function On(e){let t=e.replace(/-----BEGIN [A-Z ]+-----/,"").replace(/-----END [A-Z ]+-----[\s\S]*$/,"").replace(/\s+/g,"");return Buffer.from(t,"base64")}function Fn(e){return ii.createHash("sha256").update(e).digest("hex").toUpperCase()}function ya(e,t){let r=t.replace(/:/g,"").toUpperCase();for(let i of pa(e))try{if(Fn(On(i))===r)return!0}catch{}return!1}function gr(e){return ni(mt(e).subject)}function Ln(e,t,r=443,i=4000){let n;try{n=t.includes("-----BEGIN")?t:_t.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((s)=>{let o=!1,a=(l)=>{if(o)return;o=!0,s(l)},c=wy.connect({host:e,port:r,servername:e,ca:n,rejectUnauthorized:!0},()=>{a(c.authorized),c.end()});c.setTimeout(i,()=>{c.destroy(),a(!1)}),c.on("error",()=>a(!1))})}function Io(e){let t=[],r=e.split(`
66
+ `);for(let i of r){let[n,...s]=i.split("="),o=s.join("=");if(n&&o)t.push({shortName:n.trim(),value:o.trim()})}return t}function ni(e){return Io(e).find((t)=>t.shortName==="CN")?.value||""}function hu(e){let t=[],r=ni(e.subject);if(r&&!/^\d+\.\d+\.\d+\.\d+$/.test(r))t.push(r);let i=e.subjectAltName;if(i){let n=i.split(", ");for(let s of n)if(s.startsWith("DNS:"))t.push(s.slice(4))}return[...new Set(t)]}function Mn(e,t){let r=mt(e),i=hu(r);for(let n of i){if(n===t)return!0;if(n.startsWith("*.")){let s=n.slice(2);if(t.endsWith(s)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}function du(e){let t=mt(e);return{subject:Io(t.subject),issuer:Io(t.issuer),validFrom:new Date(t.validFrom),validTo:new Date(t.validTo),serialNumber:t.serialNumber}}function mu(e){let t=mt(e);return new Date>new Date(t.validTo)}function gu(e,t=30){let r=mt(e),i=new Date;return(new Date(r.validTo).getTime()-i.getTime())/86400000<=t}function pu(e,t,r){v(b.CERT,`Validating certificate: ${e}`,r);try{if(!_t.existsSync(e))return{valid:!1,expired:!1,notYetValid:!1,issuerValid:!1,domains:[],validFrom:new Date,validTo:new Date,issuer:"",subject:"",message:`Certificate file not found: ${e}`};let i=_t.readFileSync(e,"utf8"),n=new ii.X509Certificate(i),s=new Date,o=new Date(n.validFrom),a=new Date(n.validTo),c=s>a,l=s<o,f=ni(n.subject),u=ni(n.issuer),h=hu(n),d=!1;if(t)if(_t.existsSync(t))try{let p=_t.readFileSync(t,"utf8"),g=new ii.X509Certificate(p);d=n.verify(g.publicKey)}catch(p){v(b.CERT,`Error validating CA certificate: ${p}`,r)}else v(b.CERT,`CA certificate file not found: ${t}`,r);return{valid:!c&&!l&&(t?d:!0),expired:c,notYetValid:l,issuerValid:d,domains:h,validFrom:o,validTo:a,issuer:u,subject:f}}catch(i){return v(b.CERT,`Error validating certificate: ${i}`,r),{valid:!1,expired:!1,notYetValid:!1,issuerValid:!1,domains:[],validFrom:new Date,validTo:new Date,issuer:"",subject:"",message:`Error validating certificate: ${i}`}}}function yu(e,t){v(b.CERT,`Validating browser compatibility: ${e}`,t);try{if(!_t.existsSync(e))return{compatible:!1,issues:[`Certificate file not found: ${e}`]};let r=_t.readFileSync(e,"utf8"),i=new ii.X509Certificate(r),n=[],s=!1,o=!1;if(ni(i.subject)==="localhost")s=!0;let a=i.subjectAltName;if(a){let h=a.split(", ");for(let d of h){if(d==="DNS:localhost")s=!0;if(d.includes("*"))o=!0}}if(!s)n.push('Certificate does not include "localhost" in Subject Alternative Names, which may cause issues with some browsers.');if(o)n.push("Certificate contains wildcard domains, which may not be fully supported in all browsers for localhost development.");let c=i.keyUsage,l=i.extKeyUsage||"";if(!(l.includes("TLS Web Server Authentication")||l.includes("1.3.6.1.5.5.7.3.1")))n.push("Certificate lacks Extended Key Usage for serverAuth, which is required by modern browsers.");let f=new Date(i.validFrom),u=(new Date(i.validTo).getTime()-f.getTime())/86400000;if(u>398)n.push(`Certificate validity period is ${Math.floor(u)} days, which exceeds the 398-day maximum supported by modern browsers.`);return{compatible:n.length===0,issues:n}}catch(r){return v(b.CERT,`Error validating browser compatibility: ${r}`,t),{compatible:!1,issues:[`Error validating browser compatibility: ${r}`]}}}var wa=["macos","ios","windows","debian","rhel","android","linux-nss"],va={pem:"application/x-pem-file",der:"application/x-x509-ca-cert",mobileconfig:"application/x-apple-aspen-config"},Sy={pem:"pem",der:"cer",mobileconfig:"mobileconfig"},Bn="dev.stacksjs.tlsx",$y="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Ey(e){return Buffer.from(e.replace(/-/g,""),"hex")}function si(e,t=ba){let r=by.createHash("sha1").update(Buffer.concat([Ey(t),Buffer.from(e,"utf8")])).digest(),i=Buffer.from(r.subarray(0,16));i[6]=i[6]&15|80,i[8]=i[8]&63|128;let n=i.toString("hex").toUpperCase();return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}var ba=si(Bn,$y);function tn(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function wu(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"root-ca"}function pf(e,t){for(let r of e.split(`
67
+ `)){let i=r.indexOf("=");if(i!==-1&&r.slice(0,i).trim()===t)return r.slice(i+1).trim()}return}function xy(e,t=64){let r=[];for(let i=0;i<e.length;i+=t)r.push(e.slice(i,i+t));return r.join(`
68
+ `)}function Ca(e){let t=e.fingerprint.replace(/:/g,"").toUpperCase(),r=si(`${t}:profile`),i=si(`${t}:root`),n=xy(Buffer.from(e.certificateDer).toString("base64")),s=tn(e.displayName),o=tn(e.organization),a=tn(e.identifier);return`<?xml version="1.0" encoding="UTF-8"?>
69
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
70
+ <plist version="1.0">
71
+ <dict>
72
+ <key>PayloadContent</key>
73
+ <array>
74
+ <dict>
75
+ <key>PayloadCertificateFileName</key>
76
+ <string>${tn(`${wu(e.displayName)}.cer`)}</string>
77
+ <key>PayloadContent</key>
78
+ <data>
79
+ ${n}
80
+ </data>
81
+ <key>PayloadDescription</key>
82
+ <string>Adds the ${s} root certificate</string>
83
+ <key>PayloadDisplayName</key>
84
+ <string>${s}</string>
85
+ <key>PayloadIdentifier</key>
86
+ <string>${a}.root</string>
87
+ <key>PayloadType</key>
88
+ <string>com.apple.security.root</string>
89
+ <key>PayloadUUID</key>
90
+ <string>${i}</string>
91
+ <key>PayloadVersion</key>
92
+ <integer>1</integer>
93
+ </dict>
94
+ </array>
95
+ <key>PayloadDescription</key>
96
+ <string>Trusts the ${s} certificate authority on this device (SHA-256 ${t.slice(0,16)})</string>
97
+ <key>PayloadDisplayName</key>
98
+ <string>${s}</string>
99
+ <key>PayloadIdentifier</key>
100
+ <string>${a}</string>
101
+ <key>PayloadOrganization</key>
102
+ <string>${o}</string>
103
+ <key>PayloadRemovalDisallowed</key>
104
+ <false/>
105
+ <key>PayloadType</key>
106
+ <string>Configuration</string>
107
+ <key>PayloadUUID</key>
108
+ <string>${r}</string>
109
+ <key>PayloadVersion</key>
110
+ <integer>1</integer>
111
+ </dict>
112
+ </plist>
113
+ `}async function vu(e){let t=e.caCertPath.startsWith("-----BEGIN")?e.caCertPath:Cy.readFileSync(e.caCertPath,"utf8"),r=mt(t),i=On(t),n=Fn(i),s=e.name?.trim()||pf(r.subject,"CN")||"tlsx Root CA",o=e.organization?.trim()||pf(r.subject,"O")||"tlsx",a=e.identifier?.trim()||`${Bn}.${n.slice(0,12).toLowerCase()}`,c=`${wu(s)}.${Sy[e.format]}`,l=va[e.format];switch(e.format){case"pem":return{data:t.endsWith(`
114
+ `)?t:`${t}
115
+ `,filename:c,mime:l};case"der":return{data:new Uint8Array(i),filename:c,mime:l};case"mobileconfig":return{data:Ca({certificateDer:i,displayName:s,organization:o,identifier:a,fingerprint:n}),filename:c,mime:l};default:throw Error(`Unsupported export format: ${String(e.format)}`)}}function bu(e,t){switch(e){case"macos":return["macOS (system keychain, all users and browsers):",` sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`," Restart any open browser afterwards."].join(`
116
+ `);case"ios":return["iOS / iPadOS (configuration profile):",` 1. Export the profile if you have not yet: tlsx export-ca --format mobileconfig --out ${t}`,` 2. Send ${t} to the device (AirDrop, Mail, or a link) and open it.`," 3. Settings > Profile Downloaded > Install, and confirm with the passcode."," 4. Settings > General > About > Certificate Trust Settings, then enable full trust for the new root."," Without step 4 the profile is installed but Safari still rejects the certificate."].join(`
117
+ `);case"windows":return["Windows (Local Machine root store, run from an elevated prompt):",` certutil -addstore -f ROOT ${t}`," Or double-click the file, Install Certificate, Local Machine, Trusted Root Certification Authorities."].join(`
118
+ `);case"debian":return["Debian / Ubuntu / Raspberry Pi OS:",` sudo cp ${t} /usr/local/share/ca-certificates/tlsx-root-ca.crt`," sudo update-ca-certificates"," The file must end in .crt to be picked up. Browsers using NSS (Firefox, Chromium) keep their own store; see linux-nss."].join(`
119
+ `);case"rhel":return["RHEL / Fedora / Rocky / AlmaLinux:",` sudo cp ${t} /etc/pki/ca-trust/source/anchors/tlsx-root-ca.crt`," sudo update-ca-trust"].join(`
120
+ `);case"android":return["Android (user CA):",` 1. Copy ${t} to the device (it must be PEM or DER with a .crt or .cer extension).`," 2. Settings > Security > Encryption & credentials > Install a certificate > CA certificate."," Apps only trust user CAs when their network security config opts in (Android 7+); Chrome does, most apps do not."].join(`
121
+ `);case"linux-nss":return["Linux browser stores (Firefox, Chromium via NSS):",` certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "tlsx Root CA" -i ${t}`," For Firefox, repeat with -d sql:$HOME/.mozilla/firefox/<profile>, or import via Settings > Privacy & Security > Certificates."," tlsx install does this for every cert9.db it finds under your home directory."].join(`
122
+ `);default:throw Error(`Unknown platform: ${String(e)}. Expected one of ${wa.join(", ")}`)}}function In(e){let t=[],r=new Set;if(e.domain)r.add(e.domain);if(e.domains?.length)e.domains.forEach((i)=>r.add(i));for(let i of r)t.push({type:2,value:i});if(e.altNameIPs?.length)for(let i of e.altNameIPs)t.push({type:7,ip:i});if(e.altNameURIs?.length)for(let i of e.altNameURIs)t.push({type:6,value:i});if(e.subjectAltNames?.length)t.push(...e.subjectAltNames);return v(b.CERT,`Generated ${t.length} Subject Alternative Names`,e.verbose),t}function Cu(e){v(b.CERT,"Generating random serial number",e);let t=Ty.randomBytes(20),r=da(t.toString("hex"));return v(b.CERT,`Generated serial number: ${r}`,e),r}function _n(e){let t=e.notBeforeDays??De.DEFAULT_NOT_BEFORE_DAYS,r=e.validityDays??(e.validityYears?e.validityYears*365:De.DEFAULT_VALIDITY_DAYS);v(b.CERT,"Calculating certificate validity dates",e.verbose);let i=new Date(Date.now()-86400*t*1000),n=new Date(i.getTime()+r*24*60*60*1000);return i.setUTCHours(0,0,0,0),n.setUTCHours(23,59,59,999),v(b.CERT,`Validity period: ${i.toISOString()} to ${n.toISOString()}`,e.verbose),{notBefore:i,notAfter:n}}function Su(e){let t=[];t.push({name:"basicConstraints",cA:e.isCA??!1,critical:!0,...e.basicConstraints||{}});let r=In(e);if(r.length>0)t.push({name:"subjectAltName",altNames:r});let i=e.keyUsage||{digitalSignature:!0,keyEncipherment:!0};t.push({name:"keyUsage",critical:!0,...i});let n=e.extKeyUsage||{serverAuth:!0};return t.push({name:"extKeyUsage",...n}),t}var Ve={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},be={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 qr(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function Fe(e,t){let r=qr(t.length);return Buffer.concat([Buffer.from([e]),r,t])}function oi(e){let t=e.split(".").map(Number),r=[];r.push(40*t[0]+t[1]);for(let i=2;i<t.length;i++){let n=t[i],s=[];s.unshift(n&127),n>>=7;while(n>0)s.unshift(n&127|128),n>>=7;r.push(...s)}return Fe(Ve.OID,Buffer.from(r))}function _o(e){let t;if(typeof e==="bigint"){let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof e==="number")if(e===0)t=Buffer.from([0]);else{let r=e.toString(16).padStart(2,"0");t=Buffer.from(r.length%2?`0${r}`:r,"hex")}else t=e;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Fe(Ve.INTEGER,t)}function $u(e,t=0){return Fe(Ve.BIT_STRING,Buffer.concat([Buffer.from([t]),e]))}function Eu(e){return Fe(Ve.OCTET_STRING,e)}function Oe(...e){return Fe(Ve.SEQUENCE,Buffer.concat(e))}function Py(...e){return Fe(Ve.SET,Buffer.concat(e))}function Ay(e){return Fe(Ve.PRINTABLE_STRING,Buffer.from(e,"ascii"))}function Ry(e){return Fe(Ve.UTF8_STRING,Buffer.from(e,"utf8"))}function ky(){return Buffer.from([Ve.NULL,0])}function yf(e,t,r=!0){let i=160|e|(r?0:0),n=qr(t.length);return Buffer.concat([Buffer.from([i]),n,t])}function wf(e){let t=e.getUTCFullYear();if(t>=2050){let r=e.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Fe(Ve.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(t%100).toString().padStart(2,"0"),i=(e.getUTCMonth()+1).toString().padStart(2,"0"),n=e.getUTCDate().toString().padStart(2,"0"),s=e.getUTCHours().toString().padStart(2,"0"),o=e.getUTCMinutes().toString().padStart(2,"0"),a=e.getUTCSeconds().toString().padStart(2,"0"),c=`${r}${i}${n}${s}${o}${a}Z`;return Fe(Ve.UTC_TIME,Buffer.from(c,"ascii"))}}function Ny(e,t){return Oe(wf(e),wf(t))}function vf(e){let t=[];for(let r of e){let i;switch(r.shortName){case"CN":i=be.COMMON_NAME;break;case"C":i=be.COUNTRY;break;case"L":i=be.LOCALITY;break;case"ST":i=be.STATE;break;case"O":i=be.ORGANIZATION;break;case"OU":i=be.ORGANIZATIONAL_UNIT;break;default:continue}let n=r.shortName==="C"?Ay(r.value):Ry(r.value),s=Oe(oi(i),n);t.push(Py(s))}return Oe(...t)}function xu(e){return Oe(oi(e),ky())}function Dy(e){return e.export({type:"spki",format:"der"})}function Oy(e){if(e.includes(":")){let t=e;if(e.includes("::")){let n=e.split("::"),s=n[0]?n[0].split(":"):[],o=n[1]?n[1].split(":"):[],a=8-s.length-o.length,c=Array.from({length:a},()=>"0");t=[...s,...c,...o].join(":")}let r=t.split(":"),i=Buffer.alloc(16);for(let n=0;n<8;n++){let s=Number.parseInt(r[n]||"0",16);i.writeUInt16BE(s,n*2)}return i}else{let t=e.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(t)}}function Fy(e){let t=[];for(let r of e)if(r.type===2&&r.value){let i=qr(r.value.length);t.push(Buffer.concat([Buffer.from([130]),i,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let i=Oy(r.ip),n=qr(i.length);t.push(Buffer.concat([Buffer.from([135]),n,i]))}else if(r.type===6&&r.value){let i=qr(r.value.length);t.push(Buffer.concat([Buffer.from([134]),i,Buffer.from(r.value,"ascii")]))}return Oe(...t)}function Ly(e,t){if(e){if(t!==void 0)return Oe(Fe(1,Buffer.from([255])),_o(t));return Oe(Fe(1,Buffer.from([255])))}return Oe()}function My(e){let t=0;if(e.digitalSignature)t|=128;if(e.keyEncipherment)t|=32;if(e.keyCertSign)t|=4;if(e.cRLSign)t|=2;let r=0,i=t;while(i>0&&(i&1)===0)r++,i>>=1;if(t===0)r=7;return $u(Buffer.from([t]),r)}function By(e){let t=[];if(e.serverAuth)t.push(oi(be.SERVER_AUTH));if(e.clientAuth)t.push(oi(be.CLIENT_AUTH));return Oe(...t)}function Kr(e,t,r){let i=[oi(e)];if(t)i.push(Fe(1,Buffer.from([255])));return i.push(Eu(r)),Oe(...i)}function Iy(e){let t=[];if(t.push(yf(0,_o(2))),t.push(_o(e.serialNumber)),t.push(xu(be.SHA256_WITH_RSA)),t.push(vf(e.issuer)),t.push(Ny(e.notBefore,e.notAfter)),t.push(vf(e.subject)),t.push(Dy(e.publicKey)),e.extensions){let r=[];if(e.extensions.basicConstraints)r.push(Kr(be.BASIC_CONSTRAINTS,e.extensions.basicConstraints.critical??!0,Ly(e.extensions.basicConstraints.isCA,e.extensions.basicConstraints.pathLenConstraint)));if(e.extensions.keyUsage)r.push(Kr(be.KEY_USAGE,e.extensions.keyUsage.critical??!0,My(e.extensions.keyUsage)));if(e.extensions.extendedKeyUsage)r.push(Kr(be.EXTENDED_KEY_USAGE,!1,By(e.extensions.extendedKeyUsage)));if(e.extensions.subjectAltName?.length)r.push(Kr(be.SUBJECT_ALT_NAME,!1,Fy(e.extensions.subjectAltName)));if(e.extensions.subjectKeyIdentifier)r.push(Kr(be.SUBJECT_KEY_IDENTIFIER,!1,Eu(e.extensions.subjectKeyIdentifier)));if(r.length>0)t.push(yf(3,Oe(...r)))}return Oe(...t)}function _y(e,t){let r=pr.createSign("SHA256");r.update(e);let i=r.sign(t);return Oe(e,xu(be.SHA256_WITH_RSA),$u(i))}function jy(e,t){let r=e.toString("base64"),i=[];for(let n=0;n<r.length;n+=64)i.push(r.slice(n,n+64));return`-----BEGIN ${t}-----
123
+ ${i.join(`
124
+ `)}
125
+ -----END ${t}-----
126
+ `}function Sa(){let e=pr.randomBytes(20);return e[0]=e[0]&127||1,e}function Tu(e=2048){let{privateKey:t,publicKey:r}=pr.generateKeyPairSync("rsa",{modulusLength:e});return{privateKey:t,publicKey:r}}function Uy(e){let t=e.export({type:"spki",format:"der"});return pr.createHash("sha1").update(t).digest()}function Pu(e){let t={serialNumber:e.serialNumber||Sa(),notBefore:e.notBefore,notAfter:e.notAfter,subject:e.subject,issuer:e.issuer||e.subject,publicKey:e.publicKey,extensions:{basicConstraints:{isCA:e.isCA??!1,critical:!0,pathLenConstraint:e.pathLenConstraint},subjectKeyIdentifier:Uy(e.publicKey)}};if(e.keyUsage)t.extensions.keyUsage={...e.keyUsage,critical:!0};if(e.extendedKeyUsage)t.extensions.extendedKeyUsage=e.extendedKeyUsage;if(e.subjectAltName?.length)t.extensions.subjectAltName=e.subjectAltName;let r=Iy(t),i=_y(r,e.signingKey);return{certificate:jy(i,"CERTIFICATE"),certificateDer:i}}function Au(e){return e.export({type:"pkcs8",format:"pem"})}function Ky(e){return pr.createPrivateKey(e)}function Wy(e){let t=new pr.X509Certificate(e),r=t.publicKey,i=[],n=t.subject.split(`
127
+ `);for(let s of n){let[o,...a]=s.split("="),c=a.join("=");if(o&&c)i.push({shortName:o.trim(),value:c.trim()})}return{publicKey:r,subject:i}}async function fi(e={}){v("ca","Creating new Root CA Certificate",e.verbose);let t=e.keySize||De.DEFAULT_KEY_SIZE;v("ca",`Generating ${t}-bit RSA key pair`,e.verbose);let{privateKey:r,publicKey:i}=Tu(t),n=[{shortName:"C",value:e.countryName||O.countryName},{shortName:"ST",value:e.stateName||O.stateName},{shortName:"L",value:e.localityName||O.localityName},{shortName:"O",value:e.organization||"Local Development CA"},{shortName:"OU",value:e.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:e.commonName||"Local Development Root CA"}],{notBefore:s,notAfter:o}=_n({validityYears:e.validityYears||De.DEFAULT_CA_VALIDITY_YEARS,verbose:e.verbose}),{certificate:a}=Pu({serialNumber:Sa(),notBefore:s,notAfter:o,subject:n,publicKey:i,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:a,privateKey:Au(r),notBefore:s,notAfter:o}}async function yr(e){if(v("ca","Generating new certificate",e.verbose),v("ca",`Options: ${li(e)}`,e.verbose),!e.domain&&!e.domains?.length)throw Error("Either domain or domains must be specified");if(!e.rootCA?.certificate||!e.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=Wy(e.rootCA.certificate),r=Ky(e.rootCA.privateKey);v("ca",`Generating ${De.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,e.verbose);let i=De.DEFAULT_KEY_SIZE,{privateKey:n,publicKey:s}=Tu(i),o=e.commonName||ga(e),a=e.certificateAttributes||[{shortName:"C",value:e.countryName||O.countryName},{shortName:"ST",value:e.stateName||O.stateName},{shortName:"L",value:e.localityName||O.localityName},{shortName:"O",value:e.organizationName||O.organizationName},{shortName:"CN",value:o}],{notBefore:c,notAfter:l}=_n({validityDays:e.validityDays||De.DEFAULT_VALIDITY_DAYS,verbose:e.verbose}),f=In(e),u=e.keyUsage||{digitalSignature:!0,keyEncipherment:!0},h=e.extKeyUsage||{serverAuth:!0},{certificate:d}=Pu({serialNumber:Sa(),notBefore:c,notAfter:l,subject:a,issuer:t,publicKey:s,signingKey:r,isCA:e.basicConstraints?.cA??!1,pathLenConstraint:e.basicConstraints?.pathLenConstraint,keyUsage:u,extendedKeyUsage:h,subjectAltName:f});return{certificate:d,privateKey:Au(n),notBefore:c,notAfter:l}}var wr={debian:{family:"debian",anchorDir:"/usr/local/share/ca-certificates",updateCommand:"update-ca-certificates",bundles:["/etc/ssl/certs/ca-certificates.crt"]},rhel:{family:"rhel",anchorDir:"/etc/pki/ca-trust/source/anchors",updateCommand:"update-ca-trust",bundles:["/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"]},arch:{family:"arch",anchorDir:"/etc/ca-certificates/trust-source/anchors",updateCommand:"trust extract-compat",bundles:["/etc/ca-certificates/extracted/tls-ca-bundle.pem","/etc/ssl/certs/ca-certificates.crt"]}},Vy=new Set(["debian","ubuntu","raspbian","linuxmint","pop","elementary","kali","neon","zorin","alpine"]),zy=new Set(["rhel","fedora","centos","rocky","almalinux","ol","oracle","amzn"]),Gy=new Set(["arch","archarm","manjaro","endeavouros","garuda"]);function $a(e){let t={};for(let r of e.split(`
128
+ `)){let i=r.trim();if(!i||i.startsWith("#"))continue;let n=i.indexOf("=");if(n===-1)continue;let s=i.slice(0,n).trim(),o=i.slice(n+1).trim();if(o.startsWith('"')&&o.endsWith('"')||o.startsWith("'")&&o.endsWith("'"))o=o.slice(1,-1);t[s]=o}return t}function Ea(e){let t=$a(e),r=[t.ID??"",...(t.ID_LIKE??"").split(/\s+/)].map((i)=>i.trim().toLowerCase()).filter(Boolean);for(let i of r){if(Vy.has(i))return"debian";if(zy.has(i))return"rhel";if(Gy.has(i))return"arch"}return"unknown"}function jn(e="/"){for(let t of["/etc/os-release","/usr/lib/os-release"]){let r=ur.join(e,t);if(!Qe.existsSync(r))continue;try{let i=Ea(Qe.readFileSync(r,"utf8"));if(i!=="unknown")return i}catch{}}for(let t of Object.values(wr))if(Qe.existsSync(ur.join(e,t.anchorDir)))return t.family;return"unknown"}function Un(e){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tlsx-root-ca"}.crt`}function xa(e="/"){let t=new Set;for(let r of Object.values(wr))for(let i of r.bundles){if(t.has(i))continue;t.add(i);let n=ur.join(e,i);if(Qe.existsSync(n))return n}return}function Kn(e,t="/"){let r=xa(t);if(!r)return!1;try{let i=mr(e);return ya(Qe.readFileSync(r,"utf8"),i)}catch{return!1}}function Vr(e){return`'${e.replace(/'/g,"'\\''")}'`}function Ru(e){return{root:e.root??"/",exec:e.exec??((t)=>Te(t)),isRoot:e.isRoot??Hy.getuid?.()===0}}function qy(e){try{return gr(e)||O.commonName}catch{return O.commonName}}async function Ta(e,t={}){let{root:r,exec:i,isRoot:n}=Ru(t),s=jn(r),o=[];if(v(b.TRUST,`Linux distro family: ${s} (root=${r}, isRoot=${n})`,t.verbose),s==="unknown")return{family:s,commands:o,status:"unsupported",error:"could not detect a supported distro family from /etc/os-release (debian, rhel or arch)"};let a=wr[s],c=ur.join(r,a.anchorDir),l=ur.join(c,Un(t.name??qy(e))),f={family:s,anchorPath:l,updateCommand:a.updateCommand,commands:o};if(Kn(e,r))return v(b.TRUST,"CA already present in the system bundle, not rerunning the update",t.verbose),{...f,status:"already-trusted"};try{if(n)Qe.mkdirSync(c,{recursive:!0}),Qe.copyFileSync(e,l),Qe.chmodSync(l,420),o.push(a.updateCommand),v(b.TRUST,`Wrote ${l}; running ${a.updateCommand}`,t.verbose),await i(a.updateCommand);else{let u=[`sudo mkdir -p ${Vr(c)}`,`sudo cp ${Vr(e)} ${Vr(l)}`,`sudo chmod 644 ${Vr(l)}`,`sudo ${a.updateCommand}`].join(" && ");o.push(u),v(b.TRUST,`Running: ${u}`,t.verbose),await i(u)}return{...f,status:"installed"}}catch(u){return v(b.TRUST,`System trust store install failed: ${u}`,t.verbose),{...f,status:"failed",error:u instanceof Error?u.message:String(u)}}}async function Pa(e,t={}){let{root:r,exec:i,isRoot:n}=Ru(t),s=jn(r),o=[];if(s==="unknown")return{family:s,commands:o,status:"unsupported",error:"could not detect a supported distro family"};let a=wr[s],c=ur.join(r,a.anchorDir,Un(e)),l={family:s,anchorPath:c,updateCommand:a.updateCommand,commands:o};if(!Qe.existsSync(c))return{...l,status:"not-found"};try{if(n)Qe.unlinkSync(c),o.push(a.updateCommand),await i(a.updateCommand);else{let f=`sudo rm -f ${Vr(c)} && sudo ${a.updateCommand}`;o.push(f),await i(f)}return{...l,status:"removed"}}catch(f){return{...l,status:"failed",error:f instanceof Error?f.message:String(f)}}}function Aa(e,t){v(b.STORAGE,`Storing certificate and private key with options: ${li(t)}`,t?.verbose);let{certPath:r,keyPath:i}=dr({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});v(b.STORAGE,`Certificate path: ${r}`,t?.verbose),v(b.STORAGE,`Private key path: ${i}`,t?.verbose);let n=jo.dirname(r);if(!ut.existsSync(n))v(b.STORAGE,`Creating certificate directory: ${n}`,t?.verbose),ut.mkdirSync(n,{recursive:!0});v(b.STORAGE,"Writing certificate file",t?.verbose),ut.writeFileSync(r,e.certificate);let s=jo.dirname(i);if(!ut.existsSync(s))v(b.STORAGE,`Creating private key directory: ${s}`,t?.verbose),ut.mkdirSync(s,{recursive:!0});return v(b.STORAGE,"Writing private key file",t?.verbose),ut.writeFileSync(i,e.privateKey),v(b.STORAGE,"Certificate and private key stored successfully",t?.verbose),r}function Wn(e,t){v(b.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:r}=dr({basePath:t?.basePath,caCertPath:t?.caCertPath});v(b.STORAGE,`CA certificate path: ${r}`,t?.verbose);let i=jo.dirname(r);if(!ut.existsSync(i))v(b.STORAGE,`Creating CA certificate directory: ${i}`,t?.verbose),ut.mkdirSync(i,{recursive:!0});return v(b.STORAGE,"Writing CA certificate file",t?.verbose),ut.writeFileSync(r,e),v(b.STORAGE,"CA certificate stored successfully",t?.verbose),r}function hr(e,t){return{platform:e,stores:t,trusted:t.some((r)=>r.status==="installed"||r.status==="already-trusted")}}async function Ra(e,t,r){let i=et.platform();if(i==="linux"){let n=Kn(e,r?.root);return v(b.TRUST,n?"Certificate found in the system CA bundle":"Certificate not in the system CA bundle",t),n}if(i!=="darwin")return!1;try{let n=mr(e);if(!n)return v(b.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(Yy("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
129
+ `).some((s)=>{let o=s.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!o&&o[1].toUpperCase()===n}))return v(b.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return v(b.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(n){return v(b.TRUST,`Error checking certificate trust: ${n}`,t),!1}}async function ku(e,t){return Ra(e,t?.verbose,t?.linux)}var zr="/Library/Keychains/System.keychain",Jy={platform:"darwin",async addCertificate(e,t){if(await Ra(e,t?.verbose))return v(b.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),z.success("Certificate is already trusted in system keychain"),hr("darwin",[{store:"macos-keychain",location:zr,status:"already-trusted"}]);return v(b.TRUST,"Adding certificate to macOS keychain",t?.verbose),await Te(`sudo security add-trusted-cert -d -r trustRoot -k ${zr} ${e}`),hr("darwin",[{store:"macos-keychain",location:zr,status:"installed"}])},async removeCertificate(e,t,r){let i=r||O.commonName;v(b.TRUST,`Removing certificate ${i} from macOS keychain`,t?.verbose);try{await Te(`sudo security delete-certificate -c "${i}" ${zr}`),v(b.TRUST,`Removed certificate ${i} from macOS keychain`,t?.verbose)}catch(n){throw v(b.TRUST,`Error removing certificate: ${n}`,t?.verbose),n}}},Xy={platform:"win32",async addCertificate(e,t){return v(b.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await Te(`certutil -f -v -addstore -enterprise Root ${e}`),hr("win32",[{store:"windows-root",location:"LocalMachine\\Root",status:"installed"}])},async removeCertificate(e,t,r){let i=r||O.commonName;v(b.TRUST,`Removing certificate ${i} from Windows certificate store`,t?.verbose);try{await Te(`certutil -delstore -enterprise Root "${i}"`),v(b.TRUST,`Removed certificate ${i} from Windows certificate store`,t?.verbose)}catch(n){throw v(b.TRUST,`Error removing certificate: ${n}`,t?.verbose),n}}},Zy={platform:"linux",async addCertificate(e,t){let r=t?.verbose,i=[];v(b.TRUST,"Adding certificate to the Linux system trust store",r);let n=await Ta(e,{...t?.linux,verbose:r}),s=n.anchorPath??"(no supported anchor directory)";if(n.status==="installed")z.success(`Root CA installed into the ${n.family} system trust store (${n.anchorPath})`),i.push({store:"linux-system",location:s,status:"installed"});else if(n.status==="already-trusted")z.success("Root CA is already in the system CA bundle"),i.push({store:"linux-system",location:s,status:"already-trusted"});else if(n.status==="failed")z.warn(`Could not update the ${n.family} system trust store: ${n.error}`),i.push({store:"linux-system",location:s,status:"failed",detail:n.error});else v(b.TRUST,`System trust store skipped: ${n.error}`,r),i.push({store:"linux-system",location:s,status:"skipped",detail:n.error});let o=n.status==="installed"||n.status==="already-trusted",a=et.homedir(),c=De.LINUX_CERT_DB_FILENAME,l=De.LINUX_TRUST_ARGS;v(b.TRUST,`Searching for certificate databases in ${a}`,r);let f=ti(a,c);if(f.length===0){if(o)v(b.TRUST,"No NSS certificate databases found; the system store covers this host",r);else z.warn("No certificate databases found and the system trust store was not updated. Certificate may not be trusted by the system.");return hr("linux",i)}for(let u of f){v(b.TRUST,`Processing certificate database in ${u}`,r);try{v(b.TRUST,`Attempting to delete existing cert for ${O.commonName}`,r),await Te(`certutil -d sql:${u} -D -n ${O.commonName}`)}catch(h){v(b.TRUST,`Warning: Error deleting existing cert: ${h}`,r),console.warn(`Error deleting existing cert: ${h}`)}v(b.TRUST,`Adding new certificate to ${u}`,r);try{await Te(`certutil -d sql:${u} -A -t ${l} -n ${O.commonName} -i ${e}`),z.info(`Cert added to ${u}`),i.push({store:"linux-nss",location:u,status:"installed"})}catch(h){if(!o)throw h;v(b.TRUST,`certutil failed for ${u}: ${h}`,r),i.push({store:"linux-nss",location:u,status:"failed",detail:h instanceof Error?h.message:String(h)})}}return hr("linux",i)},async removeCertificate(e,t,r){let i=r||O.commonName;v(b.TRUST,`Removing certificate ${i} from Linux certificate store`,t?.verbose);let n=await Pa(i,{...t?.linux,verbose:t?.verbose});if(n.status==="removed")z.info(`Removed ${n.anchorPath} from the ${n.family} system trust store`);else if(n.status==="failed")z.warn(`Could not remove the CA from the system trust store: ${n.error}`);else v(b.TRUST,`System trust store removal: ${n.status}`,t?.verbose);let s=et.homedir(),o=De.LINUX_CERT_DB_FILENAME;v(b.TRUST,`Searching for certificate databases in ${s}`,t?.verbose);let a=ti(s,o);if(a.length===0){z.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of a){v(b.TRUST,`Processing certificate database in ${c}`,t?.verbose);try{await Te(`certutil -d sql:${c} -D -n "${i}"`),z.info(`Cert removed from ${c}`)}catch(l){v(b.TRUST,`Error removing cert from ${c}: ${l}`,t?.verbose),console.warn(`Error removing cert from ${c}: ${l}`)}}}},vr={darwin:Jy,win32:Xy,linux:Zy};async function Hn(e,t,r){v(b.TRUST,`Adding certificate to system trust store with options: ${li(r)}`,r?.verbose),v(b.TRUST,"Storing certificate and private key",r?.verbose);let i=Aa(e,r);v(b.TRUST,"Storing CA certificate",r?.verbose);let n=Wn(t,r),s=et.platform();v(b.TRUST,`Detected platform: ${s}`,r?.verbose);let o=vr[s];if(!o){let a=`Unsupported platform: ${s}`;throw v(b.TRUST,`Error: ${a}`,r?.verbose),Error(a)}return await o.addCertificate(n,r),v(b.TRUST,"Certificate successfully added to system trust store",r?.verbose),i}async function Nu(e,t){let r=et.platform();v(b.TRUST,`Adding ${e} to the ${r} trust store`,t?.verbose);let i=vr[r];if(!i)throw Error(`Unsupported platform: ${r}`);return i.addCertificate(e,t)}async function Du(e,t,r){v(b.TRUST,`Removing certificate for ${e} from system trust store`,t?.verbose);let i=t?.caCertPath||O.caCertPath,n=r||O.commonName,s=et.platform();v(b.TRUST,`Detected platform: ${s}`,t?.verbose);let o=vr[s];if(!o){let a=`Unsupported platform: ${s}`;throw v(b.TRUST,`Error: ${a}`,t?.verbose),Error(a)}if(!o.removeCertificate)throw Error(`Removing certificates is not supported on ${s}`);await o.removeCertificate(i,t,n),v(b.TRUST,`Certificate for ${e} successfully removed from system trust store`,t?.verbose)}async function Ou(e,t){let r=e?.verbose||O.verbose;v(b.TRUST,"Cleaning up all TLSX certificates from system trust store",r);let i=et.platform();v(b.TRUST,`Detected platform: ${i}`,r);let n=vr[i];if(!n){let s=`Unsupported platform: ${i}`;throw v(b.TRUST,`Error: ${s}`,r),Error(s)}if(!n.removeCertificate)throw Error(`Removing certificates is not supported on ${i}`);try{if(i==="darwin"){v(b.TRUST,"Removing all TLSX certificates from macOS keychain",r);let s=t||O.commonName;await Te(`sudo security find-certificate -a -c "${s}" -Z /Library/Keychains/System.keychain | grep SHA-1 | awk '{print $3}' | xargs -I {} sudo security delete-certificate -Z {} /Library/Keychains/System.keychain`),z.success(`All certificates matching "${s}" removed from macOS keychain`)}else if(i==="win32"){v(b.TRUST,"Removing all TLSX certificates from Windows certificate store",r);let s=t||O.organizationName;await Te(`certutil -delstore -enterprise Root "${s}"`),z.success(`All certificates matching "${s}" removed from Windows certificate store`)}else if(i==="linux"){v(b.TRUST,"Removing all TLSX certificates from Linux certificate stores",r);let s=et.homedir(),o=De.LINUX_CERT_DB_FILENAME;v(b.TRUST,`Searching for certificate databases in ${s}`,r);let a=ti(s,o);if(a.length===0){z.warn("No certificate databases found. Cannot clean up certificates.");return}for(let c of a){v(b.TRUST,`Processing certificate database in ${c}`,r);try{let{stdout:l}=await Te(`certutil -d sql:${c} -L`),f=l.split(`
130
+ `);for(let u of f)if(t?u.toLowerCase().includes(t.toLowerCase()):u.includes(O.organizationName)||u.includes("tlsx")||u.includes("Local Development")){let h=u.split(/\s+/)[0].trim();if(h){v(b.TRUST,`Removing certificate: ${h}`,r);try{await Te(`certutil -d sql:${c} -D -n "${h}"`),z.info(`Removed certificate ${h} from ${c}`)}catch(d){v(b.TRUST,`Error removing cert ${h}: ${d}`,r)}}}}catch(l){v(b.TRUST,`Error processing database ${c}: ${l}`,r),console.warn(`Error processing database ${c}: ${l}`)}}z.success("All matching certificates removed from Linux certificate stores")}v(b.TRUST,"Trust store cleanup completed successfully",r)}catch(s){throw v(b.TRUST,`Error cleaning up trust store: ${s}`,r),Error(`Failed to clean up trust store: ${s}`)}}async function Vn(e){let t=e?.verbose??O.verbose,{caCertPath:r,basePath:i}=dr({basePath:e?.basePath,caCertPath:e?.caCertPath}),n=r.replace(/\.crt$/,".key");v(b.TRUST,`installCA: caCertPath=${r}`,t),v(b.TRUST,`installCA: basePath=${i}`,t);let s=!1;if(!(cr.existsSync(r)&&cr.existsSync(n))){v(b.TRUST,"No existing Root CA found, generating one",t);let l=await fi({...e?.ca,verbose:t});Wn(l.certificate,{...e,basePath:i,caCertPath:r}),cr.writeFileSync(n,l.privateKey,{mode:384}),s=!0,z.success(`Generated new Root CA at ${r}`)}else v(b.TRUST,"Reusing existing Root CA on disk",t),z.info(`Using existing Root CA at ${r}`);let o=et.platform(),a=vr[o];if(!a)throw Error(`installCA: unsupported platform: ${o}`);if(await Ra(r,t,e?.linux)){z.success("Root CA is already trusted in the system store");let l=hr(o,[{store:o==="linux"?"linux-system":"macos-keychain",location:o==="linux"?"system CA bundle":zr,status:"already-trusted"}]);return{caCertPath:r,caKeyPath:n,generated:s,trustInstalled:!1,alreadyTrusted:!0,report:l}}let c=await a.addCertificate(r,e);if(c.trusted)z.success("Root CA installed in the system trust store");else z.warn("Root CA was not installed into any trust store; see the report for details");return{caCertPath:r,caKeyPath:n,generated:s,trustInstalled:c.trusted,alreadyTrusted:!1,report:c}}async function Fu(e){let t=e?.verbose??O.verbose,{caCertPath:r}=dr({basePath:e?.basePath,caCertPath:e?.caCertPath}),i=r.replace(/\.crt$/,".key"),n=e?.certName;if(!n&&cr.existsSync(r))try{n=gr(r)||void 0,v(b.TRUST,`uninstallCA: extracted CN from cert: ${n}`,t)}catch(l){v(b.TRUST,`uninstallCA: CN extraction failed: ${l}`,t)}n=n??O.commonName;let s=et.platform(),o=vr[s];if(!o?.removeCertificate)throw Error(`uninstallCA: removing certificates is not supported on ${s}`);let a=!1;try{await o.removeCertificate(r,e,n),a=!0,z.success(`Root CA "${n}" removed from the system trust store`)}catch(l){v(b.TRUST,`uninstallCA: handler.removeCertificate failed: ${l}`,t),z.warn(`Could not remove Root CA from trust store: ${l.message}`)}let c=!1;if(e?.deleteFiles){for(let l of[r,i])try{if(cr.existsSync(l))cr.unlinkSync(l),v(b.TRUST,`uninstallCA: deleted ${l}`,t),c=!0}catch(f){v(b.TRUST,`uninstallCA: failed to delete ${l}: ${f}`,t)}if(c)z.success("Removed CA cert + key from disk")}return{removedFromTrustStore:a,filesDeleted:c,caCertPath:r,caKeyPath:i}}import{homedir as wc}from"node:os";import{join as vc,resolve as rT}from"node:path";import{existsSync as Lu,statSync as Mu}from"fs";import{existsSync as ew,mkdirSync as p0,readdirSync as y0,readFileSync as tw,writeFileSync as w0}from"fs";import{homedir as br}from"os";import{dirname as C0,resolve as _e}from"path";import xs from"process";import{existsSync as Bu,statSync as Iu}from"fs";import{existsSync as Ja,mkdirSync as rw,readdirSync as iw,writeFileSync as nw}from"fs";import{homedir as Cr}from"os";import{dirname as _u,resolve as Se}from"path";import Kt from"process";import{join as sw,relative as ow,resolve as ju}from"path";import hs from"process";import{existsSync as $h,mkdirSync as N0,readdirSync as D0,writeFileSync as O0}from"fs";import{homedir as Na}from"os";import{dirname as M0,resolve as Ce}from"path";import hi from"process";import{join as aw,relative as cw,resolve as Uu}from"path";import ds from"process";import{existsSync as Eh,mkdirSync as U0,readdirSync as K0,writeFileSync as W0}from"fs";import{dirname as V0,resolve as ms}from"path";import Xa from"process";import{Buffer as kt}from"buffer";import{createCipheriv as lw,createDecipheriv as fw,randomBytes as Da}from"crypto";import{closeSync as Oa,createReadStream as Ku,createWriteStream as uw,existsSync as Fa,fsyncSync as Wu,openSync as Hu,writeFileSync as hw}from"fs";import{access as dw,constants as Vu,mkdir as mw,readdir as zn,rename as zu,stat as Sr,unlink as Gn,writeFile as La}from"fs/promises";import{join as $r}from"path";import me from"process";import{pipeline as gw}from"stream/promises";import{createGzip as Gu}from"zlib";import Er from"process";import wt from"process";import{Buffer as gt}from"buffer";import{createCipheriv as pw,createDecipheriv as yw,randomBytes as Ma}from"crypto";import{closeSync as Ba,createReadStream as qu,createWriteStream as ww,existsSync as qn,fsyncSync as Yu,openSync as Ju,writeFileSync as vw}from"fs";import{access as bw,constants as Xu,mkdir as Cw,readdir as Yn,rename as Zu,stat as xr,unlink as Jn,writeFile as Ia}from"fs/promises";import{isAbsolute as Sw,join as Tr,resolve as $w}from"path";import F from"process";import{pipeline as Ew}from"stream/promises";import{createGzip as Qu}from"zlib";import Pr from"process";import vt from"process";import Xn from"process";import{existsSync as Zn}from"fs";import{resolve as _a}from"path";import{existsSync as xw}from"fs";import{existsSync as Tw,readdirSync as Pw}from"fs";import{extname as ja,resolve as eh}from"path";import Aw from"process";import{join as Rw,relative as kw,resolve as th}from"path";import gs from"process";import{Buffer as pt}from"buffer";import{createCipheriv as Nw,createDecipheriv as Dw,randomBytes as Ua}from"crypto";import{closeSync as Ka,createReadStream as rh,createWriteStream as Ow,existsSync as Qn,fsyncSync as ih,openSync as nh,writeFileSync as Fw}from"fs";import{access as Lw,constants as sh,mkdir as Mw,readdir as es,rename as oh,stat as Ar,unlink as ts,writeFile as Wa}from"fs/promises";import{isAbsolute as Bw,join as Rr,resolve as Iw}from"path";import L from"process";import{pipeline as _w}from"stream/promises";import{createGzip as ah}from"zlib";import kr from"process";import bt from"process";import is from"process";import{existsSync as ns}from"fs";import{resolve as Ya}from"path";import{existsSync as sb}from"fs";class Ch{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Lu(e))return!0;return Mu(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=Lu(r)?Mu(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.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 e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class Sh{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}var us=new Ch,cc=new Sh;var jw=Object.defineProperty,Uw=(e)=>e;function Kw(e,t){this[e]=Uw.bind(null,t)}var Ww=(e,t)=>{for(var r in t)jw(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Kw.bind(t,r)})},Hw=(e,t)=>()=>(e&&(t=e(e=0)),t),xh={};Ww(xh,{withErrorRecovery:()=>Ah,tryLoadConfig:()=>dv,loadConfigWithResult:()=>uv,loadConfig:()=>Oh,isRetryableError:()=>sv,isConfigNotFoundError:()=>nv,isBunfigError:()=>Rh,globalPerformanceMonitor:()=>gi,globalCache:()=>Nr,getEnvOrDefault:()=>ov,generateConfigTypes:()=>mv,defaultGeneratedDir:()=>Uh,defaultConfigDir:()=>jh,deepMergeWithArrayStrategy:()=>dc,deepMerge:()=>kh,createLibraryConfig:()=>gv,config:()=>hv,bunfigPlugin:()=>pv,applyEnvVarsToConfig:()=>ui,TypeGenerationError:()=>nc,SchemaValidationError:()=>mi,PluginError:()=>oc,PerformanceMonitor:()=>fc,FileSystemError:()=>ic,ErrorFactory:()=>Nt,EnvVarError:()=>Cs,EnvProcessor:()=>Ts,ConfigValidator:()=>mc,ConfigValidationError:()=>tc,ConfigNotFoundError:()=>bs,ConfigMergeError:()=>rc,ConfigLoader:()=>gc,ConfigLoadError:()=>di,ConfigFileLoader:()=>Ps,ConfigCache:()=>lc,CacheUtils:()=>Lh,BunfigError:()=>Le,BrowserConfigError:()=>sc,ArrayMergeStrategies:()=>Ih});class lc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,i])=>r.timestamp.getTime()-i.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,i){if(!this.options.enabled)return;let n=this.generateKey(e,r),s=i??this.options.ttl,o=this.estimateSize(t);this.cache.set(n,{value:t,timestamp:new Date,ttl:s,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),i=this.cache.get(r);if(!i){this.totalMisses++;return}if(this.isExpired(i)){this.cache.delete(r),this.totalMisses++;return}return i.hits++,this.totalHits++,i.value}isFileModified(e,t){try{if(!Bu(e))return!0;return Iu(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,i){try{let n=Bu(r)?Iu(r):null,s=n?n.mtime:new Date;this.set(e,{value:t,fileTimestamp:s},r,i)}catch{this.set(e,t,r,i)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((i,n)=>i+n.size,0),r=e.map((i)=>i.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 e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let i=r;this.cache.set(t,{value:i.value,timestamp:new Date(i.timestamp),ttl:i.ttl,hits:i.hits,size:i.size})}}}class fc{metrics=[];maxMetrics=1000;async track(e,t,r={}){let i=performance.now(),n=new Date;try{let s=await t(),o=performance.now()-i;return this.recordMetric({operation:e,duration:o,timestamp:n,...r}),s}catch(s){let o=performance.now()-i;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:n,...r}),s}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((n)=>n.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((n)=>n.duration),i=r.reduce((n,s)=>n+s,0);return{count:t.length,averageDuration:i/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:i,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Vw(e,t={}){let i=Object.keys(t).sort().map((n)=>`${n}:${t[n]}`).join("|");return i?`${e}:${i}`:e}function zw(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Gw(e){return e.getStats().size*2}function uc(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&Y(t[0])&&"id"in t[0]&&t[0].id===3&&Y(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(Y(t)&&Y(e)&&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 e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(Y(e)&&"arr"in e&&Array.isArray(e.arr)&&Y(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&Y(t[0])&&Y(e[0])){let i=[...t];for(let n of e)if(Y(n)&&"name"in n){if(!i.find((o)=>Y(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(Y(n)&&"path"in n){if(!i.find((o)=>Y(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>ps(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!Y(t)||!Y(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(Y(n)&&Y(r[i]))r[i]=uc(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&Y(n[0])&&Y(r[i][0])){let s=[...n];for(let o of r[i])if(Y(o)&&"name"in o){if(!s.find((c)=>Y(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(Y(o)&&"path"in o){if(!s.find((c)=>Y(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((a)=>ps(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function ps(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ps(e[r],t[r]))return!1;return!0}if(Y(e)&&Y(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ps(e[n],t[n]))return!1}return!0}return!1}function Y(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function qw(e,t){if(!Eh(e))return null;try{let r=await import(e),i=r.default||r;if(typeof i!=="object"||i===null||Array.isArray(i))return null;try{return uc(t,i)}catch{return null}}catch{return null}}async function Yw({name:e="",cwd:t,defaultConfig:r}){let i=t||Xa.cwd(),n=[".ts",".js",".mjs",".cjs",".json"],s=[`${e}.config`,`.${e}.config`,e,`.${e}`];for(let o of s)for(let a of n){let c=ms(i,`${o}${a}`),l=await qw(c,r);if(l!==null)return l}try{let o=ms(i,"package.json");if(Eh(o)){let c=(await import(o))[e];if(c&&typeof c==="object"&&!Array.isArray(c))try{return uc(r,c)}catch{}}}catch{}return r}function Jw(e,t={}){let r=ds.cwd();while(r.includes("storage"))r=Uu(r,"..");let i=Uu(r,e||"");if(t?.relative)return cw(ds.cwd(),i);return i}async function Xw(){try{let e=await Yw({name:"clarity",defaultConfig:as,cwd:ds.cwd(),endpoint:"",headers:{}});return{...as,...e}}catch{return as}}function Q(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Zw(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof wt<"u"){let e=wt.type;if(e==="renderer"||e==="worker")return!1;return!!(wt.versions&&(wt.versions.node||wt.versions.bun))}return!1}class Th{async format(e){let t=await Zw(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Er.pid,hostname:t(),environment:Er.env.NODE_ENV||"development",platform:Er.platform,version:Er.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Er.env.NODE_ENV||Er.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ys{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(e,t={}){this.name=e,this.config={...Qa},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Th,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??me.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...cs,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...cs};return{...cs,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Qa.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,a=1000;while(s<o)try{try{try{await dw(this.config.logDirectory,Vu.F_OK|Vu.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await mw(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:kt.from(e);try{if(!Fa(this.currentLogFile))await La(this.currentLogFile,"",{mode:420});if(n=Hu(this.currentLogFile,"a",420),hw(n,c,{flag:"a"}),Wu(n),n!==void 0)Oa(n),n=void 0;if((await Sr(this.currentLogFile)).size===0){if(await La(this.currentLogFile,c,{flag:"w",mode:420}),(await Sr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=a*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{Oa(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(s===o-1){let f=c,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}s++;let l=a*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 $r(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 $r(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return $r(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(Q())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.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,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,c])=>c.createdAt.getTime()-a.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[a]of n.slice(o))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return Da(16).toString("hex")}generateKey(){return Da(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Da(16),i=lw("aes-256-gcm",t,r),n=kt.concat([i.update(e,"utf8"),i.final()]),s=i.getAuthTag();return{encrypted:kt.concat([r,n,s]),iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Gu(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(kt.from(kt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(Q())return;let e=await Sr(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await zn(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Sr(r).catch(()=>null))try{if(await zu(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Gn(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await La(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Sr(r).catch(()=>null))await zu(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await zn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,a)=>a.localeCompare(o));for(let o of s.slice(t.maxFiles))await Gn($r(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=Ku(e),i=uw(t),n=Gu();await gw(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);await this.writeToFile(i),console.log(i)}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:e,message:t,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(e)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(e){return{debug:0,info:1,success:2,warning:3,error:4}[e]}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Fa(this.currentLogFile))try{let e=Hu(this.currentLogFile,"r+");Wu(e),Oa(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!Q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await zn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Gn($r(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.fancy?G.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=me.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${G.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);if(this.fancy&&!Q()){let l=Mh[e],f=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",u;switch(e){case"debug":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:G.gray(o),level:e}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:G.green(o),level:e}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:n,icon:l,tag:f,message:o,level:e}),console.error(u),a){let h=a.split(`
131
+ `);for(let d of h)if(d.trim()&&!d.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:G.gray(` ${d}`),level:e,showTimestamp:!1}))}break}}else if(!Q()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let c=`${s} ${this.environment}.${e.toUpperCase()}: ${o}
132
+ `;if(a)c+=`${a}
133
+ `;c=c.replace(this.ANSI_PATTERN,""),await this.writeToFile(c)}time(e){let t=performance.now();if(this.fancy&&!Q()){let r=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:G.blue("◐"),tag:r,message:`${G.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
134
+ `,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!Q()){let f=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:G.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Q())console.error(l.trim());await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new ys(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(!Fa(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ku(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){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 i=kt.isBuffer(e)?e:kt.from(e,"base64"),n=i.slice(0,16),s=i.slice(-16),o=i.slice(16,-16),a=fw("aes-256-gcm",r,n);return a.setAuthTag(s),kt.concat([a.update(o),a.final()]).toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}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(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t);if(this.fancy&&!Q()){let s=e.split(`
135
+ `),o=Math.max(...s.map((f)=>f.length))+2,a=`┌${"─".repeat(o)}┐`,c=`└${"─".repeat(o)}┘`,l=s.map((f)=>{let u=" ".repeat(o-f.length-2);return`│ ${f}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:G.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(a)})),l.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:G.cyan(c),showTimestamp:!1}))}else if(!Q())console.error(`${i} ${this.environment}.INFO: [BOX] ${e}`);let n=`${i} ${this.environment}.INFO: [BOX] ${e}
136
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}async prompt(e){if(Q())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${G.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();me.stdin.removeListener("data",r);try{if(typeof me.stdin.setRawMode==="function")me.stdin.setRawMode(!1)}catch{}me.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof me.stdin.setRawMode==="function")me.stdin.setRawMode(!0)}catch{}me.stdin.resume(),me.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let o=/%([sdijfo%])/g,a=0;if(r=e.replace(o,(c,l)=>{if(l==="%")return"%";if(a>=t.length)return c;let f=t[a++];switch(l){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return c}}),a<t.length)r+=` ${t.slice(a).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!Q()){let o=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",a=G.blue("◐");console.error(`${a} ${o} ${G.cyan(r)}`)}let s=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
137
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(s)}progress(e,t=""){if(!this.enabled||!this.fancy||Q()||e<=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:e,current:0,message:t,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(o,a)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(e,o)),a!==void 0)this.activeProgressBar.message=a;let c=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,c)},finish:(o)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;if(this.activeProgressBar.current=this.activeProgressBar.total,o!==void 0)this.activeProgressBar.message=o;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(o,a="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;me.stdout.write(`${"\r".padEnd(me.stdout.columns||80)}\r`),this.log(a,o),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(e,t=!1){if(!this.enabled||!this.fancy||Q()||!me.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=G.green("━".repeat(i)),o=G.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=t||r===100?G.green("✓"):G.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=me.stdout.columns||80,p=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${p}`,me.stdout.write(e.lastRenderedLine),t)me.stdout.write(`
138
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||Q()||!me.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(Q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await zn(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=$r(this.config.logDirectory,i);if(e.before)try{if((await Sr(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}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 i of r)try{await Gn(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function os(e,t){if(Array.isArray(t)&&Array.isArray(e)&&t.length===2&&e.length===2&&H(t[0])&&"id"in t[0]&&t[0].id===3&&H(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(H(t)&&H(e)&&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 e;if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(t)&&Array.isArray(e)){if(H(e)&&"arr"in e&&Array.isArray(e.arr)&&H(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&e.length>0&&H(t[0])&&H(e[0])){let i=[...t];for(let n of e)if(H(n)&&"name"in n){if(!i.find((o)=>H(o)&&("name"in o)&&o.name===n.name))i.push(n)}else if(H(n)&&"path"in n){if(!i.find((o)=>H(o)&&("path"in o)&&o.path===n.path))i.push(n)}else if(!i.some((s)=>ws(s,n)))i.push(n);return i}if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}if(!H(t)||!H(e))return t;let r={...e};for(let i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let n=t[i];if(n===null||n===void 0)continue;else if(H(n)&&H(r[i]))r[i]=os(r[i],n);else if(Array.isArray(n)&&Array.isArray(r[i]))if(n.length>0&&r[i].length>0&&H(n[0])&&H(r[i][0])){let s=[...n];for(let o of r[i])if(H(o)&&"name"in o){if(!s.find((c)=>H(c)&&("name"in c)&&c.name===o.name))s.push(o)}else if(H(o)&&"path"in o){if(!s.find((c)=>H(c)&&("path"in c)&&c.path===o.path))s.push(o)}else if(!s.some((a)=>ws(a,o)))s.push(o);r[i]=s}else if(n.every((s)=>typeof s==="string")&&r[i].every((s)=>typeof s==="string")){let s=[...n];for(let o of r[i])if(!s.includes(o))s.push(o);r[i]=s}else r[i]=n;else r[i]=n}return r}function hc(e,t,r="replace"){if(t===null||t===void 0)return e;if(Array.isArray(t))return r==="replace"?t:os(e,t);if(Array.isArray(e))return r==="replace"?t:os(e,t);if(!H(t)||!H(e))return t;let i={...e};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n],o=i[n];if(s===null||s===void 0)continue;if(Array.isArray(s)||Array.isArray(o))if(r==="replace")i[n]=s;else i[n]=os(o,s);else if(H(s)&&H(o))i[n]=hc(o,s,r);else i[n]=s}return i}function ws(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ws(e[r],t[r]))return!1;return!0}if(H(e)&&H(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ws(e[n],t[n]))return!1}return!0}return!1}function H(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}async function rs(e,t,r="replace"){if(!$h(e))return null;try{let i=await import(e),n=i.default||i;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return hc(t,n,r)}catch{return null}}catch{return null}}function Qw(e,t,r=!1){if(!e)return t;let i=e.toUpperCase().replace(/-/g,"_"),n={...t};function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=(g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase(),d=`${i}_${u.map(h).join("_")}`,p=`${i}_${u.map((g)=>g.toUpperCase()).join("_")}`;if(r)pe.info(`Checking environment variable ${d} for config ${e}.${u.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))c[l]=s(f,u);else{let g=hi.env[d]||hi.env[p];if(g!==void 0){if(r)pe.info(`Using environment variable ${g?d:p} for config ${e}.${u.join(".")}`);if(typeof f==="number")c[l]=Number(g);else if(typeof f==="boolean")c[l]=g.toLowerCase()==="true";else if(Array.isArray(f))try{let y=JSON.parse(g);if(Array.isArray(y))c[l]=y;else c[l]=g.split(",").map((w)=>w.trim())}catch{c[l]=g.split(",").map((y)=>y.trim())}else c[l]=g}}}return c}return s(n)}async function ev({name:e="",alias:t,cwd:r,configDir:i,defaultConfig:n,verbose:s=!1,checkEnv:o=!0,arrayStrategy:a="replace"}){let c=o&&typeof n==="object"&&n!==null&&!Array.isArray(n)?Qw(e,n,s):n,l=r||hi.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(s)pe.info(`Loading configuration for "${e}"${t?` (alias: "${t}")`:""} from ${l}`);let u=[e,`.${e}`].filter(Boolean),h=[`${e}.config`,`.${e}.config`].filter(Boolean),d=t?[t,`.${t}`]:[],p=t?[`${t}.config`,`.${t}.config`]:[],g=Array.from(new Set([l,Ce(l,"config"),Ce(l,".config"),i?Ce(l,i):void 0].filter(Boolean)));for(let y of g){if(s)pe.info(`Searching for configuration in: ${y}`);let C=[Ce(l,"config"),Ce(l,".config")].concat(i?[Ce(l,i)]:[]).includes(y)?[...u,...h,...d,...p]:[...h,...u,...p,...d];for(let A of C)for(let T of f){let P=Ce(y,`${A}${T}`),D=await rs(P,c,a);if(D!==null){if(s)pe.success(`Configuration loaded from: ${P}`);return D}}}if(e){let y=Ce(Na(),".config",e),w=["config",`${e}.config`];if(t)w.push(`${t}.config`);if(s)pe.info(`Checking user config directory: ${y}`);for(let C of w)for(let A of f){let T=Ce(y,`${C}${A}`),P=await rs(T,c,a);if(P!==null){if(s)pe.success(`Configuration loaded from user config directory: ${T}`);return P}}}if(e){let y=Ce(Na(),".config"),w=[`.${e}.config`];if(t)w.push(`.${t}.config`);if(s)pe.info(`Checking user config directory for dotfile configs: ${y}`);for(let C of w)for(let A of f){let T=Ce(y,`${C}${A}`),P=await rs(T,c,a);if(P!==null){if(s)pe.success(`Configuration loaded from user config directory dotfile: ${T}`);return P}}}if(e){let y=Na(),w=[`.${e}.config`,`.${e}`];if(t)w.push(`.${t}.config`),w.push(`.${t}`);if(s)pe.info(`Checking user home directory for dotfile configs: ${y}`);for(let C of w)for(let A of f){let T=Ce(y,`${C}${A}`),P=await rs(T,c,a);if(P!==null){if(s)pe.success(`Configuration loaded from user home directory: ${T}`);return P}}}try{let y=Ce(l,"package.json");if($h(y)){let w=await import(y),C=w[e];if(!C&&t){if(C=w[t],C&&s)pe.success(`Using alias "${t}" configuration from package.json`)}if(C&&typeof C==="object"&&!Array.isArray(C))try{if(s)pe.success(`Configuration loaded from package.json: ${C===w[e]?e:t}`);return hc(c,C,a)}catch(A){if(s)pe.warn("Failed to merge package.json config:",A)}}}catch(y){if(s)pe.warn("Failed to load package.json:",y)}if(s)pe.info(`No configuration found for "${e}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return c}function tv(e,t={}){let r=hs.cwd();while(r.includes("storage"))r=ju(r,"..");let i=ju(r,e||"");if(t?.relative)return ow(hs.cwd(),i);return i}async function rv(){try{let e=await ev({name:"clarity",alias:"logging",defaultConfig:ls,cwd:hs.cwd()});return{...ls,...e||{}}}catch{return ls}}function ne(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function iv(){if(vt.env.NODE_ENV==="test"||vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vt<"u"){let e=vt.type;if(e==="renderer"||e==="worker")return!1;return!!(vt.versions&&(vt.versions.node||vt.versions.bun))}return!1}class Ph{async format(e){let t=await iv(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:Pr.pid,hostname:t(),environment:Pr.env.NODE_ENV||"development",platform:Pr.platform,version:Pr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Pr.env.NODE_ENV||Pr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class vs{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(e,t={}){this.name=e,this.config={...ec},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ph,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??F.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...fs,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...fs};return{...fs,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:ec.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!ne()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,a=1000;while(s<o)try{try{try{await bw(this.config.logDirectory,Xu.F_OK|Xu.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Cw(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:gt.from(e);try{if(!qn(this.currentLogFile))await Ia(this.currentLogFile,"",{mode:420});if(n=Ju(this.currentLogFile,"a",420),vw(n,c,{flag:"a"}),Yu(n),n!==void 0)Ba(n),n=void 0;if((await xr(this.currentLogFile)).size===0){if(await Ia(this.currentLogFile,c,{flag:"w",mode:420}),(await xr(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=a*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{Ba(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(s===o-1){let f=c,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}s++;let l=a*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 Tr(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 Tr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Tr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(ne())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.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,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,c])=>c.createdAt.getTime()-a.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[a]of n.slice(o))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return Ma(16).toString("hex")}generateKey(){return Ma(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ma(16),i=pw("aes-256-gcm",t,r),n=gt.isBuffer(e)?e:gt.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),l=gt.allocUnsafe(16+a+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),c.copy(l,16+a),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=Qu(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(gt.from(gt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(ne())return;if(!this.shouldWriteToFile())return;let e=await xr(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await Yn(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await xr(r).catch(()=>null))try{if(await Zu(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await Jn(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Ia(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await xr(r).catch(()=>null))await Zu(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await Yn(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,a)=>a.localeCompare(o));for(let o of s.slice(t.maxFiles))await Jn(Tr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=qu(e),i=ww(t),n=Qu();await Ew(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),qn(this.currentLogFile))try{let e=Ju(this.currentLogFile,"r+");Yu(e),Ba(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!ne()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Yn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await Jn(Tr(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?B.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ne())return!1;let e=typeof F.env.NO_COLOR<"u",t=F.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof F.stderr<"u"&&F.stderr.isTTY||typeof F.stdout<"u"&&F.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=F.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${B.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=B.underline(B.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>B.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>B.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>B.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>B.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>B.strikethrough(i)),t}supportsHyperlinks(){if(ne())return!1;let e=F.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=F.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Sw(t)||t.startsWith("./")||t.startsWith("../"))t=$w(t);else return null;return qn(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Bh[e],h=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:B.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:B.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.error(d),a){let p=a.split(`
139
+ `);for(let g of p)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:B.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!ne()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}if(!this.shouldLog(e))return;let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
140
+ `;if(a)f+=`${a}
141
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(a,c)=>{},finish:(a)=>{},interrupt:(a,c)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!ne()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(a,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,a),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!ne()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(a)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,a)},interrupt:(a,c="info")=>{if(!ne()&&F.stdout.isTTY)F.stdout.write(`
142
+ `);if(this[c==="warning"?"warn":c](a),this.activeProgressBar&&this.shouldStyleConsole()&&!ne()&&F.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":B.blue("◐"),tag:r,message:`${B.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
143
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":B.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!ne())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new vs(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(ne())throw Error("createReadStream is not supported in browser environments");if(!qn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return qu(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){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 i=gt.isBuffer(e)?e:gt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=yw("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),l=a.final(),f=c.length+l.length,u=gt.allocUnsafe(f);return c.copy(u,0),l.copy(u,c.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ne()}isServerMode(){return!ne()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
144
+ `),c=Math.max(...a.map((h)=>h.length))+2,l=`┌${"─".repeat(c)}┐`,f=`└${"─".repeat(c)}┘`,u=a.map((h)=>this.formatConsoleMessage({timestamp:r,message:B.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:B.cyan(f),showTimestamp:!1}))}else if(!ne())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
145
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(ne())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${B.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();F.stdin.removeListener("data",r);try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!1)}catch{}F.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof F.stdin.setRawMode==="function")F.stdin.setRawMode(!0)}catch{}F.stdin.resume(),F.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let c=/%([sdijfo%])/g,l=0;if(r=e.replace(c,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?B.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${B.blue("◐")} `;console.error(`${l}${c} ${B.cyan(i)}`)}let a=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
146
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!F.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=B.green("━".repeat(i)),o=B.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?B.green("✓"):B.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${B.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=F.stdout.columns||80,p=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${p}`,F.stdout.write(e.lastRenderedLine),t)F.stdout.write(`
147
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||ne()||!F.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(ne()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Yn(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=Tr(this.config.logDirectory,i);if(e.before)try{if((await xr(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}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 i of r)try{await Jn(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Ah(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}function Rh(e){return e instanceof Le}function nv(e){return e instanceof bs}function sv(e){if(Rh(e))return e.code==="FILE_SYSTEM_ERROR"||e.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>e.message.toLowerCase().includes(r.toLowerCase()))}class Ts{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return gi.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((f)=>this.formatEnvKey(f,i.useCamelCase)),c=`${r}_${a.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let f=Xn.env[c]||(l?Xn.env[l]:void 0);if(f!==void 0){if(i.verbose){let u=Xn.env[c]?c:l}try{e[n]=this.parseEnvironmentValue(f,typeof s,c,i.customParsers,i.configName)}catch(u){if(u instanceof Cs)throw u;throw Nt.envVar(c,f,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Nt.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(Xn.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
148
+
149
+ `;for(let i of e)r+=`${i.key}
150
+ `,r+=` Type: ${i.type}
151
+ `,r+=` Description: ${i.description}
152
+ `,r+=` Example: ${i.example}
153
+
154
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
155
+
156
+ `;r+=`| Variable | Type | Description | Example |
157
+ `,r+=`|----------|------|-------------|----------|
158
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
159
+ `;return r}}function ov(e,t){let r=Fh("process");if(typeof r>"u"||!r.env)return t;let i=r.env[e];return i!==void 0?i:t}function kh(e,t,r={}){return Nh(e,t,r,new WeakMap)}function Nh(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Dh(e,t,n,i);if(!je(t)||!je(e))return t;return fv(e,t,r,i)}function Dh(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return av(e,t);case"smart":return cv(e,t,i);default:return t}return t}function av(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>Za(n,i)))r.push(i);return r}function cv(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(je(t[0])&&je(e[0]))return lv(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function lv(e,t,r){let i=[...t];for(let n of e){if(!je(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((l)=>je(l)&&(a in l)&&l[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function fv(e,t,r,i){let n=t;if(je(n)&&i.has(n))return i.get(n);let s={...e};if(je(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(je(a)&&je(c))s[o]=Nh(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=Dh(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function dc(e,t,r="replace"){return kh(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Za(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Za(e[r],t[r]))return!1;return!0}if(je(e)&&je(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!Za(e[n],t[n]))return!1}return!0}return!1}function je(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class Ps{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let l=Nr.getWithFileCheck("file",e);if(l){if(a)console.log(`Configuration loaded from cache: ${e}`);return l}}let c=async()=>{if(!Zn(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,d=Object.keys(f).length>0;if(!h&&!d)throw new di(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new di(e,Error("Configuration must export a valid object"),"unknown");let y={config:dc(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)Nr.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?Nt.configLoad(e,l):Nt.configLoad(e,Error(String(l)))}};if(o)return gi.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(_a(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);if(t){if(r.push(t,`.${t}.config`,`${t}.config`,`.${t}`),e)r.push(`${e}.${t}.config`,`.${e}.${t}.config`)}return r.filter(Boolean)}checkFileAccess(e){return Ah(async()=>Zn(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!Zn(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=_a(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=_a(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}looksLikeConfigFile(e){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(e))}async validateConfigFile(e){let t=[];try{if(!Zn(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}class mc{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return f.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(a)return await gi.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!xw(t))throw new mi(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new mi(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let l=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:_h},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class gc{fileLoader=new Ps;envProcessor=new Ts;validator=new mc;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let l=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(l)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let f=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),u=!f&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),h=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw c;if(u&&(!l||!h))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)Ge.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){let c=Date.now()-t;throw Ge.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||Kt.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,u,o,a,l,f,c,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,u,o)),this.finalizeResult(d,h,c,i,f);let p=await this.loadHomeConfiguration(i,n,a,l,f,c);if(p)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(p,h,c,i,f);let g=await this.loadPackageJsonConfiguration(i,n,u,a,l,f,c);if(g)return h.push(Se(u,"package.json")),this.finalizeResult(g,h,c,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,o)),t)throw Nt.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,a,c,f),warnings:[`No configuration file found for "${i}"${n?` or alias "${n}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let l=a?ui(e,n,o):n,f=this.getLocalDirectories(r,i);for(let u of f){if(o)Ge.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)Ge.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?ui(e,r,n):r,a=[Se(Cr(),".config",e),Se(Cr(),".config"),Cr()];for(let c of a){if(n)Ge.info(`Checking home directory: ${c}`);let l=this.fileLoader.generateConfigPaths(e,c,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(f){if(n)Ge.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?ui(e,i,s):i;try{let c=Se(r,"package.json");if(!Ja(c))return null;let l=await import(c),f=l[e],u=e;if(!f&&t)f=l[t],u=t;if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)Ge.success(`Configuration loaded from package.json: ${u}`);return{config:dc(a,f,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)Ge.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ui(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw Nt.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return Nr.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);Nr.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];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(e,t){return Array.from(new Set([e,Se(e,"config"),Se(e,".config"),t?Se(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(Se(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[Se(Cr(),".config",e),Se(Cr(),".config"),Cr()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}function ch(e){let r=!(e.message.includes("EACCES")||e.message.includes("EPERM")||e.message.includes("permission denied"))&&(e.message.includes("syntax")||e.message.includes("Expected")||e.message.includes("Unexpected")||e.message.includes("BuildMessage")),i=e.message.includes("Configuration must export a valid object")||e.message.includes("Configuration file is empty and exports nothing");return r||i}async function uv(e){return Ct.loadConfig({...e,__strictErrorHandling:!0})}async function Oh(e){let t="defaultConfig"in e&&e.defaultConfig!==void 0?e.defaultConfig:{},r="cache"in e||"performance"in e||"schema"in e||"validate"in e;try{let i;if(r)i=await Ct.loadConfig(e);else i=await Ct.loadConfig({...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return i?.config??t}catch(i){let n=i instanceof Error?i.name:"UnknownError",s=i instanceof Error?i.message:String(i);if(!(n==="ConfigNotFoundError"||n==="ConfigLoadError"||n==="ConfigValidationError"||s.includes("config"))&&e.verbose)Ge.warn("Unexpected error loading config, using defaults:",[i instanceof Error?i:Error(String(i))]);let a=r?{...e,defaultConfig:t}:{...e,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in e?e.checkEnv!==!1:!0)return(await Ct.applyEnvironmentVariables(a.name||"",t,!0,a.verbose||!1))?.config??t;return t}}async function hv(e={defaultConfig:{}}){if(typeof e==="string"){let{cwd:t}=await import("process");try{return(await Ct.loadConfig({name:e,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&ch(r)))return(await Ct.applyEnvironmentVariables(e,{},!0,!1)).config;throw r}}try{return(await Ct.loadConfig({...e,cwd:e.cwd||Kt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&ch(t)))return(await Ct.applyEnvironmentVariables(e.name||"",e.defaultConfig||{},e.checkEnv!==!1,e.verbose||!1)).config;throw t}}async function dv(e,t,r="replace"){let i=new Ps;try{let n=await i.loadFromPath(e,t,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return n?n.config:null}catch{return null}}function ui(e,t,r=!1){let i=new Ts,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((g)=>g.toUpperCase()).join("")}`,`${n}_${u.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,p;for(let g of h)if(d=Kt.env[g],d!==void 0){p=g;break}if(d!==void 0&&p)if(typeof f==="boolean")c[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof f==="number"){let g=Number(d);if(!Number.isNaN(g))c[l]=g}else if(Array.isArray(f))try{c[l]=JSON.parse(d)}catch{c[l]=d.split(",").map((g)=>g.trim())}else c[l]=d;else if(f&&typeof f==="object"&&!Array.isArray(f))c[l]=s(f,u)}return c}return s(t)}function mv(e){let t=Se(Kt.cwd(),e.configDir),r=Se(Kt.cwd(),e.generatedDir),i=Se(r,"config-types.ts");if(!Ja(_u(i)))rw(_u(i),{recursive:!0,mode:511});let n=Ja(t)?iw(t).map((o)=>o.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],s=`// Generated by bunfig v${Wv}
160
+ export type ConfigNames = ${n.length?`'${n.join("' | '")}'`:"string"}
161
+ `;nw(i,s,{mode:438})}function gv(e){let t=null,r=null,i=()=>{if(!r)r=Oh(e).then((s)=>(t=s,s),(s)=>{let o="defaultConfig"in e?e.defaultConfig:{};if(t=o,"verbose"in e&&e.verbose)Ge.warn("Config loading failed, using defaults:",[s instanceof Error?s:Error(String(s))]);return o});return r},n="defaultConfig"in e?e.defaultConfig:{};return t=n,i(),new Proxy({},{get(s,o){if(t)return t[o];let a=n[o];return i(),a},has(s,o){return o in(t||n)},ownKeys(){return Object.keys(t||n)},getOwnPropertyDescriptor(s,o){return Object.getOwnPropertyDescriptor(t||n,o)},set(s,o,a){if(!t)t={...n};return t[o]=a,!0}})}function pv(e){let t=eh(Aw.cwd(),e?.configDir||"./config");function r(){if(!Tw(t))return[];let n=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),s=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],o=Pw(t).filter((c)=>n.has(ja(c))).map((c)=>({base:c.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:c})),a=new Map;for(let{base:c,file:l}of o){let f=ja(l).toLowerCase(),u=a.get(c);if(!u){a.set(c,l);continue}let h=ja(u).toLowerCase();if(s.indexOf(f)<s.indexOf(h))a.set(c,l)}return Array.from(a.entries()).map(([c,l])=>({base:c,file:l})).sort((c,l)=>c.base.localeCompare(l.base))}function i(){let n=r(),s=n.map((l)=>l.base),o=s.length?s.map((l)=>`'${l}'`).join(" | "):"string",a=n.length?`{
162
+ ${n.map((l)=>{let f=eh(t,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${f}').default`}).join(`,
163
+ `)}
164
+ }`:"Record<string, any>";return`export type ConfigNames = ${o}
165
+ export type ConfigByName = ${a}
166
+ export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
167
+ export type ConfigOf = Config
168
+ `}return{name:"bunfig-plugin",setup(n){n.onResolve({filter:/^virtual:bunfig-types$/},(s)=>({path:s.path,namespace:"bunfig-virtual"})),n.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>({contents:i(),loader:"ts"}))}}}var Fh,Nr,gi,Lh,yv,wv,lh,as,Qa,ge,G,vv,fh,bv,uh,Cv,Sv,Ha,$v,hh,dh,Va,Ev,xv,Tv,Pv,cs,Mh,Av,pe,Rv,kv,mh,ls,ec,se,B,Nv,gh,Dv,ph,Ov,Fv,za,Lv,yh,wh,Mv,Ga,Bv,Iv,_v,jv,Uv,fs,Bh,Kv,Wv="0.15.6",Le,bs,di,tc,rc,Cs,ic,nc,mi,sc,oc,Nt,Ih,_h,Ge,Ct,jh,Uh,Hv=Hw(async()=>{Fh=import.meta.require,Nr=new lc,gi=new fc,Lh={createKey:Vw,isEquivalent:zw,estimateMemoryUsage:Gw},yv=ms(Xa.cwd(),"config"),wv=ms(Xa.cwd(),"src/generated"),lh=ds.env.CLARITY_LOG_DIR||aw(Jw(),"logs"),as={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:lh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Qa=await Xw(),ge={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,reset:"\x1B[0m"},G=ge,vv=ge.red,fh=ge.green,bv=ge.yellow,uh=ge.blue,Cv=ge.magenta,Sv=ge.cyan,Ha=ge.white,$v=ge.gray,hh=ge.bgRed,dh=ge.bgYellow,Va=ge.bold,Ev=ge.dim,xv=ge.italic,Tv=ge.underline,Pv=ge.reset,cs={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Mh={debug:"\uD83D\uDD0D",info:uh("ℹ"),success:fh("✓"),warning:dh(Ha(Va(" WARN "))),error:hh(Ha(Va(" ERROR ")))},Av=new ys("stacks"),pe=new ys("bunfig",{showTags:!0}),Rv=Ce(hi.cwd(),"config"),kv=Ce(hi.cwd(),"src/generated"),mh=hs.env.CLARITY_LOG_DIR||sw(tv(),"logs"),ls={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},ec=await rv(),se={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},B=se,Nv=se.red,gh=se.green,Dv=se.yellow,ph=se.blue,Ov=se.magenta,Fv=se.cyan,za=se.white,Lv=se.gray,yh=se.bgRed,wh=se.bgYellow,Mv=se.bgGray,Ga=se.bold,Bv=se.dim,Iv=se.italic,_v=se.underline,jv=se.strikethrough,Uv=se.reset,fs={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Bh={debug:"\uD83D\uDD0D",info:ph("ℹ"),success:gh("✓"),warning:wh(za(Ga(" WARN "))),error:yh(za(Ga(" ERROR ")))},Kv=new vs("stacks"),Le=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,i])=>`${r}: ${i}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},bs=class extends Le{code="CONFIG_NOT_FOUND";constructor(t,r,i){let n=i?` or alias "${i}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:i,searchPaths:r,searchPathCount:r.length})}},di=class extends Le{code="CONFIG_LOAD_ERROR";constructor(t,r,i){super(`Failed to load configuration from "${t}": ${r.message}`,{configPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}},tc=class extends Le{code="CONFIG_VALIDATION_ERROR";constructor(t,r,i){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:i,validationErrors:r,errorCount:r.length})}},rc=class extends Le{code="CONFIG_MERGE_ERROR";constructor(t,r,i,n){super(`Failed to merge configuration from "${t}" with "${r}": ${i.message}`,{sourcePath:t,targetPath:r,configName:n,originalError:i.name,originalMessage:i.message});this.cause=i}},Cs=class extends Le{code="ENV_VAR_ERROR";constructor(t,r,i,n){super(`Failed to parse environment variable "${t}" with value "${r}" as ${i}`,{envKey:t,envValue:r,expectedType:i,configName:n})}},ic=class extends Le{code="FILE_SYSTEM_ERROR";constructor(t,r,i){super(`File system ${t} failed for "${r}": ${i.message}`,{operation:t,path:r,originalError:i.name,originalMessage:i.message});this.cause=i}},nc=class extends Le{code="TYPE_GENERATION_ERROR";constructor(t,r,i){super(`Failed to generate types from "${t}" to "${r}": ${i.message}`,{configDir:t,outputPath:r,originalError:i.name,originalMessage:i.message});this.cause=i}},mi=class extends Le{code="SCHEMA_VALIDATION_ERROR";constructor(t,r,i){super(`Schema validation failed${i?` for config "${i}"`:""}`,{schemaPath:t,configName:i,validationErrors:r,errorCount:r.length})}},sc=class extends Le{code="BROWSER_CONFIG_ERROR";constructor(t,r,i,n){super(`Failed to fetch configuration from "${t}": ${r} ${i}`,{endpoint:t,status:r,statusText:i,configName:n})}},oc=class extends Le{code="PLUGIN_ERROR";constructor(t,r,i){super(`Plugin "${t}" failed during ${r}: ${i.message}`,{pluginName:t,operation:r,originalError:i.name,originalMessage:i.message});this.cause=i}},Nt={configNotFound(e,t,r){return new bs(e,t,r)},configLoad(e,t,r){return new di(e,t,r)},configValidation(e,t,r){return new tc(e,t,r)},configMerge(e,t,r,i){return new rc(e,t,r,i)},envVar(e,t,r,i){return new Cs(e,t,r,i)},fileSystem(e,t,r){return new ic(e,t,r)},typeGeneration(e,t,r){return new nc(e,t,r)},schemaValidation(e,t,r){return new mi(e,t,r)},browserConfig(e,t,r,i){return new sc(e,t,r,i)},plugin(e,t,r){return new oc(e,t,r)}},Ih={replace:"replace",concat:"concat",smart:"smart"},_h=/^https?:\/\//,Ge=new vs("bunfig",{showTags:!0}),Ct=new gc,jh=Se(Kt.cwd(),"config"),Uh=Se(Kt.cwd(),"src/generated")});function Vv(e,t={}){let r=gs.cwd();while(r.includes("storage"))r=th(r,"..");let i=th(r,e||"");if(t?.relative)return kw(gs.cwd(),i);return i}var zv=gs.env.CLARITY_LOG_DIR||Rw(Vv(),"logs"),Kh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:zv,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Ss={...Kh},Dx=(async()=>{try{let{loadConfig:e}=await Hv().then(()=>xh),t=await e({name:"clarity",alias:"logging",defaultConfig:Kh,cwd:gs.cwd()});if(t)Object.assign(Ss,t)}catch{}return Ss})();function oe(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Gv(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bt<"u"){let e=bt.type;if(e==="renderer"||e==="worker")return!1;return!!(bt.versions&&(bt.versions.node||bt.versions.bun))}return!1}class Wh{async format(e){let t=await Gv(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:kr.pid,hostname:t(),environment:kr.env.NODE_ENV||"development",platform:kr.platform,version:kr.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:kr.env.NODE_ENV||kr.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var le={red:(e)=>`\x1B[31m${e}\x1B[0m`,green:(e)=>`\x1B[32m${e}\x1B[0m`,yellow:(e)=>`\x1B[33m${e}\x1B[0m`,blue:(e)=>`\x1B[34m${e}\x1B[0m`,magenta:(e)=>`\x1B[35m${e}\x1B[0m`,cyan:(e)=>`\x1B[36m${e}\x1B[0m`,white:(e)=>`\x1B[37m${e}\x1B[0m`,gray:(e)=>`\x1B[90m${e}\x1B[0m`,bgRed:(e)=>`\x1B[41m${e}\x1B[0m`,bgYellow:(e)=>`\x1B[43m${e}\x1B[0m`,bgGray:(e)=>`\x1B[100m${e}\x1B[0m`,bold:(e)=>`\x1B[1m${e}\x1B[0m`,dim:(e)=>`\x1B[2m${e}\x1B[0m`,italic:(e)=>`\x1B[3m${e}\x1B[0m`,underline:(e)=>`\x1B[4m${e}\x1B[0m`,strikethrough:(e)=>`\x1B[9m${e}\x1B[0m`,reset:"\x1B[0m"},_=le,Ox=le.red,qv=le.green,Fx=le.yellow,Yv=le.blue,Lx=le.magenta,Mx=le.cyan,vh=le.white,Bx=le.gray,Jv=le.bgRed,Xv=le.bgYellow,Ix=le.bgGray,bh=le.bold,_x=le.dim,jx=le.italic,Ux=le.underline,Kx=le.strikethrough,Wx=le.reset,qa={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Zv={debug:"\uD83D\uDD0D",info:Yv("ℹ"),success:qv("✓"),warning:Xv(vh(bh(" WARN "))),error:Jv(vh(bh(" ERROR ")))};class As{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(e,t={}){this.name=e,this.config={...Ss},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Wh,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??L.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},i=t.timestamp!==void 0;if(i)delete r.timestamp;if(this.config={...this.config,...r,timestamp:i||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let n=this.generateKeyId(),s=this.generateKey();this.currentKeyId=n,this.keys.set(n,s),this.encryptionKeys.set(n,{key:s,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...qa,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...qa};return{...qa,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:Ss.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,i])=>i!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!oe()&&this.config.writeToFile===!0}async writeToFile(e){let r=(async()=>{let n,s=0,o=3,a=1000;while(s<o)try{try{try{await Lw(this.config.logDirectory,sh.F_OK|sh.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Mw(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:pt.from(e);try{if(!Qn(this.currentLogFile))await Wa(this.currentLogFile,"",{mode:420});if(n=nh(this.currentLogFile,"a",420),Fw(n,c,{flag:"a"}),ih(n),n!==void 0)Ka(n),n=void 0;if((await Ar(this.currentLogFile)).size===0){if(await Wa(this.currentLogFile,c,{flag:"w",mode:420}),(await Ar(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let f=l;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(s<o-1){let u=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${s+1}/${o}:`,u);let h=a*2**s;await new Promise((d)=>setTimeout(d,h)),s++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(n!==void 0)try{Ka(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(s===o-1){let f=c,u=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),c}s++;let l=a*2**(s-1);await new Promise((f)=>setTimeout(f,l))}})();this.pendingOperations.push(r);let i=this.pendingOperations.length-1;try{await r}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(i,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 Rr(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 Rr(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return Rr(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(oe())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.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,i=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},i)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,r=this.generateKeyId(),i=this.generateKey();this.currentKeyId=r,this.keys.set(r,i),this.encryptionKeys.set(r,{key:i,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,a],[,c])=>c.createdAt.getTime()-a.createdAt.getTime()),s=typeof t.maxKeys==="number"?t.maxKeys:1,o=Math.max(1,s);if(n.length>o)for(let[a]of n.slice(o))this.encryptionKeys.delete(a),this.keys.delete(a)}generateKeyId(){return Ua(16).toString("hex")}generateKey(){return Ua(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=Ua(16),i=Nw("aes-256-gcm",t,r),n=pt.isBuffer(e)?e:pt.from(e,"utf8"),s=i.update(n),o=i.final(),a=s.length+o.length,c=i.getAuthTag(),l=pt.allocUnsafe(16+a+16);return r.copy(l,0),s.copy(l,16),o.copy(l,16+s.length),c.copy(l,16+a),{encrypted:l,iv:r}}async compressData(e){return new Promise((t,r)=>{let i=ah(),n=[];i.on("data",(s)=>n.push(s)),i.on("end",()=>t(pt.from(pt.concat(n)))),i.on("error",r),i.write(e),i.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(oe())return;if(!this.shouldWriteToFile())return;let e=await Ar(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,i=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let n=await es(this.config.logDirectory),s=n.filter((c)=>c.startsWith(this.name)&&/\.log\.\d+$/.test(c)).sort((c,l)=>{let f=Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),o=s.length>0?Number.parseInt(s[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,a=`${r}.${o}`;if(await Ar(r).catch(()=>null))try{if(await oh(r,a),t.compress)try{let c=`${a}.gz`;await this.compressLogFile(a,c),await ts(a)}catch(c){console.error("Error compressing rotated file:",c)}if(s.length===0&&!n.some((c)=>c.endsWith(".log.1")))try{let c=`${r}.1`;await Wa(c,"")}catch(c){console.error("Error creating backup file:",c)}}catch(c){console.error(`Error during rotation: ${c instanceof Error?c.message:String(c)}`)}}else{let n=new Date().toISOString().replace(/[:.]/g,"-"),s=r.replace(/\.log$/,`-${n}.log`);if(await Ar(r).catch(()=>null))await oh(r,s)}if(this.currentLogFile=i,t.maxFiles){let s=(await es(this.config.logDirectory)).filter((o)=>o.startsWith(this.name)).sort((o,a)=>a.localeCompare(o));for(let o of s.slice(t.maxFiles))await ts(Rr(this.config.logDirectory,o))}}}async compressLogFile(e,t){let r=rh(e),i=Ow(t),n=ah();await _w(r,n,i)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let i=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Qn(this.currentLogFile))try{let e=nh(this.currentLogFile,"r+");ih(e),Ka(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!oe()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await es(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of t)try{await ts(Rr(this.config.logDirectory,r))}catch(i){console.error(`Failed to delete temp file ${r}:`,i)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?_.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||oe())return!1;let e=typeof L.env.NO_COLOR<"u",t=L.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof L.stderr<"u"&&L.stderr.isTTY||typeof L.stdout<"u"&&L.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:i="",message:n,level:s,showTimestamp:o=!0}=e,a=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(s==="warning")d.push("WARN");else if(s==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(i)d.push(i.replace(/[[\]]/g,""));return d.push(n),d.join(" ")}let c=L.stdout.columns||120,l="";if(s==="warning"||s==="error")l=`${r} ${n}`;else if(s==="info"||s==="success")l=`${r} ${i} ${n}`;else l=`${r} ${i} ${_.cyan(n)}`;if(!o)return l.trim();let f=a(l).trim().length,u=a(t).length,h=Math.max(1,c-2-f-u);return`${l.trim()}${" ".repeat(h)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(s,o)=>{let a=Number.parseInt(o,10);return a<t[0].length?String(t[0][a]):s});let r=/%([sdijfo%])/g,i=0,n=e.replace(r,(s,o)=>{if(o==="%")return"%";if(i>=t.length)return s;let a=t[i++];switch(o){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return s}});if(i<t.length)n+=` ${t.slice(i).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`;return n}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,n)=>{let s=_.underline(_.blue(i)),o=this.toAbsoluteFilePath(n);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let a=`file://${encodeURI(o)}`,c="\x1B]8;;",l="\x1B\\";return`\x1B]8;;${a}\x1B\\${s}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${n}\x1B\\${s}\x1B]8;;\x1B\\`;return s}),t=t.replace(/`([^`]+)`/g,(r,i)=>_.bgGray(i)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,i)=>_.bold(i)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,i)=>_.italic(i)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,i)=>_.italic(i)),t=t.replace(/~([^~]+)~/g,(r,i)=>_.strikethrough(i)),t}supportsHyperlinks(){if(oe())return!1;let e=L.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=L.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(Bw(t)||t.startsWith("./")||t.startsWith("../"))t=Iw(t);else return null;return Qn(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let i=new Date,n=this.formatConsoleTimestamp(i),s=this.formatFileTimestamp(i),o,a;if(t instanceof Error)o=t.message,a=t.stack;else o=this.formatMessage(t,r);let{consoleText:c,fileText:l}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Zv[e],h=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:_.gray(c),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:_.green(c),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:n,icon:u,tag:h,message:c,level:e}),console.error(d),a){let p=a.split(`
169
+ `);for(let g of p)if(g.trim()&&!g.includes(o))console.error(this.formatConsoleMessage({timestamp:n,message:_.gray(` ${g}`),level:e,showTimestamp:!1}))}break}}else if(!oe()){if(console.error(`${s} ${this.environment}.${e.toUpperCase()}: ${o}`),a)console.error(a)}let f=`${s} ${this.environment}.${e.toUpperCase()}: ${l}
170
+ `;if(a)f+=`${a}
171
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(e,t=""){let r={update:(a,c)=>{},finish:(a)=>{},interrupt:(a,c)=>{}};if(!this.enabled)return r;let i=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:i,lastRenderedLine:""},this.shouldStyleConsole()&&!oe()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(a,c)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,a),this.activeProgressBar.total),c!==void 0)this.activeProgressBar.message=c;if(this.shouldStyleConsole()&&!oe()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(a)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,a)},interrupt:(a,c="info")=>{if(!oe()&&L.stdout.isTTY)L.stdout.write(`
172
+ `);if(this[c==="warning"?"warn":c](a),this.activeProgressBar&&this.shouldStyleConsole()&&!oe()&&L.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(e){let t=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",i=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:i,icon:this.options.showIcons===!1?"":_.blue("◐"),tag:r,message:`${_.cyan(e)}...`}))}return async(r)=>{if(!this.enabled)return;let i=performance.now(),n=Math.round(i-t),s=`${e} completed in ${n}ms`,o=new Date,a=this.formatConsoleTimestamp(o),l=`${this.formatFileTimestamp(o)} ${this.environment}.INFO: ${s}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
173
+ `,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:a,icon:this.options.showIcons===!1?"":_.green("✓"),tag:f,message:`${s}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!oe())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(e,...t){await this.log("debug",e,...t)}async info(e,...t){await this.log("info",e,...t)}async success(e,...t){await this.log("success",e,...t)}async warn(e,...t){await this.log("warning",e,...t)}async error(e,...t){await this.log("error",e,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let e=this.config.rotation,{encrypt:t}=e;return!!t}async only(e){if(!this.enabled)return;return await e()}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}extend(e){let t=`${this.name}:${e}`,r=new As(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(oe())throw Error("createReadStream is not supported in browser environments");if(!Qn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rh(this.currentLogFile,{encoding:"utf8"})}async decrypt(e){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 i=pt.isBuffer(e)?e:pt.from(e,"base64"),n=i.subarray(0,16),s=i.subarray(i.length-16),o=i.subarray(16,i.length-16),a=Dw("aes-256-gcm",r,n);a.setAuthTag(s);let c=a.update(o),l=a.final(),f=c.length+l.length,u=pt.allocUnsafe(f);return c.copy(u,0),l.copy(u,c.length),u.toString("utf8")}catch(i){throw Error(`Decryption failed: ${i instanceof Error?i.message:String(i)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return oe()}isServerMode(){return!oe()}setTestEncryptionKey(e,t){this.currentKeyId=e,this.keys.set(e,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(e){if(!this.enabled)return;let t=new Date,r=this.formatConsoleTimestamp(t),i=this.formatFileTimestamp(t),{consoleText:n,fileText:s}=this.buildOutputTexts(e);if(this.shouldStyleConsole()){let a=n.split(`
174
+ `),c=Math.max(...a.map((h)=>h.length))+2,l=`┌${"─".repeat(c)}┐`,f=`└${"─".repeat(c)}┘`,u=a.map((h)=>this.formatConsoleMessage({timestamp:r,message:_.cyan(h),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:_.cyan(l),showTimestamp:!1})),u.forEach((h)=>console.error(h)),console.error(this.formatConsoleMessage({timestamp:r,message:_.cyan(f),showTimestamp:!1}))}else if(!oe())console.error(`${i} ${this.environment}.INFO: [BOX] ${s}`);let o=`${i} ${this.environment}.INFO: [BOX] ${s}
175
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(o)}async prompt(e){if(oe())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${_.cyan("?")} ${e} (y/n) `);let r=(i)=>{let n=i.toString().trim().toLowerCase();L.stdin.removeListener("data",r);try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!1)}catch{}L.stdin.pause(),console.error(""),t(n==="y"||n==="yes")};try{if(typeof L.stdin.setRawMode==="function")L.stdin.setRawMode(!0)}catch{}L.stdin.resume(),L.stdin.once("data",r)})}setFancy(e){this.fancy=e}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(e,...t){if(!this.enabled)return;let r=e;if(t&&t.length>0){let c=/%([sdijfo%])/g,l=0;if(r=e.replace(c,(f,u)=>{if(u==="%")return"%";if(l>=t.length)return f;let h=t[l++];switch(u){case"s":return String(h);case"d":case"i":return Number(h).toString();case"j":case"o":return JSON.stringify(h,null,2);default:return f}}),l<t.length)r+=` ${t.slice(l).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:i,fileText:n}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?_.gray(this.formatTag(this.name)):"",l=this.options.showIcons===!1?"":`${_.blue("◐")} `;console.error(`${l}${c} ${_.cyan(i)}`)}let a=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
176
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(a)}renderProgressBar(e,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!L.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(e.current/e.total*100))),i=Math.round(e.barLength*r/100),n=e.barLength-i,s=_.green("━".repeat(i)),o=_.gray("━".repeat(n)),a=`[${s}${o}]`,c=`${r}%`.padStart(4),l=e.message?` ${e.message}`:"",f=this.options.showIcons===!1?"":t||r===100?_.green("✓"):_.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${_.gray(this.formatTag(this.name))}`:"",h=`\r${f}${u} ${a} ${c}${l}`,d=L.stdout.columns||80,p=" ".repeat(Math.max(0,d-h.replace(this.ANSI_PATTERN,"").length));if(e.lastRenderedLine=`${h}${p}`,L.stdout.write(e.lastRenderedLine),t)L.stdout.write(`
177
+ `)}finishProgressBar(e,t){if(!this.enabled||!this.fancy||oe()||!L.stdout.isTTY){this.activeProgressBar=null;return}if(e.current<e.total)e.current=e.total;if(t)e.message=t;this.renderProgressBar(e,!0),this.activeProgressBar=null}async clear(e={}){if(oe()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await es(this.config.logDirectory),r=[];for(let i of t){if(!(e.name?new RegExp(e.name.replace("*",".*")).test(i):i.startsWith(this.name))||!i.endsWith(".log"))continue;let s=Rr(this.config.logDirectory,i);if(e.before)try{if((await Ar(s)).mtime>=e.before)continue}catch(o){console.error(`Failed to get stats for file ${s}:`,o);continue}r.push(s)}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 i of r)try{await ts(i),console.warn(`Deleted log file: ${i}`)}catch(n){console.error(`Failed to delete log file ${i}:`,n)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var Hx=new As("stacks");class qe extends Error{timestamp;context;constructor(e,t={}){super(e);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 e=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,r])=>`${t}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${e}`}}class Hh extends qe{code="CONFIG_NOT_FOUND";constructor(e,t,r){let i=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],n="";if(i.length===1)n=` or alias "${i[0]}"`;else if(i.length>1)n=` or aliases ${i.map((s)=>`"${s}"`).join(", ")}`;super(`Configuration "${e}"${n} not found`,{configName:e,alias:r,searchPaths:t,searchPathCount:t.length})}}class $s extends qe{code="CONFIG_LOAD_ERROR";constructor(e,t,r){super(`Failed to load configuration from "${e}": ${t.message}`,{configPath:e,configName:r,originalError:t.name,originalMessage:t.message});this.cause=t}}class Vh extends qe{code="CONFIG_VALIDATION_ERROR";constructor(e,t,r){super(`Configuration validation failed for "${e}"`,{configPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class zh extends qe{code="CONFIG_MERGE_ERROR";constructor(e,t,r,i){super(`Failed to merge configuration from "${e}" with "${t}": ${r.message}`,{sourcePath:e,targetPath:t,configName:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class pc extends qe{code="ENV_VAR_ERROR";constructor(e,t,r,i){super(`Failed to parse environment variable "${e}" with value "${t}" as ${r}`,{envKey:e,envValue:t,expectedType:r,configName:i})}}class Gh extends qe{code="FILE_SYSTEM_ERROR";constructor(e,t,r){super(`File system ${e} failed for "${t}": ${r.message}`,{operation:e,path:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class qh extends qe{code="TYPE_GENERATION_ERROR";constructor(e,t,r){super(`Failed to generate types from "${e}" to "${t}": ${r.message}`,{configDir:e,outputPath:t,originalError:r.name,originalMessage:r.message});this.cause=r}}class Es extends qe{code="SCHEMA_VALIDATION_ERROR";constructor(e,t,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:e,configName:r,validationErrors:t,errorCount:t.length})}}class Yh extends qe{code="BROWSER_CONFIG_ERROR";constructor(e,t,r,i){super(`Failed to fetch configuration from "${e}": ${t} ${r}`,{endpoint:e,status:t,statusText:r,configName:i})}}class Jh extends qe{code="PLUGIN_ERROR";constructor(e,t,r){super(`Plugin "${e}" failed during ${t}: ${r.message}`,{pluginName:e,operation:t,originalError:r.name,originalMessage:r.message});this.cause=r}}var Dr={configNotFound(e,t,r){return new Hh(e,t,r)},configLoad(e,t,r){return new $s(e,t,r)},configValidation(e,t,r){return new Vh(e,t,r)},configMerge(e,t,r,i){return new zh(e,t,r,i)},envVar(e,t,r,i){return new pc(e,t,r,i)},fileSystem(e,t,r){return new Gh(e,t,r)},typeGeneration(e,t,r){return new qh(e,t,r)},schemaValidation(e,t,r){return new Es(e,t,r)},browserConfig(e,t,r,i){return new Yh(e,t,r,i)},plugin(e,t,r){return new Jh(e,t,r)}};async function Qv(e,t={}){let{maxRetries:r=3,retryDelay:i=1000,isRetryable:n=()=>!0,fallback:s}=t,o=Error("Unknown error occurred");for(let a=0;a<=r;a++)try{return await e()}catch(c){if(o=c instanceof Error?c:Error(String(c)),a===r||!n(o))break;if(i>0)await new Promise((l)=>setTimeout(l,i))}if(s!==void 0)return s;throw o instanceof Error?o:Error(`Unknown error: ${String(o)}`)}class yc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(e,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(e.toLowerCase()),parse:(e)=>{let t=e.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(e,t)=>t==="number"||!Number.isNaN(Number(e))&&!Number.isNaN(Number.parseFloat(e)),parse:(e)=>{let t=Number(e);if(Number.isNaN(t))throw TypeError(`Cannot parse "${e}" as number`);return t}},{name:"array",canParse:(e,t)=>t==="array"||e.startsWith("[")||e.includes(","),parse:(e)=>{try{let t=JSON.parse(e);if(Array.isArray(t))return t}catch{}return e.split(",").map((t)=>t.trim())}},{name:"json",canParse:(e,t)=>t==="object"||(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")),parse:(e)=>{try{return JSON.parse(e)}catch(t){throw Error(`Cannot parse "${e}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(e,t,r={}){let{prefix:i,useCamelCase:n=!0,useBackwardCompatibility:s=!0,customParsers:o={},verbose:a=!1,trackPerformance:c=!0}=r,l=async()=>{if(!e)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let f=i||this.generateEnvPrefix(e),u={...t};return this.processObject(u,[],f,{useCamelCase:n,useBackwardCompatibility:s,customParsers:o,verbose:a,configName:e}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(c)return cc.track("applyEnvironmentVariables",l,{configName:e});return l()}generateEnvPrefix(e){return e.toUpperCase().replace(/-/g,"_")}formatEnvKey(e,t){if(!t)return e.toUpperCase();return e.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=o.map((f)=>this.formatEnvKey(f,i.useCamelCase)),c=`${r}_${a.join("_")}`,l=i.useBackwardCompatibility?`${r}_${o.map((f)=>f.toUpperCase()).join("_")}`:null;if(i.verbose);if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.processObject(s,o,r,i);else{let f=is.env[c]||(l?is.env[l]:void 0);if(f!==void 0){if(i.verbose){let u=is.env[c]?c:l}try{e[n]=this.parseEnvironmentValue(f,typeof s,c,i.customParsers,i.configName)}catch(u){if(u instanceof pc)throw u;throw Dr.envVar(c,f,typeof s,i.configName)}}}}}parseEnvironmentValue(e,t,r,i,n){for(let[s,o]of Object.entries(i))try{return o(e)}catch{continue}for(let s of this.defaultParsers)if(s.canParse(e,t))try{return s.parse(e)}catch{throw Dr.envVar(r,e,`${t} (via ${s.name} parser)`,n)}return e}getEnvironmentVariables(e){let t={},r=e.toUpperCase();for(let[i,n]of Object.entries(is.env))if(i.startsWith(r)&&n!==void 0)t[i]=n;return t}validateEnvironmentVariable(e,t,r){let i=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(e))i.push(`Environment variable key "${e}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(e,t,r,{})}catch(n){i.push(`Cannot parse value "${t}" as ${r}: ${n}`)}return{isValid:i.length===0,errors:i}}generateEnvVarDocs(e,t,r={}){let{prefix:i,format:n="text"}=r,s=i||this.generateEnvPrefix(e),o=[];switch(this.extractEnvVarInfo(t,[],s,o),n){case"markdown":return this.formatAsMarkdown(o,e);case"json":return JSON.stringify(o,null,2);default:return this.formatAsText(o,e)}}extractEnvVarInfo(e,t,r,i){for(let[n,s]of Object.entries(e)){let o=[...t,n],a=`${r}_${o.map((c)=>this.formatEnvKey(c,!0)).join("_")}`;if(typeof s==="object"&&s!==null&&!Array.isArray(s))this.extractEnvVarInfo(s,o,r,i);else i.push({key:a,type:Array.isArray(s)?"array":typeof s,description:`Configuration for ${o.join(".")}`,example:this.generateExample(s)})}}generateExample(e){if(Array.isArray(e))return JSON.stringify(e);if(typeof e==="object"&&e!==null)return JSON.stringify(e);return String(e)}formatAsText(e,t){let r=`Environment Variables for ${t}:
178
+
179
+ `;for(let i of e)r+=`${i.key}
180
+ `,r+=` Type: ${i.type}
181
+ `,r+=` Description: ${i.description}
182
+ `,r+=` Example: ${i.example}
183
+
184
+ `;return r}formatAsMarkdown(e,t){let r=`# Environment Variables for ${t}
185
+
186
+ `;r+=`| Variable | Type | Description | Example |
187
+ `,r+=`|----------|------|-------------|----------|
188
+ `;for(let i of e)r+=`| \`${i.key}\` | ${i.type} | ${i.description} | \`${i.example}\` |
189
+ `;return r}}function eb(e,t,r={}){return Xh(e,t,r,new WeakMap)}function Xh(e,t,r,i){let{arrayMergeMode:n="replace",skipNullish:s=!1,customMerger:o}=r;if(t===null||t===void 0)return s?e:t;if(o){let a=o(e,t);if(a!==void 0)return a}if(Array.isArray(t)||Array.isArray(e))return Zh(e,t,n,i);if(!Ue(t)||!Ue(e))return t;return nb(e,t,r,i)}function Zh(e,t,r,i){if(Array.isArray(t)&&!Array.isArray(e))return t;if(Array.isArray(e)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e))switch(r){case"replace":return t;case"concat":return tb(e,t);case"smart":return rb(e,t,i);default:return t}return t}function tb(e,t){let r=[...t];for(let i of e)if(!r.some((n)=>ac(n,i)))r.push(i);return r}function rb(e,t,r){if(t.length===0)return e;if(e.length===0)return t;if(Ue(t[0])&&Ue(e[0]))return ib(e,t,r);if(t.every((i)=>typeof i==="string")&&e.every((i)=>typeof i==="string")){let i=[...t];for(let n of e)if(!i.includes(n))i.push(n);return i}return t}function ib(e,t,r){let i=[...t];for(let n of e){if(!Ue(n)){i.push(n);continue}let s=["id","name","key","path","type"],o=!1;for(let a of s)if(a in n){if(i.find((l)=>Ue(l)&&(a in l)&&l[a]===n[a])){o=!0;break}}if(!o)i.push(n)}return i}function nb(e,t,r,i){let n=t;if(Ue(n)&&i.has(n))return i.get(n);let s={...e};if(Ue(n))i.set(n,s);for(let o in n){if(!Object.prototype.hasOwnProperty.call(n,o))continue;let a=n[o],c=s[o];if(r.skipNullish&&(a===null||a===void 0))continue;if(a===null||a===void 0){s[o]=a;continue}if(Ue(a)&&Ue(c))s[o]=Xh(c,a,r,i);else if(Array.isArray(a)||Array.isArray(c))s[o]=Zh(c,a,r.arrayMergeMode||"smart",i);else s[o]=a}return s}function Qh(e,t,r="replace"){return eb(e,t,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ac(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ac(e[r],t[r]))return!1;return!0}if(Ue(e)&&Ue(t)){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let n of r){if(!Object.prototype.hasOwnProperty.call(t,n))return!1;if(!ac(e[n],t[n]))return!1}return!0}return!1}function Ue(e){return Boolean(e&&typeof e==="object"&&!Array.isArray(e))}class ed{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(e,t,r={}){let{arrayStrategy:i="replace",useCache:n=!0,cacheTtl:s,trackPerformance:o=!0,verbose:a=!1}=r;if(n){let l=us.getWithFileCheck("file",e);if(l){if(a)console.log(`Configuration loaded from cache: ${e}`);return l}}let c=async()=>{if(!ns(e))return null;try{let l=`?t=${Date.now()}`,f=await import(e+l),u=f.default||f,h="default"in f,d=Object.keys(f).length>0;if(!h&&!d)throw new $s(e,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new $s(e,Error("Configuration must export a valid object"),"unknown");let y={config:Qh(t,u,i),source:{type:"file",path:e,priority:100,timestamp:new Date}};if(n)us.setWithFileCheck("file",y,e,s);return y}catch(l){throw l instanceof Error?Dr.configLoad(e,l):Dr.configLoad(e,Error(String(l)))}};if(o)return cc.track("loadFromPath",c,{path:e});return c()}async tryLoadFromPaths(e,t,r={}){for(let i of e)try{let n=await this.loadFromPath(i,t,r);if(n)return n}catch(n){if(n instanceof Error&&n.name==="ConfigLoadError")throw n;if(r.verbose)console.warn(`Failed to load config from ${i}:`,n)}return null}generateConfigPaths(e,t,r){let i=this.generateNamePatterns(e,r),n=[];for(let s of i)for(let o of this.extensions)n.push(Ya(t,`${s}${o}`));return n}generateNamePatterns(e,t){let r=[];if(r.push("config",".config"),e)r.push(e,`.${e}.config`,`${e}.config`,`.${e}`);let i=t===void 0?[]:Array.isArray(t)?t:[t];for(let s of i){if(!s)continue;if(r.push(s,`.${s}.config`,`${s}.config`,`.${s}`),e)r.push(`${e}.${s}.config`,`.${e}.${s}.config`)}let n=new Set;return r.filter((s)=>{if(!s||n.has(s))return!1;return n.add(s),!0})}checkFileAccess(e){return Qv(async()=>ns(e),{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(e,t,r){let i=[];if(!ns(e))return i;if(t||r){let n=this.generateNamePatterns(t||"",r);for(let s of n)for(let o of this.extensions){let a=Ya(e,`${s}${o}`);if(await this.checkFileAccess(a))i.push(a)}}else try{let{readdirSync:n}=await import("fs"),s=n(e);for(let o of s)if(this.looksLikeConfigFile(o)){let a=Ya(e,o);if(await this.checkFileAccess(a))i.push(a)}}catch{return[]}return i}looksLikeConfigFile(e){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(e))}async validateConfigFile(e){let t=[];try{if(!ns(e))return t.push("Configuration file does not exist"),t;let r=await import(e),i=r.default||r;if(i===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof i!=="object"||i===null)t.push("Configuration must be an object");else if(Array.isArray(i))t.push("Configuration cannot be an array at the root level");if(e.endsWith(".json"))try{let{readFileSync:n}=await import("fs"),s=n(e,"utf8");JSON.parse(s)}catch(n){t.push(`Invalid JSON syntax: ${n}`)}}catch(r){t.push(`Failed to load configuration file: ${r}`)}return t}async getFileModificationTime(e){try{let{statSync:t}=await import("fs");return t(e).mtime}catch{return null}}async preloadConfigurations(e,t={}){let r=new Map;return await Promise.allSettled(e.map(async(i)=>{try{let n=await this.loadFromPath(i,{},t);if(n)r.set(i,n.config)}catch(n){if(t.verbose)console.warn(`Failed to preload ${i}:`,n)}})),r}}var ob=/^https?:\/\//;class td{async validateConfiguration(e,t,r={}){let{stopOnFirstError:i=!1,validateRequired:n=!0,validateTypes:s=!0,customRules:o=[],trackPerformance:a=!0,verbose:c=!1}=r,l=async()=>{let f=[],u=[],h={stopOnFirstError:i,validateRequired:n,validateTypes:s,customRules:o,trackPerformance:a,verbose:c};try{if(typeof t==="string")return await this.validateWithSchemaFile(e,t,h);else if(Array.isArray(t))return this.validateWithRules(e,[...t,...o],h);else return this.validateWithJSONSchema(e,t,h)}catch(d){return f.push({path:"",message:`Validation failed: ${d}`,rule:"system"}),{isValid:!1,errors:f,warnings:u}}};if(a)return await cc.track("validateConfiguration",l);return l()}async validateWithSchemaFile(e,t,r){try{if(!sb(t))throw new Es(t,[{path:"",message:"Schema file does not exist"}]);let i=await import(t),n=i.default||i;if(Array.isArray(n))return this.validateWithRules(e,n,r);else return this.validateWithJSONSchema(e,n,r)}catch(i){throw new Es(t,[{path:"",message:`Failed to load schema: ${i}`}])}}validateWithJSONSchema(e,t,r){let i=[],n=[];return this.validateObjectAgainstSchema(e,t,"",i,n,r),{isValid:i.length===0,errors:i,warnings:n}}validateObjectAgainstSchema(e,t,r,i,n,s){if(s.validateTypes&&t.type){let o=Array.isArray(e)?"array":typeof e,a=Array.isArray(t.type)?t.type:[t.type];if(!a.includes(o)){if(i.push({path:r,message:`Expected type ${a.join(" or ")}, got ${o}`,expected:a.join(" or "),actual:o,rule:"type"}),s.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(e)){if(i.push({path:r,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"}),s.stopOnFirstError)return}if(typeof e==="string"){if(t.minLength!==void 0&&e.length<t.minLength)i.push({path:r,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:e.length,rule:"minLength"});if(t.maxLength!==void 0&&e.length>t.maxLength)i.push({path:r,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:e.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(e))i.push({path:r,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:e,rule:"pattern"})}}if(typeof e==="number"){if(t.minimum!==void 0&&e<t.minimum)i.push({path:r,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:e,rule:"minimum"});if(t.maximum!==void 0&&e>t.maximum)i.push({path:r,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:e,rule:"maximum"})}if(Array.isArray(e)&&t.items)for(let o=0;o<e.length;o++){let a=r?`${r}[${o}]`:`[${o}]`;if(this.validateObjectAgainstSchema(e[o],t.items,a,i,n,s),s.stopOnFirstError&&i.length>0)return}if(e&&typeof e==="object"&&!Array.isArray(e)){let o=e;if(s.validateRequired&&t.required){for(let a of t.required)if(!(a in o)){if(i.push({path:r?`${r}.${a}`:a,message:`Missing required property '${a}'`,expected:"required",rule:"required"}),s.stopOnFirstError)return}}if(t.properties){for(let[a,c]of Object.entries(t.properties))if(a in o){let l=r?`${r}.${a}`:a;if(this.validateObjectAgainstSchema(o[a],c,l,i,n,s),s.stopOnFirstError&&i.length>0)return}}if(t.additionalProperties===!1){let a=new Set(Object.keys(t.properties||{}));for(let c of Object.keys(o))if(!a.has(c))n.push({path:r?`${r}.${c}`:c,message:`Additional property '${c}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(e,t,r){let i=[],n=[];for(let s of t)try{let o=this.getValueByPath(e,s.path),a=this.validateWithRule(o,s,s.path);if(i.push(...a),r.stopOnFirstError&&i.length>0)break}catch(o){i.push({path:s.path,message:`Rule validation failed: ${o}`,rule:"system"})}return{isValid:i.length===0,errors:i,warnings:n}}validateWithRule(e,t,r){let i=[];if(t.required&&(e===void 0||e===null))return i.push({path:r,message:t.message||`Property '${r}' is required`,expected:"required",rule:"required"}),i;if(e===void 0||e===null)return i;if(t.type){let n=Array.isArray(e)?"array":typeof e;if(n!==t.type)i.push({path:r,message:t.message||`Expected type ${t.type}, got ${n}`,expected:t.type,actual:n,rule:"type"})}if(t.min!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n<t.min)i.push({path:r,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:n,rule:"min"})}if(t.max!==void 0){let n=Array.isArray(e)?e.length:typeof e==="string"?e.length:typeof e==="number"?e:0;if(n>t.max)i.push({path:r,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:n,rule:"max"})}if(t.pattern&&typeof e==="string"){if(!t.pattern.test(e))i.push({path:r,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:e,rule:"pattern"})}if(t.enum&&!t.enum.includes(e))i.push({path:r,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:e,rule:"enum"});if(t.validator){let n=t.validator(e);if(n)i.push({path:r,message:t.message||n,rule:"custom"})}return i}getValueByPath(e,t){if(!t)return e;let r=t.split("."),i=e;for(let n of r)if(i&&typeof i==="object"&&n in i)i=i[n];else return;return i}generateRulesFromInterface(e){let t=[],r=e.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let i of r){let[,n,s,o]=i;t.push({path:n,required:!s,type:this.mapTypeScriptType(o)})}return t}mapTypeScriptType(e){switch(e.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:ob},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var yt=new As("bunfig",{showTags:!0});function ab(e){if(!e)return"";let t=Array.isArray(e)?e.filter(Boolean):[e];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((r)=>`"${r}"`).join(", ")}`}class rd{fileLoader=new ed;envProcessor=new yc;validator=new td;async loadConfig(e){let t=Date.now(),{cache:r,performance:i,schema:n,validate:s,...o}=e;try{if(r?.enabled){let c=this.checkCache(o.name||"",o);if(c)return c}let a;try{a=await this.loadConfigurationStrategies(o,!0,r)}catch(c){let l=o.__strictErrorHandling;if(c instanceof Error&&c.name==="ConfigNotFoundError"){if(l)throw c;a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`No configuration file found for "${o.name||"config"}", using defaults with environment variables`]}}else if(c instanceof Error&&c.name==="ConfigLoadError"){let f=c.message.includes("EACCES")||c.message.includes("EPERM")||c.message.includes("permission denied"),u=!f&&(c.message.includes("syntax")||c.message.includes("Expected")||c.message.includes("Unexpected")||c.message.includes("BuildMessage")||c.message.includes("errors building")),h=c.message.includes("Configuration must export a valid object")||c.message.includes("Configuration file is empty and exports nothing");if(l&&(h||f))throw c;if(u&&(!l||!h))a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!l)a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading error, using defaults: ${c.message}`]};else throw c}else a={...await this.applyEnvironmentVariables(o.name||"",o.defaultConfig,o.checkEnv!==!1,o.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${c instanceof Error?c.message:String(c)}`]}}if(n||s)await this.validateConfiguration(a.config,n,s,o.name);if(r?.enabled&&a)this.cacheResult(o.name||"",a,r,o);if(i?.enabled){let c={operation:"loadConfig",duration:Date.now()-t,configName:o.name,timestamp:new Date};if(i.onMetrics)i.onMetrics(c);if(i.slowThreshold&&c.duration>i.slowThreshold)yt.warn(`Slow configuration loading detected: ${c.duration}ms for ${o.name}`);a.metrics=c}return a}catch(a){if(a instanceof Error&&a.name==="ConfigNotFoundError")throw a;let c=Date.now()-t;throw yt.error(`Configuration loading failed after ${c}ms:`,[a instanceof Error?a:Error(String(a))]),a}}async loadConfigurationStrategies(e,t=!1,r){let{name:i="",alias:n,cwd:s,configDir:o,defaultConfig:a,checkEnv:c=!0,arrayStrategy:l="replace",verbose:f=!1}=e,u=s||xs.cwd(),h=[],d=await this.loadLocalConfiguration(i,n,u,o,a,l,f,c,r);if(d)return h.push(...this.getLocalSearchPaths(i,n,u,o)),this.finalizeResult(d,h,c,i,f);let p=await this.loadHomeConfiguration(i,n,a,l,f,c);if(p)return h.push(...this.getHomeSearchPaths(i,n)),this.finalizeResult(p,h,c,i,f);let g=await this.loadPackageJsonConfiguration(i,n,u,a,l,f,c);if(g)return h.push(_e(u,"package.json")),this.finalizeResult(g,h,c,i,f);if(h.push(...this.getAllSearchPaths(i,n,u,o)),t)throw Dr.configNotFound(i,h,n);return{...await this.applyEnvironmentVariables(i,a,c,f),warnings:[`No configuration file found for "${i}"${ab(n)}, using defaults with environment variables`]}}async loadLocalConfiguration(e,t,r,i,n,s,o,a,c){let l=a?ss(e,n,o):n,f=this.getLocalDirectories(r,i);for(let u of f){if(o)yt.info(`Searching for configuration in: ${u}`);let h=this.fileLoader.generateConfigPaths(e,u,t),d=await this.fileLoader.tryLoadFromPaths(h,l,{arrayStrategy:s,verbose:o,cacheTtl:c?.ttl,useCache:!c?.ttl||c.ttl>100});if(d){if(o)yt.success(`Configuration loaded from: ${d.source.path}`);return d}}return null}async loadHomeConfiguration(e,t,r,i,n,s){if(!e)return null;let o=s?ss(e,r,n):r,a=[_e(br(),".config",e),_e(br(),".config"),br()];for(let c of a){if(n)yt.info(`Checking home directory: ${c}`);let l=this.fileLoader.generateConfigPaths(e,c,t),f=await this.fileLoader.tryLoadFromPaths(l,o,{arrayStrategy:i,verbose:n});if(f){if(n)yt.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(e,t,r,i,n,s,o){let a=o?ss(e,i,s):i;try{let c=_e(r,"package.json");if(!ew(c))return null;let l={};try{l=JSON.parse(tw(c,"utf8"))}catch(h){if(s)yt.warn("Failed to parse package.json:",[h instanceof Error?h:Error(String(h))]);return null}let f=l[e],u=e;if(!f&&t){let h=Array.isArray(t)?t:[t];for(let d of h){if(!d)continue;if(l[d]){f=l[d],u=d;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(s)yt.success(`Configuration loaded from package.json: ${u}`);return{config:Qh(a,f,n),source:{type:"package.json",path:c,priority:30,timestamp:new Date}}}}catch(c){if(s)yt.warn("Failed to load package.json:",[c instanceof Error?c:Error(String(c))])}return null}async applyEnvironmentVariables(e,t,r,i){if(!r||!e||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:ss(e,t,i),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(e,t,r,i,n){return{config:e.config,source:e.source,path:e.source.path}}async validateConfiguration(e,t,r,i){let n=[];if(r){let s=r(e);if(s)n.push(...s)}if(t){let s=await this.validator.validateConfiguration(e,t);if(!s.isValid)n.push(...s.errors.map((o)=>o.path?`${o.path}: ${o.message}`:o.message))}if(n.length>0)throw Dr.configValidation(i||"unknown",n,i)}checkCache(e,t){let r=this.generateCacheKey(e,t);return us.get(r)||null}cacheResult(e,t,r,i){let n=this.generateCacheKey(e,i);us.set(n,t,void 0,r.ttl)}generateCacheKey(e,t){let r=[e];if(t.alias){let i=Array.isArray(t.alias)?t.alias.join(","):t.alias;r.push(`alias:${i}`)}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(e,t){return Array.from(new Set([e,_e(e,"config"),_e(e,".config"),t?_e(e,t):void 0].filter(Boolean)))}getAllSearchPaths(e,t,r,i){let n=[];return n.push(...this.getLocalSearchPaths(e,t,r,i)),n.push(...this.getHomeSearchPaths(e,t)),n.push(_e(r,"package.json")),n}getLocalSearchPaths(e,t,r,i){let n=this.getLocalDirectories(r,i),s=[];for(let o of n)s.push(...this.fileLoader.generateConfigPaths(e,o,t));return s}getHomeSearchPaths(e,t){if(!e)return[];let r=[_e(br(),".config",e),_e(br(),".config"),br()],i=[];for(let n of r)i.push(...this.fileLoader.generateConfigPaths(e,n,t));return i}async loadConfigWithResult(e){return this.loadConfig(e)}}var Yx=new rd;function ss(e,t,r=!1){let i=new yc,n=e.toUpperCase().replace(/[^A-Z0-9]/g,"_");function s(o,a=[]){let c={...o};for(let[l,f]of Object.entries(o)){let u=[...a,l],h=[`${n}_${u.join("_").toUpperCase()}`,`${n}_${u.map((g)=>g.toUpperCase()).join("")}`,`${n}_${u.map((g)=>g.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],d,p;for(let g of h)if(d=xs.env[g],d!==void 0){p=g;break}if(d!==void 0&&p)if(typeof f==="boolean")c[l]=["true","1","yes"].includes(d.toLowerCase());else if(typeof f==="number"){let g=Number(d);if(!Number.isNaN(g))c[l]=g}else if(Array.isArray(f))try{c[l]=JSON.parse(d)}catch{c[l]=d.split(",").map((g)=>g.trim())}else c[l]=d;else if(f&&typeof f==="object"&&!Array.isArray(f))c[l]=s(f,u)}return c}return s(t)}var Jx=_e(xs.cwd(),"config"),Xx=_e(xs.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",cb={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:vc(wc(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:vc(wc(),".stacks","ssl","stacks.localhost.crt"),keyPath:vc(wc(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var id=cb;import{execSync as pi}from"node:child_process";import{homedir as hb}from"node:os";import{join as db}from"node:path";function lb(e){return(e.includes("=")?e.split("=").pop():e).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function Wt(e){try{return mr(e)}catch{return null}}function bc(e){try{return gr(e)||null}catch{return null}}function Cc(e,t){try{return t.every((r)=>Mn(e,r))}catch{return!1}}function fb(e,t,r=443){return Ln(e,t,r)}function ub(e){let t=[];for(let r of e.split(`
190
+ `)){let i=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(i)t.push(i[1].toUpperCase())}return t}var tt="-d -r trustRoot -p ssl -p basic",St="/Library/Keychains/System.keychain",Sc="rpx.localhost";function yi(){return db(hb(),"Library/Keychains/login.keychain-db")}function $c(){return[St,yi()]}function nd(e,t=Sc){let r=pi(`security find-certificate -a -c "${t}" -Z "${e}" 2>/dev/null || true`,{encoding:"utf8"}),i=[];for(let n of r.split(`
191
+ `)){let s=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(s)i.push(s[1].toUpperCase())}return i}function Rs(e){if(process.platform!=="darwin")return;let t=Wt(e.caPath);if(!t)return;let r=e.commonName??Sc,i=e.keychains??$c();for(let n of i)for(let s of nd(n,r)){if(s===t)continue;try{if(n.startsWith("/Library"))Dt(`security delete-certificate -Z ${s} "${n}"`);else pi(`security delete-certificate -Z ${s} "${n}"`,{stdio:"ignore"});m("ssl",`Removed stale Root CA ${s} from ${n}`,e.verbose)}catch{}}}function wi(e,t,r){if(process.platform!=="darwin")return vi(e,r);try{let n=pi(`security verify-cert -c "${e}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return m("ssl",`verify-cert ${t}: ${n?"trusted":"not trusted"}`,r?.verbose),n}catch{return!1}}function vi(e,t){let r=Wt(e);if(!r)return!1;for(let i of $c())try{let n=pi(`security find-certificate -a -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"});for(let s of n.split(`
192
+ `))if(s.toUpperCase().includes("SHA-256")){if(s.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return m("ssl",`Root CA fingerprint found in ${i}`,t?.verbose),!0}}catch{}return!1}function Ec(e,t){if(process.platform!=="darwin")return!1;let r=t.serverName;Rs({caPath:e,commonName:t.commonName,verbose:t.verbose});let i=yi();try{pi(`security add-trusted-cert ${tt} -k "${i}" "${e}"`,{stdio:"ignore"})}catch{}try{Dt(`security add-trusted-cert ${tt} -k ${St} "${e}"`)}catch{return!1}return wi(e,r,{verbose:t.verbose})||vi(e,{verbose:t.verbose})}var Ot=null,Ac=X(Or(),".stacks","ssl","rpx.localhost.crt");function ud(e,t){return[...new Set(e.filter(Boolean))].map((r)=>({serverName:r,cert:t.cert,key:t.key}))}function hd(e,t,r){let i=X(Or(),".stacks","ssl"),n=[...new Set([t,...e,"rpx.localhost"])];return{https:{certPath:Ac,keyPath:X(i,"rpx.localhost.key"),caCertPath:X(i,"rpx.localhost.ca.crt"),commonName:t},verbose:r,regenerateUntrustedCerts:!0,proxies:n.map((s)=>({from:"localhost:1",to:s,cleanUrls:!1}))}}var mb="rpx-root-ca.crt",gb="rpx-root-ca.key";function bi(e){return{caCertPath:X(e,mb),caKeyPath:X(e,gb)}}function ET(e){return{certPath:X(e,"rpx.localhost.crt"),keyPath:X(e,"rpx.localhost.key"),caCertPath:X(e,"rpx.localhost.ca.crt"),rootCA:bi(e)}}async function pb(e,t){try{let[r,i]=await Promise.all([ee.readFile(e.caCertPath,"utf8"),ee.readFile(e.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!i.includes("PRIVATE KEY-----"))return m("ssl",`Root CA files at ${e.caCertPath} look malformed, will regenerate`,t),null;return{certificate:r,privateKey:i}}catch(r){return m("ssl",`No existing Root CA at ${e.caCertPath} (${r.code||r}), will create one`,t),null}}async function Rc(e,t={}){await ee.mkdir(e,{recursive:!0});let r=bi(e),i=await pb(r,t.verbose);if(i)return m("ssl",`Reusing existing Root CA from ${r.caCertPath}`,t.verbose),{...i,created:!1,paths:r};if(t.verbose)x.info("Generating Root CA certificate (one-time)...");let n=await fi(t.caOptions??{});try{await Promise.all([ee.writeFile(r.caCertPath,n.certificate),ee.writeFile(r.caKeyPath,n.privateKey,{mode:384})]),m("ssl",`Persisted Root CA at ${r.caCertPath}`,t.verbose)}catch(s){throw m("ssl",`Error saving Root CA files: ${s}`,t.verbose),Error(`Failed to save Root CA files: ${s}`)}return{certificate:n.certificate,privateKey:n.privateKey,created:!0,paths:r}}function sd(e){let t=new Set;t.add(e);let r=e.split(".");if(r.length>=3){let i=r[r.length-1],n=r[r.length-2],s=new Set(["co","com","org","net","ac","gov","edu"]);if(!(r.length===3&&i.length===2&&s.has(n)))t.add(`*.${r.slice(1).join(".")}`)}return Array.from(t)}function dd(e){let r=Pc(e).replace(/\*/g,"wildcard"),i=X(Or(),".stacks","ssl"),n=i;if(typeof e?.https==="object")return n=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:i,{caCertPath:e.https.caCertPath||X(n,`${r}.ca.crt`),certPath:e.https.certPath||X(n,`${r}.crt`),keyPath:e.https.keyPath||X(n,`${r}.key`)};return{caCertPath:X(n,`${r}.ca.crt`),certPath:X(n,`${r}.crt`),keyPath:X(n,`${r}.key`)}}function od(e){let t=new Set;if(ks(e))e.proxies.forEach((r)=>{let i=r.to||"rpx.localhost";sd(i).forEach((n)=>t.add(n))});else if(cd(e)){let r=e.to||"rpx.localhost";sd(r).forEach((i)=>t.add(i))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function xT(e){m("ssl","Loading SSL configuration",e.verbose);let t={...id,...e};if(e.https=Dc(t),!e.https?.keyPath&&!e.https?.certPath)return m("ssl","No SSL configuration provided",e.verbose),null;if(e.https?.keyPath&&!e.https?.certPath||!e.https?.keyPath&&e.https?.certPath){let r=!e.https?.keyPath?"keyPath":"certPath";throw m("ssl",`Invalid SSL configuration - missing ${r}`,e.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!e.https?.keyPath||!e.https?.certPath)return null;try{m("ssl","Reading SSL certificate files",e.verbose);let r=await ee.readFile(e.https?.keyPath,"utf8"),i=await ee.readFile(e.https?.certPath,"utf8");return m("ssl","SSL configuration loaded successfully",e.verbose),{key:r,cert:i}}catch(r){return m("ssl",`Failed to read certificates: ${r}`,e.verbose),null}}catch(r){throw m("ssl",`SSL configuration error: ${r}`,e.verbose),r}}async function TT(e,t){if(Ye.platform==="darwin")return yb(e,t);if(Ye.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((i)=>{r(`sudo cp "${e}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(n)=>{if(!n)i(!0);else r(`sudo cp "${e}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(s)=>{i(!s)})})})}catch{return!1}return!1}async function yb(e,t){if(Ye.platform!=="darwin")return!1;let r=t?.serverName??"rpx.localhost",i=t?.verbose??!1;try{if(wi(e,r,{verbose:i}))return m("ssl","Root CA already trusted for SSL, skipping trust operation",i),!0;return m("ssl","Trusting Root CA for browsers (login + system keychains)",i),Ec(e,{serverName:r,verbose:i})}catch{return!1}}async function md(e){if(Ot&&!e.forceRegenerate){m("ssl","Using cached SSL configuration",e.verbose);return}kc();let t=ks(e)?e.proxies.map((u)=>u.to):[e.to];m("ssl",`Generating certificate for domains: ${t.join(", ")}`,e.verbose);let r=Dc(e,e.verbose),i=r.basePath||X(Or(),".stacks","ssl"),n=await Rc(i,{caOptions:r,verbose:e.verbose}),s={certificate:n.certificate,privateKey:n.privateKey},o=n.created,a=n.paths;if(e.verbose)x.info(`Generating host certificate for: ${t.join(", ")}`);let c=await yr({...r,rootCA:{certificate:s.certificate,privateKey:s.privateKey}});try{await Promise.all([ee.writeFile(r.certPath,c.certificate),ee.writeFile(r.keyPath,c.privateKey),ee.writeFile(r.caCertPath,s.certificate)]),m("ssl","Certificate files saved successfully",e.verbose)}catch(u){throw m("ssl",`Error saving certificate files: ${u}`,e.verbose),Error(`Failed to save certificate files: ${u}`)}if(o?!1:await Ns(a.caCertPath,{verbose:e.verbose,regenerateUntrustedCerts:!0})){if(m("ssl","Root CA already trusted, skipping trust store update",e.verbose),e.verbose)x.success("Root CA is already trusted in system trust store");if(Ot={key:c.privateKey,cert:c.certificate,ca:s.certificate},e.verbose)x.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(e.verbose)x.info("Adding certificate to system trust store (may require sudo permission)...");let f=!1;if(Ye.platform==="darwin")try{Rs({caPath:a.caCertPath,verbose:e.verbose});let u=yi();try{xc(`security add-trusted-cert ${tt} -k "${u}" "${a.caCertPath}"`,{stdio:"ignore"})}catch{}if(Dt(`security add-trusted-cert ${tt} -k ${St} "${a.caCertPath}"`),e.verbose)x.success("Successfully added Root CA to system trust store");f=!0;let h=X(i,"trust-rpx-cert.sh"),d=`#!/bin/bash
193
+ echo "Trusting RPX Root CA"
194
+ # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
195
+ # non-interactive. Without it, fall back to a normal sudo prompt.
196
+ if [ -n "$SUDO_PASSWORD" ]
197
+ then
198
+ printf '%s
199
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${tt} -k ${St} "${a.caCertPath}"
200
+ else
201
+ sudo security add-trusted-cert ${tt} -k ${St} "${a.caCertPath}"
202
+ fi
203
+ echo "Root CA trusted! Please restart your browser."
204
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
205
+ `;await ee.writeFile(h,d,{mode:493})}catch(u){if(e.verbose)x.warn(`Could not add Root CA to trust store automatically: ${u}`);let h=X(i,"trust-rpx-cert.sh"),d=`#!/bin/bash
206
+ echo "Trusting RPX Root CA"
207
+ # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
208
+ # non-interactive. Without it, fall back to a normal sudo prompt.
209
+ if [ -n "$SUDO_PASSWORD" ]
210
+ then
211
+ printf '%s
212
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${tt} -k ${St} "${a.caCertPath}"
213
+ else
214
+ sudo security add-trusted-cert ${tt} -k ${St} "${a.caCertPath}"
215
+ fi
216
+ echo "Root CA trusted! Please restart your browser."
217
+ echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
218
+ `;if(await ee.writeFile(h,d,{mode:493}),e.verbose)x.info(`Created a trust helper script at: ${h}`),x.info(`If you're still having certificate issues, run: sh ${h}`)}else if(Ye.platform==="linux")try{let{exec:u}=await import("node:child_process"),h="/usr/local/share/ca-certificates/rpx",d=`
219
+ mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
220
+ cp "${a.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
221
+ update-ca-certificates
222
+ echo "RPX Root CA installed. Please restart your browser."
223
+ `,p=X(Tc.tmpdir(),`rpx-trust-${Date.now()}.sh`);await ee.writeFile(p,d,{mode:493}),await new Promise((g)=>{u(`sudo bash "${p}"`,(y)=>{if(y){if(e.verbose)x.warn(`Could not trust certificates: ${y}`);g(!1)}else{if(e.verbose)x.success("Successfully added certificates to system trust store");g(!0)}})}),await ee.unlink(p).catch(()=>{}),f=!0}catch(u){if(e.verbose)x.warn(`Failed to trust certificates: ${u}`)}else if(Ye.platform==="win32")try{let u=`
224
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${a.caCertPath.replace(/\//g,"\\")}")
225
+ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
226
+ $store.Open("ReadWrite")
227
+ $store.Add($cert)
228
+ $store.Close()
229
+ Write-Host "Root CA trusted successfully!"
230
+ `,h=X(Tc.tmpdir(),"rpx-trust.ps1");if(await ee.writeFile(h,u),xc(`powershell -ExecutionPolicy Bypass -File "${h}"`),e.verbose)x.success("Successfully added certificate to Windows trust store");f=!0}catch(u){if(e.verbose)x.warn(`Could not trust certificate: ${u}`)}else try{await Hn(c,s.certificate,r),f=!0}catch(u){if(e.verbose)x.warn(`Could not add certificate to trust store: ${u}`)}if(Ot={key:c.privateKey,cert:c.certificate,ca:s.certificate},e.verbose)x.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!f&&e.verbose)x.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),x.warn("This will bypass the warning and you should only need to do it once")}function kc(){Ot=null}async function Nc(e){if(!e)return null;if(Ot)return Ot;let t=Dc(e);try{let[r,i,n]=await Promise.all([ee.access(t.keyPath).then(()=>!0).catch(()=>!1),ee.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?ee.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!i)return m("ssl",`Certificate files don't exist: key=${r}, cert=${i}, paths: ${t.keyPath}, ${t.certPath}`,e.verbose),null;let s="regenerateUntrustedCerts"in e,o=e.regenerateUntrustedCerts,a=s?o!==!1:!0;m("ssl",`Trust check: hasFlag=${s}, flagValue=${o}, shouldCheckTrust=${a}`,e.verbose);let c=t.basePath||X(Or(),".stacks","ssl"),l=bi(c);if(!(a?await Ns(l.caCertPath,e):!0))return m("ssl","Root CA exists but is not trusted, will regenerate",e.verbose),null;let[u,h,d]=await Promise.all([ee.readFile(t.keyPath,"utf8"),ee.readFile(t.certPath,"utf8"),n&&t.caCertPath?ee.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(d&&!d.includes("-----BEGIN CERTIFICATE-----"))return m("ssl","Invalid root CA certificate content, will regenerate",e.verbose),null;if(ks(e))try{let{X509Certificate:p}=await import("node:crypto"),y=new p(h).subjectAltName||"",C=e.proxies.map((A)=>A.to).filter((A)=>!y.includes(`DNS:${A}`));if(C.length>0)return m("ssl",`Certificate missing SANs for: ${C.join(", ")}, will regenerate`,e.verbose),null}catch(p){m("ssl",`Could not verify cert SANs: ${p}`,e.verbose)}return m("ssl","Successfully loaded existing certificates",e.verbose),Ot={key:u,cert:h,ca:d},Ot}catch(r){return m("ssl",`Error checking existing certificates: ${r}`,e.verbose),null}}function Dc(e,t){let r=Pc(e);m("ssl",`Primary domain: ${r}`,t);let i=dd(e),n=X(Or(),".stacks","ssl");if(typeof e.https==="object"){let s=e.https.basePath&&e.https.basePath.trim()!==""?e.https.basePath:n,o=e.https.altNameIPs?.filter((c)=>typeof c==="string"&&c.length>0),a={domain:r,hostCertCN:r,basePath:s,caCertPath:e.https.caCertPath||i.caCertPath,certPath:e.https.certPath||i.certPath,keyPath:e.https.keyPath||i.keyPath,altNameIPs:o&&o.length>0?o:["127.0.0.1","::1"],altNameURIs:[],commonName:e.https.commonName||r,organizationName:e.https.organizationName||"Local Development",countryName:e.https.countryName||"US",stateName:e.https.stateName||"California",localityName:e.https.localityName||"Playa Vista",validityDays:e.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(od(e)).map((c)=>({type:2,value:c}))};if(ad(e.https.rootCA))a.rootCA=e.https.rootCA;return a}return{domain:r,hostCertCN:r,basePath:n,...i,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(od(e)).map((s)=>({type:2,value:s}))}}async function PT(e,t){let r=dd({to:e,verbose:t}),i=[r.caCertPath,r.certPath,r.keyPath];m("certificates","Attempting to clean up relating certificates",t),await Promise.all(i.map((n)=>ld(n,t)))}async function Ns(e,t){try{if(m("ssl",`Checking if certificate is trusted: ${e}`,t?.verbose),Ye.platform==="darwin"){if(t?.serverName)return wi(e,t.serverName,{verbose:t?.verbose});return vi(e,{verbose:t?.verbose})}else if(Ye.platform==="win32")try{let r=bc(e)||"";if(!r)return m("ssl","Could not extract certificate subject",t?.verbose),!1;let i=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${r}*' } | Select-Object Subject"`;if(xc(i).toString().includes(r))return m("ssl","Certificate found in trusted root store",t?.verbose),!0;return m("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Windows: ${r}`,t?.verbose),!1}else if(Ye.platform==="linux")try{let r=Wt(e);if(!r)return m("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let i=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let n of i){let s;try{s=await ee.readdir(n)}catch{continue}for(let o of s){let a=Wt(fd.join(n,o));if(a&&a===r)return m("ssl",`Certificate fingerprint found in ${n}`,t?.verbose),!0}}return m("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(r){return m("ssl",`Error checking certificate trust on Linux: ${r}`,t?.verbose),!1}return m("ssl",`Platform ${Ye.platform} not supported for certificate trust check`,t?.verbose),!1}catch(r){return m("ssl",`Error checking if certificate is trusted: ${r}`,t?.verbose),!1}}function wb(e){return{enabled:e?.enabled??!1,path:e?.path??"/",interval:e?.interval??1e4,timeout:e?.timeout??2000,healthyThreshold:e?.healthyThreshold??2,unhealthyThreshold:e?.unhealthyThreshold??3}}function vb(e){return(Array.isArray(e)?e:[e]).map((r)=>{let i=typeof r==="string"?{url:r}:r;return{url:i.url,weight:i.weight&&i.weight>0?i.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function gd(e){return(Array.isArray(e)?e:[e]).map((r)=>typeof r==="string"?r:r.url)}function pd(e){if(!e)return"localhost:5173";let t=Array.isArray(e)?e[0]:e;if(!t)return"localhost:5173";return typeof t==="string"?t:t.url}function yd(e,t){return{upstreams:vb(e),strategy:t?.strategy??"round-robin",healthCheck:wb(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function bb(e){let t=e.upstreams.filter((r)=>r.healthy);if(t.length===0&&e.upstreams.length===1)return e.upstreams;return t}function Cb(e,t){let r=e.cursor%t.length;return e.cursor=(e.cursor+1)%t.length,t[r]}function Sb(e,t){if(e.wrrCurrentWeights.length!==t.length)e.wrrCurrentWeights=t.map(()=>0);let r=t.reduce((n,s)=>n+s.weight,0),i=0;for(let n=0;n<t.length;n++)if(e.wrrCurrentWeights[n]+=t[n].weight,e.wrrCurrentWeights[n]>e.wrrCurrentWeights[i])i=n;return e.wrrCurrentWeights[i]-=r,t[i]}function $b(e){let t=e[0];for(let r=1;r<e.length;r++)if(e[r].activeConnections<t.activeConnections)t=e[r];return t}function wd(e){let t=bb(e);if(t.length===0)return;if(t.length===1)return t[0];switch(e.strategy){case"weighted-round-robin":return Sb(e,t);case"least-connections":return $b(t);case"round-robin":default:return Cb(e,t)}}function Ds(e,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=e.healthCheck.healthyThreshold)t.healthy=!0}function Ci(e,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=e.healthCheck.unhealthyThreshold)t.healthy=!1}function Eb(e){let t=e.lastIndexOf(":");if(t===-1)return{hostname:e,port:80};let r=Number(e.slice(t+1));return{hostname:e.slice(0,t),port:Number.isFinite(r)?r:80}}async function xb(e,t){let{hostname:r,port:i}=Eb(t.url),n=new AbortController,s=setTimeout(()=>n.abort(),e.healthCheck.timeout);try{(await fetch(`http://${r}:${i}${e.healthCheck.path}`,{signal:n.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),Ds(e,t)}catch{Ci(e,t)}finally{clearTimeout(s)}}function vd(e){if(!e.healthCheck.enabled||e.healthCheckTimer||e.upstreams.length<2)return;let t=setInterval(()=>{for(let r of e.upstreams)xb(e,r)},e.healthCheck.interval);t.unref?.(),e.healthCheckTimer=t}function Oc(e){if(e.healthCheckTimer)clearInterval(e.healthCheckTimer),e.healthCheckTimer=null}import{createHash as Cd,timingSafeEqual as bd}from"node:crypto";import{readFileSync as Tb}from"node:fs";var Pb="/.well-known/acme-challenge/";function Si(e,t){let r=Buffer.from(e,"utf8"),i=Buffer.from(t,"utf8");if(r.length!==i.length)return bd(r,r),!1;return bd(r,i)}function Ab(e,t){let r=(h)=>Cd("md5").update(h).digest(),i=Buffer.from(e,"utf8"),n=Buffer.from(t,"utf8"),s=r(Buffer.concat([i,n,i])),o=[i,Buffer.from("$apr1$","utf8"),n];for(let h=i.length;h>0;h-=16)o.push(s.subarray(0,Math.min(h,16)));for(let h=i.length;h>0;h>>=1)o.push(h&1?Buffer.from([0]):i.subarray(0,1));let a=r(Buffer.concat(o));for(let h=0;h<1000;h++){let d=[];if(d.push(h&1?i:a.subarray(0,16)),h%3)d.push(n);if(h%7)d.push(i);d.push(h&1?a.subarray(0,16):i),a=r(Buffer.concat(d))}let c="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",l=(h,d)=>{let p="",g=h;for(let y=0;y<d;y++)p+=c[g&63],g>>=6;return p},f=a,u="";return u+=l(f[0]<<16|f[6]<<8|f[12],4),u+=l(f[1]<<16|f[7]<<8|f[13],4),u+=l(f[2]<<16|f[8]<<8|f[14],4),u+=l(f[3]<<16|f[9]<<8|f[15],4),u+=l(f[4]<<16|f[10]<<8|f[5],4),u+=l(f[11],2),`$apr1$${t}$${u}`}function Rb(e,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(e,t)}catch{return!1}if(t.startsWith("$apr1$")){let i=t.split("$")[2]??"";return Si(Ab(e,i),t)}if(t.startsWith("{SHA}")){let r=Cd("sha1").update(e,"utf8").digest("base64");return Si(`{SHA}${r}`,t)}return Si(e,t)}function kb(e){let t=new Map;for(let r of e.split(`
231
+ `)){let i=r.trim();if(!i||i.startsWith("#"))continue;let n=i.indexOf(":");if(n<=0)continue;t.set(i.slice(0,n),i.slice(n+1))}return t}function Sd(e){if(!e)return;let t=(e.realm??"").trim()||"Restricted",r=[];if(e.username)r.push({username:e.username,password:e.password??""});for(let s of e.users??[])if(s?.username)r.push({username:s.username,password:s.password??""});let i;if(e.htpasswdFile)try{i=kb(Tb(e.htpasswdFile,"utf8"))}catch{i=void 0}if(r.length===0&&(!i||i.size===0))return;return{realm:t,verify:(s,o)=>{let a=!1;for(let c of r)if(Si(s,c.username)&&Si(o,c.password))a=!0;if(i){let c=i.get(s);if(c&&Rb(o,c))a=!0}return a}}}function $d(e,t,r){if(t.startsWith(Pb))return;let i=e.headers.get("authorization")??"",n=i.indexOf(" "),s=n===-1?i:i.slice(0,n),o=n===-1?"":i.slice(n+1).trim();if(s.toLowerCase()==="basic"&&o){let c="";try{c=Buffer.from(o,"base64").toString("utf8")}catch{c=""}let l=c.indexOf(":");if(l>=0&&r.verify(c.slice(0,l),c.slice(l+1)))return}let a=r.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${a}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:Nb}=Bun,$i=Symbol("rpx.pool.fallback"),Os=Symbol("rpx.pool.stale");var Db=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function Ob(e){return Db.has(e.toUpperCase())}var Lc=Symbol("rpx.pool.timeout"),Ht=Symbol("rpx.pool.busy");function Fb(){let e=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(e)&&e>0?e:30000}function Lb(e){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:e*8}function Mb(){let e=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(e)&&e>0?e:0}function Bb(){let e=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(e)&&e>0?e:0}var xd=1048576;function Ib(){let e=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(e)&&e>0?e:256}var Fc=30000,_b=16384,Td=262144,jb=2097152,Ub=524288,Kb=8192,Wb=4096,Hb=new TextEncoder,Pd=new TextDecoder,Vb=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host","x-real-ip"]);class Ad{socket=null;buf=new Uint8Array(_b);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(e){let t=this.socket,r=t.write(e);while(r<e.length){if(this.closed)throw Os;await new Promise((i)=>{this.drainWaiter=i}),r+=t.write(e.subarray(r))}}wakeDrain(){let e=this.drainWaiter;if(e)this.drainWaiter=null,e()}push(e){if(this.bodyQueue){let t=e.length<=this.bodyRemaining?e.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(e.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<e.length)this.appendToBuf(e.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(e),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()>jb)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=Ub)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(e){let t=this.len+e.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(e,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let e=this.waiter;if(e)this.waiter=null,e()}waitForData(e){if(this.len>e||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((e)=>{this.waiter=e})}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 Rd{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=Fb();maxWaiters;checkoutIdleMs=Mb();inUse=new Set;constructor(e,t,r,i=""){this.host=e;this.port=t;this.maxTotal=r;this.key=i;this.maxWaiters=Lb(r)}trackCheckout(e){if(e.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(e),this.ensureSweeper()}dial(){let e=new Ad;return Nb({hostname:this.host,port:this.port,socket:{data:(t,r)=>e.push(r),drain:()=>e.wakeDrain(),close:()=>e.markClosed(),end:()=>e.markClosed(),error:()=>e.markClosed(),connectError:()=>e.markClosed(),timeout:()=>e.markTimedOut()}}).then((t)=>{let r=t;r.setNoDelay?.(!0);let i=Bb();if(i>0)r.timeout?.(i);return e.socket=t,e})}acquireIdleSync(){while(this.idle.length){let e=this.idle.pop();if(!e.closed)return e.socket?.ref(),e.pos=0,e.len=0,this.trackCheckout(e),e;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Ht;let e=await this.waitForSlot();if(e===Ht)throw Ht;if(e)return e.pos=0,e.len=0,this.trackCheckout(e),e}this.open++;try{let e=await this.dial();return this.trackCheckout(e),e}catch(e){throw this.open--,this.wakeWaiter(),e}}waitForSlot(){return new Promise((e)=>{let t=!1,r=(s)=>{if(t)return;t=!0,clearTimeout(n),e(s)},i=(s)=>r(s),n=setTimeout(()=>{let s=this.waiters.indexOf(i);if(s!==-1)this.waiters.splice(s,1);r(Ht)},this.queueWaitMs);n.unref?.(),this.waiters.push(i)})}release(e){if(this.inUse.delete(e),e.closed){this.open--,this.wakeWaiter();return}e.clearStreaming(),e.compact(),e.fresh=!1;let t=this.waiters.shift();if(t){e.socket?.ref(),this.trackCheckout(e),t(e);return}e.idleSince=Date.now(),e.socket?.unref(),this.idle.push(e),this.ensureSweeper()}destroy(e){this.inUse.delete(e),e.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let e=this.waiters.shift();if(e)e(null)}ensureSweeper(){if(this.sweeper)return;let e=this.checkoutIdleMs>0?Math.min(Fc,this.checkoutIdleMs):Fc;this.sweeper=setInterval(()=>this.sweep(),e),this.sweeper.unref?.()}sweep(){let e=Date.now(),t=e-Fc;if(this.idle.length){let r=[];for(let i of this.idle)if(i.closed||i.idleSince<=t)i.destroy(),this.open--;else r.push(i);this.idle=r}if(this.checkoutIdleMs>0&&this.inUse.size){let r=e-this.checkoutIdleMs;for(let i of this.inUse)if(!i.closed&&i.lastActivityAt>0&&i.lastActivityAt<=r)i.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&Fs.get(this.key)===this)Fs.delete(this.key)}}}var Fs=new Map;function zb(e,t){let r=Fs.get(e);if(!r){let i=e.lastIndexOf(":"),n=i===-1?e:e.slice(0,i),s=i===-1?80:Number(e.slice(i+1));r=new Rd(n,s,t??Ib(),e),Fs.set(e,r)}return r}function Ed(e,t,r){for(let i=r+3;i<t;i++)if(e[i]===10&&e[i-1]===13&&e[i-2]===10&&e[i-3]===13)return i-3;return-1}function Gb(e,t,r){let i=Pd.decode(e.subarray(t,r)),n=i.indexOf(`\r
232
+ `),s=n===-1?i:i.slice(0,n),o=s.indexOf(" "),a=Number.parseInt(s.slice(o+1,o+5),10),c=s.startsWith("HTTP/1.0"),l=[],f=-1,u=!1,h=c,d=!1,p=!1,g=n===-1?i.length:n+2;while(g<i.length){let y=i.indexOf(`\r
233
+ `,g);if(y===-1)y=i.length;let w=i.slice(g,y);if(g=y+2,w==="")continue;let C=w.indexOf(":");if(C===-1)continue;let A=w.slice(0,C),T=w.slice(C+1).trim(),P=A.charCodeAt(0)|32;if(P===99||P===116||P===107){let D=A.toLowerCase();if(D==="content-length"){let N=/^\d+$/.test(T)?Number(T):Number.NaN;if(!Number.isSafeInteger(N)||f>=0&&f!==N)p=!0;else f=N;continue}if(D==="transfer-encoding"){if(T.toLowerCase().includes("chunked"))u=!0;continue}if(D==="connection"){let N=T.toLowerCase();if(N.includes("close"))h=!0;if(N.includes("keep-alive"))d=!0;continue}if(D==="keep-alive")continue}l.push([A,T])}if(c&&d)h=!1;if(u&&f>=0)f=-1;return{status:a,headerEnd:r,headers:l,contentLength:f,chunked:u,closeConn:h,malformed:p}}function qb(e,t){return t||e===204||e===304}async function kd(e){let{hostPort:t,method:r,path:i,reqHeaders:n,forwardedHost:s,clientIp:o,originOverride:a,body:c}=e,l=r==="HEAD",f=n.get("accept")?.toLowerCase()??"";if(n.get("expect")||n.get("upgrade")||f.includes("text/event-stream"))throw $i;let u=null;if(c){let g=n.get("content-length"),y=g?Number.parseInt(g,10):Number.NaN;if(Number.isNaN(y)||y>xd)throw $i;if(u=await tC(c),u===null)throw $i}let h=eC(r,i,n,t,s,o,a,u),d=h;if(u&&u.length)d=new Uint8Array(h.length+u.length),d.set(h),d.set(u,h.length);let p=zb(t,e.maxPerHost);for(let g=0;;g++){if(g>0)await new Promise((w)=>{setTimeout(w,g)});let y;try{y=p.acquireIdleSync()??await p.acquireOrDial()}catch(w){if(w!==Ht&&g<4)continue;throw w}try{let w=y.socket.write(d);if(w<d.length)await y.writeAll(d.subarray(w));return await Jb(p,y,l,e.signal)}catch(w){let C=w===Os&&g<4&&(y.fresh||Ob(r));if(p.destroy(y),C)continue;if(w===Os)throw Error("upstream closed connection");throw w}}}async function Yb(e){let t=Ed(e.buf,e.len,e.pos);while(t===-1){if(e.closed){if(e.timedOut)throw Lc;if(e.len===e.pos)throw Os;throw Error("upstream closed mid-header")}if(e.len-e.pos>Td)throw Error("upstream header block too large");await e.waitForData(e.len),t=Ed(e.buf,e.len,e.pos)}return t}async function Jb(e,t,r,i){let n;for(;;){let o=await Yb(t);if(n=Gb(t.buf,t.pos,o),t.pos=o+4,n.status>=100&&n.status<200)continue;break}if(n.malformed)throw e.destroy(t),Error("upstream sent malformed response framing");let s=n.headers;if(qb(n.status,r))return Nd(e,t,n.closeConn),new Response(null,{status:n.status,headers:s});if(n.chunked)return new Response(Qb(e,t,n.closeConn,i),{status:n.status,headers:s});if(n.contentLength>=0){if(t.len-t.pos>=n.contentLength){let a=t.pos+n.contentLength,c=t.len>a,l=null;if(n.contentLength>=Kb)l=t.buf.subarray(t.pos,a),t.buf=new Uint8Array(Wb);else if(n.contentLength>0)l=t.buf.slice(t.pos,a);if(t.pos=0,t.len=0,n.closeConn||c)e.destroy(t);else e.release(t);return new Response(l,{status:n.status,headers:s})}return new Response(Xb(e,t,n.contentLength,n.closeConn),{status:n.status,headers:s})}return new Response(Zb(t),{status:n.status,headers:s})}function Nd(e,t,r){if(r||t.pos!==t.len)e.destroy(t);else e.release(t)}function Xb(e,t,r,i){let n=t.len-t.pos,s=n>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=r-n,t.queuedBytes=0,t.streamingBody=!0;let o=(a)=>{if(t.bodyQueue=null,i||t.len>0)e.destroy(t);else e.release(t);a.close()};return new ReadableStream({start(a){if(s)a.enqueue(s);if(t.bodyRemaining===0&&t.bodyQueue.length===0)o(a)},async pull(a){for(;;){let c=t.bodyQueue;if(c&&c.length>0){let l=c.shift();if(t.queuedBytes-=l.length,t.resumeIfDrained(),a.enqueue(l),t.bodyRemaining===0&&c.length===0)o(a);return}if(t.bodyRemaining===0){if(t.bodyQueue)o(a);return}if(t.closed){t.bodyQueue=null,e.destroy(t),a.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,e.destroy(t)}})}function Zb(e){return e.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(e.len>e.pos){t.enqueue(e.buf.slice(e.pos,e.len)),e.pos=e.len,e.resumeIfDrained();return}if(e.closed){e.destroy(),t.close();return}await e.waitForData(e.len)}},cancel(){e.destroy()}})}function Qb(e,t,r,i){t.streamingBody=!0;let n=0,s=!1,o=!1,a,c=()=>i?.removeEventListener("abort",l),l=()=>{if(o)return;o=!0,e.destroy(t);try{a?.close()}catch{}};async function f(u=!1){for(;;){for(let h=t.pos;h+1<t.len;h++)if(t.buf[h]===13&&t.buf[h+1]===10){let d=Pd.decode(t.buf.subarray(t.pos,h));return t.pos=h+2,d}if(t.closed){if(u&&t.pos===t.len)return null;throw Error("upstream closed mid-chunk-header")}if(t.len-t.pos>Td)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({start(u){if(a=u,i?.aborted)l();else i?.addEventListener("abort",l,{once:!0})},async pull(u){try{for(;;){if(n>0){if(t.len===t.pos){if(t.closed){e.destroy(t),u.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let g=Math.min(n,t.len-t.pos);if(u.enqueue(t.buf.slice(t.pos,t.pos+g)),t.pos+=g,n-=g,t.resumeIfDrained(),n===0)s=!0;return}if(s)await f(),s=!1;let h=await f(!0);if(h===null){e.destroy(t),c(),u.close();return}let d=h.indexOf(";"),p=Number.parseInt(d===-1?h:h.slice(0,d),16);if(!Number.isInteger(p)||p<0){e.destroy(t),u.error(Error("upstream sent malformed chunk size"));return}if(p===0){for(;;)if(await f()==="")break;Nd(e,t,r),c(),u.close();return}n=p}}catch(h){if(e.destroy(t),c(),!o)u.error(h)}},cancel(){o=!0,c(),e.destroy(t)}})}function eC(e,t,r,i,n,s,o,a){let c=s||"127.0.0.1",l=`${e} ${t} HTTP/1.1\r
234
+ host: ${i}\r
235
+ x-forwarded-for: ${c}\r
236
+ x-real-ip: ${c}\r
237
+ x-forwarded-proto: https\r
238
+ x-forwarded-host: ${n}\r
239
+ `;if(o!==void 0)l+=`origin: ${o}\r
240
+ `;let f=!1;for(let[u,h]of r){let d=u.toLowerCase();if(Vb.has(d))continue;if(o!==void 0&&d==="origin")continue;if(d==="content-length")f=!0;l+=`${u}: ${h}\r
241
+ `}if(l+=`connection: keep-alive\r
242
+ `,a&&!f)l+=`content-length: ${a.length}\r
243
+ `;return l+=`\r
244
+ `,Hb.encode(l)}async function tC(e){let t=e.getReader(),r=[],i=0;for(;;){let{done:o,value:a}=await t.read();if(o)break;if(a){if(i+=a.length,i>xd)return t.cancel().catch(()=>{}),null;r.push(a)}}if(r.length===1)return r[0];let n=new Uint8Array(i),s=0;for(let o of r)n.set(o,s),s+=o.length;return n}function MT(e){let t=typeof e==="string"?{to:e}:e,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 Dd(e,t,r){if(!e.preservePath)return e.to||"/";let i=`${t}${r}`;return i==="/"?`${e.to}/`:`${e.to}${i}`}import*as Ke from"node:path";function Od(e,t){if(typeof e==="string")return{dir:e,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:e.dir,spa:e.spa??!1,pathRewriteStyle:e.pathRewriteStyle??"directory",maxAge:e.maxAge??0,cleanUrls:t}}var rC={".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 iC(e){let t=Ke.extname(e).toLowerCase();return rC[t]??"application/octet-stream"}function nC(e){let t;try{t=decodeURIComponent(e)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let r=Ke.posix.normalize(`/${t}`);if(r.split("/").includes(".."))return null;return r.replace(/^\/+/,"")}function sC(e,t){let r=nC(e);if(r===null)return null;let i=Ke.posix.extname(r);if(t.cleanUrls&&i===".html"){let n=e.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ke.join(t.dir,r),redirectTo:n||"/"}}if(r===""||e.endsWith("/"))return{filePath:Ke.join(t.dir,r,"index.html")};if(i!=="")return{filePath:Ke.join(t.dir,r)};if(t.pathRewriteStyle==="flat")return{filePath:Ke.join(t.dir,`${r}.html`)};return{filePath:Ke.join(t.dir,r,"index.html")}}async function Fd(e,t){let r=sC(e,t);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let i=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",n=Bun.file(r.filePath);if(await n.exists())return new Response(n,{status:200,headers:{"Content-Type":iC(r.filePath),"Cache-Control":i}});if(t.spa){let s=Ke.join(t.dir,"index.html"),o=Bun.file(s);if(await o.exists())return new Response(o,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var Mc="127.0.0.1";function oC(e,t){let r;try{r=t?.requestIP?.(e)?.address}catch{return Mc}if(!r)return Mc;return/^[0-9a-f.:]{1,45}$/i.test(r)?r:Mc}function aC(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var cC=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]),lC=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],fC=1024;function uC(e){if(!e)return!1;let t=null;for(let r of e.split(",")){let[i,...n]=r.trim().split(";"),s=i.trim().toLowerCase();if(s!=="gzip"&&s!=="*")continue;let o=1;for(let a of n){let c=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(a);if(c)o=Number.parseFloat(c[1])}if(s==="gzip")return Number.isFinite(o)&&o>0;t=o}return t!==null&&Number.isFinite(t)&&t>0}function hC(e){let t=e.get("vary");if(!t){e.set("vary","Accept-Encoding");return}if(!t.split(",").some((r)=>r.trim().toLowerCase()==="accept-encoding"))e.set("vary",`${t}, Accept-Encoding`)}function dC(e,t){if(e.method==="HEAD"||t.status===204||t.status===206||t.status===304||!t.body||t.headers.has("content-encoding")||t.headers.get("cache-control")?.toLowerCase().includes("no-transform")||e.headers.has("range")||!uC(e.headers.get("accept-encoding")))return t;let r=t.headers.get("content-type")?.toLowerCase()??"";if(!lC.some((s)=>r.startsWith(s)))return t;let i=t.headers.get("content-length");if(i!==null){let s=Number.parseInt(i,10);if(Number.isFinite(s)&&s<fC)return t}let n=new Headers(t.headers);return n.set("content-encoding","gzip"),hC(n),n.delete("content-length"),n.delete("content-md5"),n.delete("content-digest"),n.delete("accept-ranges"),n.delete("etag"),new Response(t.body.pipeThrough(new CompressionStream("gzip")),{status:t.status,statusText:t.statusText,headers:n})}function mC(e){let t=e.headers.get("host")||"",r=t.indexOf(":");return r===-1?t:t.slice(0,r)}function Id(e,t){if(!t||t==="/")return e;if(e===t)return"/";if(e.startsWith(`${t}/`)){let r=e.slice(t.length);return r===""?"/":r}return e}function Ld(e){if(e.upstreamPool)return wd(e.upstreamPool);if(e.sourceHost)return{url:e.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function Md(e,t,r,i){let n=r?.url??t.sourceHost??"",o=t.stripBasePathPrefix??!1?Id(e,t.basePath):e,a=Bd(o,t.pathRewrites);if(a)n=a.targetHost,o=a.targetPath,m("request",`Path rewrite: ${e} → ${n}${o}`,i);return{targetHost:n,targetPath:o}}function gC(e){let t=e.indexOf("://"),r=t===-1?e.indexOf("/"):e.indexOf("/",t+3);if(r===-1)return{pathname:"/",search:""};let i=e.indexOf("?",r);if(i===-1)return{pathname:e.slice(r),search:""};return{pathname:e.slice(r,i),search:e.slice(i)}}function Bc(e,t,r){let i=async(n,s)=>{let{pathname:o,search:a}=gC(n.url),c=mC(n),l=oC(n,s),f=e(c,o);if(!f&&r){let w=await r(c,o,n);if(w instanceof Response)return w;if(w&&w.retry)f=e(c,o)}if(!f)return m("request",`No route found for host: ${c}`,t),new Response(`No proxy configured for ${c}`,{status:404});if(f.auth){let w=$d(n,o,f.auth);if(w)return m("request",`401 challenge for ${c}${o}`,t),w}if(f.redirect){let w=Dd(f.redirect,o,a);return m("request",`${f.redirect.status} redirect ${c}${o} → ${w}`,t),new Response(null,{status:f.redirect.status,headers:{location:w}})}if(f.static){let C=f.stripBasePathPrefix??!0?Id(o,f.basePath):o;return Fd(C,f.static)}if(n.headers.get("upgrade")?.toLowerCase()==="websocket"){let w=Ld(f);if(!s||!w)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:C,targetPath:A}=Md(o,f,w,t),T=`ws://${C}${A}${a}`,P={};for(let[ae,J]of n.headers)if(!cC.has(ae.toLowerCase())&&ae.toLowerCase()!=="host")P[ae]=J;P.host=C,P["x-forwarded-for"]=l,P["x-real-ip"]=l,P["x-forwarded-proto"]="https",P["x-forwarded-host"]=c;let D={targetUrl:T,forwardHeaders:P};if(s.upgrade(n,{data:D})){m("ws",`upgraded ${c}${A} → ${T}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let u=Ld(f);if(!u)return new Response(`No upstream configured for ${c}`,{status:502});if(f.cleanUrls&&o.endsWith(".html")){let w=o.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:w}})}let{targetHost:h,targetPath:d}=Md(o,f,u,t),p=f.changeOrigin?`http://${h}`:void 0,g=n.body!=null&&n.method!=="GET"&&n.method!=="HEAD",y=f.upstreamPool;if(y)u.activeConnections++;try{let w=await kd({hostPort:h,method:n.method,path:`${d}${a}`,reqHeaders:n.headers,forwardedHost:c,clientIp:l,originOverride:p,body:n.body,signal:n.signal});if(y)Ds(y,u);return w}catch(w){if(w===Lc){if(m("request",`Upstream timeout for ${c}`,t),y)Ci(y,u);return new Response("Gateway Timeout",{status:504})}if(w===Ht)return m("request",`Upstream pool saturated for ${c}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(w===$i||!g)try{let C=new Headers(n.headers);if(C.set("host",h),C.set("x-forwarded-for",l),C.set("x-real-ip",l),C.set("x-forwarded-proto","https"),C.set("x-forwarded-host",c),p!==void 0)C.set("origin",p);let A=await fetch(`http://${h}${d}${a}`,{method:n.method,headers:C,body:n.body,redirect:"manual"});if(y)Ds(y,u);return A}catch(C){if(m("request",`Proxy error for ${c}: ${C}`,t),y)Ci(y,u);return new Response(`Proxy Error: ${C}`,{status:502})}if(m("request",`Proxy error for ${c}: ${w}`,t),y)Ci(y,u);return new Response(`Proxy Error: ${w}`,{status:502})}finally{if(y)u.activeConnections--}};return async(n,s)=>{try{let o=await i(n,s);return o?dC(n,o):o}catch(o){return m("request",`Unhandled proxy handler error: ${o}`,t),new Response("Bad Gateway",{status:502})}}}function Ic(e){let t=new WeakMap,r=aC();return{open(i){let{targetUrl:n,forwardHeaders:s}=i.data,o;try{o=new WebSocket(n,{headers:s})}catch(c){m("ws",`failed to open upstream ${n}: ${c}`,e),i.close(1011,"upstream connect failed");return}o.binaryType="arraybuffer";let a={upstream:o,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(i,a),o.addEventListener("open",()=>{a.upstreamOpen=!0;for(let c of a.pending)o.send(c);a.pending=[],a.pendingBytes=0}),o.addEventListener("message",(c)=>{i.send(c.data)}),o.addEventListener("close",(c)=>{try{i.close(c.code||1000,c.reason||"")}catch{}}),o.addEventListener("error",()=>{m("ws",`upstream error for ${n}`,e);try{i.close(1011,"upstream error")}catch{}})},message(i,n){let s=t.get(i);if(!s)return;let o=typeof n==="string"?n:new Uint8Array(n);if(s.upstreamOpen){s.upstream.send(o);return}let a=typeof o==="string"?Buffer.byteLength(o):o.byteLength;if(s.pendingBytes+a>r){m("ws",`pending buffer would exceed ${r}B before upstream open; closing socket`,e);try{i.close(1009,"buffer limit")}catch{}try{s.upstream.close(1011,"client buffer overflow")}catch{}t.delete(i);return}s.pending.push(o),s.pendingBytes+=a},close(i,n,s){let o=t.get(i);if(!o)return;t.delete(i);try{o.upstream.close(n||1000,s||"")}catch{}}}}import*as jd from"node:fs";import*as Ud from"node:path";var _d="/.well-known/acme-challenge/";function Kd(e,t){if(!e||!t.startsWith(_d))return null;let r=t.slice(_d.length);if(!r||!/^[A-Za-z0-9_-]+$/.test(r))return null;try{return jd.readFileSync(Ud.join(e,r),"utf8")}catch{return null}}function Ls(e){return e.startsWith("*.")}function _c(e,t){if(!Ls(t))return!1;let r=t.slice(1);return e.length>r.length&&e.endsWith(r)}function Wd(e,t){let r=e.get(t);if(r!==void 0)return r;let i,n=-1;for(let[s,o]of e){if(!Ls(s))continue;if(_c(t,s)){let a=s.length-1;if(a>n)n=a,i=o}}return i}function Vt(e){if(!e||e==="/")return"/";let t=e.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function pC(e,t){if(t==="/")return!0;if(e===t)return!0;return e.startsWith(`${t}/`)}function jc(e){let t=new Map;for(let i of e){let n=Vt(i.path),s=t.get(i.host);if(!s)s=new Map,t.set(i.host,s);s.set(n,i.route)}let r=new Map;for(let[i,n]of t){let s=[];for(let[o,a]of n)s.push({path:o,route:a});s.sort((o,a)=>a.path.length-o.path.length),r.set(i,s)}return r}function Uc(e,t){let r=e.get(t);if(r!==void 0)return r;let i,n=-1;for(let[s,o]of e){if(!Ls(s))continue;if(_c(t,s)){let a=s.length-1;if(a>n)n=a,i=o}}return i}function Kc(e,t,r){let i=Uc(e,t);if(!i)return;for(let n of i)if(pC(r,n.path))return n.route;return}import*as Ei from"node:fs/promises";import*as Wc from"node:path";var Hd=256;function Ms(e,t=Hd,r){let i=Number.isFinite(t)&&t>0?Math.floor(t):Hd;if(e.length<=i)return e;let n=e.slice(0,i),s=e.slice(i).map((o)=>o.serverName);return x.warn(`rpx: ${e.length} TLS contexts exceed maxTlsContexts=${i}; keeping the first ${i} and dropping ${s.length} host(s): ${s.join(", ")}`),m("sni",`capped SNI set to ${i} of ${e.length}`,r),n}function Hc(e){let r=Ms(e.sni,e.maxTlsContexts,e.verbose).map((n)=>({serverName:n.serverName,cert:n.cert,key:n.key})),i=e.defaultTls?[{cert:e.defaultTls.cert,key:e.defaultTls.key},...r]:r;return Bs(i)}function Bs(e){if(Array.isArray(e))return e.map((t)=>({...t,lowMemoryMode:!0}));return{...e,lowMemoryMode:!0}}function yC(e){if(!e.endsWith(".crt"))return null;let t=e.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function wC(e,t,r,i){try{let[n,s]=await Promise.all([Ei.readFile(t,"utf8"),Ei.readFile(r,"utf8")]);return{serverName:e,cert:n,key:s}}catch(n){return m("sni",`skipping ${e}: ${n.message}`,i),null}}async function Vc(e,t){let r=new Map,i=e.certsDirServerNames?new Set(e.certsDirServerNames):void 0;if(e.certsDir){let s=[];try{s=await Ei.readdir(e.certsDir)}catch(o){m("sni",`certsDir read failed (${e.certsDir}): ${o.message}`,t)}for(let o of s){let a=yC(o);if(!a)continue;if(i&&!i.has(a))continue;let c=o.slice(0,-4);r.set(a,{certPath:Wc.join(e.certsDir,o),keyPath:Wc.join(e.certsDir,`${c}.key`)})}}if(e.domains)for(let[s,o]of Object.entries(e.domains))r.set(s,o);let n=[];for(let[s,o]of r){let a=await wC(s,o.certPath,o.keyPath,t);if(a)n.push(a)}return n}import{X509Certificate as qc,createPrivateKey as CC}from"node:crypto";import*as xi from"node:fs/promises";import{isIP as Yc}from"node:net";import*as Ti from"node:path";import*as Je from"node:fs/promises";import*as Is from"node:path";function zc(e=process.env){let t=e.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if(t==="restart"||t==="rebind")return t;return e.INVOCATION_ID?"restart":"rebind"}var vC="acme-account.key",bC=60000,Vd=4096;function Gc(e,t){if(!t||t.length===0)return!1;return t.some((r)=>{let i=r.startsWith(".")?r.slice(1):r;return e===i||e.endsWith(`.${i}`)})}function zd(e){if(!e||e.length>253)return!1;if(e.includes("/")||e.includes(":")||e.includes(" "))return!1;if(e.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)}class _s{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(e){this.config=e.config,this.certsDir=e.certsDir,this.onCertAdded=e.onCertAdded,this.http01Store=e.http01Store??ai,this.issuer=e.issuer??Pn,this.verbose=e.verbose??!1,this.negativeCacheMs=e.negativeCacheMs??bC;for(let t of e.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(e){return this.certs.has(e)}async isApproved(e){if(!zd(e))return!1;if(Gc(e,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(e)}catch(t){return m("on-demand",`ask(${e}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(e){if(!this.config.enabled)return!1;if(this.certs.has(e))return!0;if(!zd(e))return!1;let t=this.inFlight.get(e);if(t)return t;let r=this.negativeCache.get(e);if(r!==void 0&&Date.now()<r){if(await this.loadFromDisk(e))return this.negativeCache.delete(e),!0;return m("on-demand",`${e} negatively cached for ${r-Date.now()}ms`,this.verbose),!1}let i=this.issue(e).finally(()=>{this.inFlight.delete(e)});return this.inFlight.set(e,i),i}async issue(e){if(this.certs.has(e))return!0;if(await this.loadFromDisk(e))return!0;if(!await this.isApproved(e))return m("on-demand",`refused issuance for ${e} (not approved)`,this.verbose),this.cacheNegative(e),!1;try{m("on-demand",`issuing cert for ${e} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let t=await this.issuer({domains:[e],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey(t.accountKeyPem),await this.persist(e,t.fullChainPem,t.keyPem);let r={serverName:e,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(e,r),this.negativeCache.delete(e),m("on-demand",`issued + installed cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(e),m("on-demand",`issuance for ${e} failed: ${t.message}`,this.verbose),!1}}cacheNegative(e){if(this.negativeCache.size>=Vd){let t=Date.now();for(let[r,i]of this.negativeCache)if(i<=t)this.negativeCache.delete(r);if(this.negativeCache.size>=Vd){let r=this.negativeCache.keys().next().value;if(r!==void 0)this.negativeCache.delete(r)}}this.negativeCache.set(e,Date.now()+this.negativeCacheMs)}async loadFromDisk(e){let{certPath:t,keyPath:r}=this.pathsFor(e);try{let[i,n]=await Promise.all([Je.readFile(t,"utf8"),Je.readFile(r,"utf8")]),s={serverName:e,cert:i,key:n};return this.certs.set(e,s),m("on-demand",`adopted existing on-disk cert for ${e}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(e){return{certPath:Is.join(this.certsDir,`${e}.crt`),keyPath:Is.join(this.certsDir,`${e}.key`)}}async persist(e,t,r){await Je.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:i,keyPath:n}=this.pathsFor(e);await Promise.all([Je.writeFile(i,t,"utf8"),Je.writeFile(n,r,{encoding:"utf8",mode:384})])}get accountKeyPath(){return Is.join(this.certsDir,vC)}async loadAccountKey(){try{return await Je.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(e){if(!e||this.accountKeyPem===e)return;this.accountKeyPem=e,await Je.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Je.writeFile(this.accountKeyPath,e,{encoding:"utf8",mode:384}).catch(()=>{})}}var SC="rpx-local-host.crt",$C="rpx-local-host.key",EC="rpx Local CA",xC=825,TC=30,PC=86400000;function AC(e){let t=bi(e);return{caCertPath:t.caCertPath,caKeyPath:t.caKeyPath,certPath:Ti.join(e,SC),keyPath:Ti.join(e,$C)}}function Jc(e,t){if(!e||typeof e.dir!=="string"||e.dir.trim()==="")throw Error("localCa.dir is required");let r=[...new Set((e.hosts??[]).map((o)=>String(o).trim().toLowerCase()).filter(Boolean))];if(r.length===0)throw Error("localCa.hosts must name at least one host");for(let o of r)if(o.startsWith("*")||o.includes("/")||o.includes(":")||o.includes(" ")||Yc(o)!==0)throw Error(`localCa.hosts entry ${JSON.stringify(o)} is not a hostname (wildcards are not supported; put IP addresses in localCa.ips)`);let i=[...new Set((e.ips??[]).map((o)=>String(o).trim()).filter(Boolean))];for(let o of i)if(Yc(o)===0)throw Error(`localCa.ips entry ${JSON.stringify(o)} is not an IP address`);if(t?.enabled){let o=r.filter((a)=>Gc(a,t.allowedSuffixes));if(o.length>0)throw Error(`localCa.hosts and onDemandTls.allowedSuffixes overlap on ${o.join(", ")}; a host is either LAN-only (local CA) or public (ACME), never both`)}let n=e.validityDays??xC,s=e.renewBeforeDays??TC;if(!(n>0))throw Error("localCa.validityDays must be a positive number of days");if(!(s>=0)||s>=n)throw Error("localCa.renewBeforeDays must be between 0 and localCa.validityDays");return{dir:e.dir,hosts:r,ips:i,installTrust:e.installTrust===!0,validityDays:n,renewBeforeDays:s}}function qd(e){let t=Yc(e);if(t===4)return e;if(t!==6)return e.toLowerCase();let r=[],i=[],[n,s]=e.split("::");r=n?n.split(":"):[],i=s?s.split(":"):[];let o=(l)=>l.flatMap((f)=>{if(!f.includes("."))return[f];let u=f.split(".").map((h)=>Number.parseInt(h,10));return[(u[0]<<8|u[1]).toString(16),(u[2]<<8|u[3]).toString(16)]});r=o(r),i=o(i);let a=e.includes("::")?8-r.length-i.length:0;return[...r,...Array.from({length:Math.max(0,a)},()=>"0"),...i].map((l)=>Number.parseInt(l||"0",16).toString(16)).join(":")}function RC(e){let t=new Set,r=new Set;for(let i of(e??"").split(",")){let n=i.trim();if(n.startsWith("DNS:"))t.add(n.slice(4).toLowerCase());else if(n.startsWith("IP Address:"))r.add(qd(n.slice(11)))}return{dns:t,ips:r}}function kC(e,t,r=new Date){let i,n;try{i=new qc(e.cert),n=new qc(e.caCert)}catch(h){return`unreadable certificate (${h.message})`}try{if(!i.checkPrivateKey(CC(e.key)))return"private key does not match the certificate"}catch(h){return`unreadable private key (${h.message})`}let s=!1;try{s=i.verify(n.publicKey)}catch{s=!1}if(!s)return"not issued by the current Root CA";let o=RC(i.subjectAltName),a=t.hosts.filter((h)=>!o.dns.has(h));if(a.length>0)return`missing DNS SAN(s): ${a.join(", ")}`;let c=t.ips.filter((h)=>!o.ips.has(qd(h)));if(c.length>0)return`missing IP SAN(s): ${c.join(", ")}`;let l=new Date(i.validTo).getTime(),f=new Date(i.validFrom).getTime();if(Number.isNaN(l)||Number.isNaN(f))return"unreadable validity period";if(f>r.getTime())return"not valid yet";let u=(l-r.getTime())/PC;if(u<t.renewBeforeDays)return u<=0?"expired":`${Math.floor(u)} day(s) left, under renewBeforeDays=${t.renewBeforeDays}`;return null}async function NC(e,t){let r=Reflect.get(ka,"isCertTrusted");if(typeof r==="function")try{return await r(e,{verbose:t})}catch(i){m("local-ca",`tlsx isCertTrusted failed (${i.message}); using rpx's own check`,t)}return Ns(e,{verbose:t,regenerateUntrustedCerts:!0})}async function DC(e,t){if(await NC(e.caCertPath,t))return m("local-ca",`Root CA ${e.caCertPath} already trusted; skipping installCA`,t),{alreadyTrusted:!0,installed:!1};try{let r=await Vn({basePath:Ti.dirname(e.caCertPath),caCertPath:e.caCertPath,verbose:t});if(t)x.success(`Root CA ${r.alreadyTrusted?"already trusted":"installed"} in the system trust store (${e.caCertPath})`);return{alreadyTrusted:r.alreadyTrusted,installed:r.trustInstalled}}catch(r){return x.warn(`rpx: could not install the local Root CA into the system trust store: ${r.message}`),x.warn(`rpx: trust it manually: ${e.caCertPath}`),{alreadyTrusted:!1,installed:!1}}}async function Gd(e){try{return await xi.readFile(e,"utf8")}catch{return null}}async function Xc(e,t={}){let r=t.verbose,i=Jc(e,t.onDemandTls),n=t.now??(()=>new Date),s=AC(i.dir),o=await Rc(i.dir,{verbose:r,caOptions:{commonName:EC,organization:"rpx",verbose:r}});if(o.created&&r)x.info(`Created local Root CA at ${s.caCertPath}`);let[a,c]=await Promise.all([Gd(s.certPath),Gd(s.keyPath)]),l;if(a&&c)l=kC({cert:a,key:c,caCert:o.certificate},i,n());else l="no leaf on disk";let f,u;if(l===null&&a&&c)f=a,u=c,m("local-ca",`reusing leaf ${s.certPath}`,r);else{m("local-ca",`minting leaf for ${[...i.hosts,...i.ips].join(", ")} (${l})`,r);let p={domain:i.hosts[0],domains:i.hosts,altNameIPs:i.ips,commonName:i.hosts[0],organizationName:"rpx",validityDays:i.validityDays,rootCA:{certificate:o.certificate,privateKey:o.privateKey},verbose:r},g=await yr(p);if(f=g.certificate,u=g.privateKey,await xi.writeFile(s.keyPath,u,{mode:384}),await xi.writeFile(s.certPath,f),r)x.success(`Minted local certificate for ${[...i.hosts,...i.ips].join(", ")} (${l})`)}let h=new Date(new qc(f).validTo),d={paths:s,caCert:o.certificate,cert:f,key:u,caCreated:o.created,leafMinted:l!==null,renewalReason:l,notAfter:h,entries:i.hosts.map((p)=>({serverName:p,cert:f,key:u})),defaultTls:{cert:f,key:u}};if(i.installTrust)d.trust=await DC(s,r);return d}import{existsSync as OC,readdirSync as FC,readFileSync as LC,statSync as MC}from"node:fs";import{homedir as Xd}from"node:os";import{isAbsolute as BC,join as Fr}from"node:path";var Zd=["~/Code"],Qd=["localhost","test"],IC=1800000,Zc={dirExists:(e)=>{try{return MC(e).isDirectory()}catch{return!1}},fileExists:(e)=>{try{return OC(e)}catch{return!1}},readText:(e)=>{try{return LC(e,"utf8")}catch{return null}}};function Qc(e,t){if(e==="~")return t;if(e.startsWith("~/"))return Fr(t,e.slice(2));return e}function _C(e){let t=e.indexOf(":");return(t===-1?e:e.slice(0,t)).toLowerCase()}function Yd(e){return e.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function jC(e,t){for(let r of t){let i=`.${r}`;if(e.endsWith(i)){let n=e.slice(0,-i.length);if(n.length>0&&!n.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(n))return n}}return null}function UC(e,t){let r=t.readText(Fr(e,"rpx.site.json"));if(r)try{let n=JSON.parse(r);if(n&&typeof n==="object")return n}catch{}let i=t.readText(Fr(e,"package.json"));if(i)try{let n=JSON.parse(i);if(n.rpx&&typeof n.rpx==="object")return n.rpx}catch{}return null}function KC(e){let t=e.selfRegisters??!1;return{command:e.command,env:e.env,urlEnv:e.urlEnv,selfRegisters:t,routes:e.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function WC(e,t){let r=UC(e,t);if(r?.command)return KC(r);let i=t.fileExists(Fr(e,"buddy")),n=t.readText(Fr(e,"package.json")),s=null;if(n)try{s=JSON.parse(n)}catch{s=null}let o={...s?.dependencies??{},...s?.devDependencies??{}};if(i||Object.keys(o).some((c)=>c==="stacks"||c.startsWith("@stacksjs/")))return{command:i?"./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(s?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function el(e,t={}){let r={dirExists:t.dirExists??Zc.dirExists,fileExists:t.fileExists??Zc.fileExists,readText:t.readText??Zc.readText},i=t.detect??WC,n=t.homeDir??Xd(),s=e.tlds??Qd,o=(e.roots??Zd).map((h)=>Qc(h,n)),a=e.idleTimeoutMs??IC,c=new Map;for(let h of e.sites??[])c.set(h.to,h);let l=(h)=>h.idleTimeoutMs??a;function f(h){let d=Wd(c,h);if(!d)return null;let p=BC(d.dir)?d.dir:Qc(d.dir,n),g=d.selfRegisters??!1,y=d.routes??[];if(!g&&y.length===0)y=i(p,r)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let w=Jd({...d.env??{}},void 0,h);return{host:h,id:Yd(h),dir:p,command:d.command,env:w,routes:y,selfRegisters:g,idleTimeoutMs:l(d),source:"config"}}function u(h){let d=jC(h,s);if(!d)return null;for(let p of o){let g=Fr(p,d);if(!r.dirExists(g))continue;let y=i(g,r);if(!y)continue;let w=y.selfRegisters??!1;return{host:h,id:Yd(h),dir:g,command:y.command,env:Jd({...y.env??{}},y.urlEnv,h),routes:w?[]:y.routes??[],selfRegisters:w,idleTimeoutMs:a,source:"discovered"}}return null}return{resolve(h){let d=_C(h);if(!d)return null;return f(d)??u(d)}}}function HC(e){try{return FC(e,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function dP(e,t={}){let r=t.homeDir??Xd(),i=e.tlds??Qd,n=(e.roots??Zd).map((u)=>Qc(u,r)),s=t.readdir??HC,o=el(e,t),a=[],c=new Set,l=(u)=>{if(u&&!c.has(u.host))c.add(u.host),a.push(u)};for(let u of e.sites??[])if(!u.to.includes("*"))l(o.resolve(u.to));let f=i[0]??"localhost";for(let u of n)for(let h of s(u))l(o.resolve(`${h}.${f}`));return a}function Jd(e,t,r){if(!t)return e;let i=`https://${r}`;for(let n of t)if(e[n]===void 0)e[n]=i;return e}import{closeSync as sm,openSync as YC,readFileSync as JC}from"node:fs";import*as om from"node:fs/promises";import{spawn as XC}from"node:child_process";import{homedir as ZC}from"node:os";import*as Ai from"node:path";import*as Xe from"node:process";import*as js from"node:net";function tm(e,t,r){return m("port",`Checking if port ${e} is in use on ${t}`,r),new Promise((i)=>{let n=js.createServer(),s=setTimeout(()=>{m("port",`Checking port ${e} timed out, assuming it's in use`,r),n.close(),i(!0)},3000);n.once("error",(o)=>{if(clearTimeout(s),o.code==="EADDRINUSE")m("port",`Port ${e} is in use`,r),i(!0);else m("port",`Error checking port ${e}: ${o.message}`,r),i(!0)}),n.once("listening",()=>{clearTimeout(s),m("port",`Port ${e} is available`,r),n.close(),i(!1)});try{n.listen(e,t)}catch(o){clearTimeout(s),m("port",`Exception checking port ${e}: ${o}`,r),i(!0)}})}async function tl(e,t,r,i=50){m("port",`Finding available port starting from ${e} (max attempts: ${i})`,r);let n=e,s=0;while(s<i){if(s++,!await tm(n,t,r))return m("port",`Found available port: ${n} after ${s} attempts`,r),n;m("port",`Port ${n} is in use, trying ${n+1} (attempt ${s}/${i})`,r),n++}throw Error(`Unable to find available port after ${i} attempts starting from ${e}`)}function em(e,t,r=5000,i){return m("port",`Testing connection to ${t}:${e}`,i),new Promise((n)=>{let s=js.connect({host:t,port:e,timeout:r});s.once("connect",()=>{m("port",`Successfully connected to ${t}:${e}`,i),s.end(),n(!0)}),s.once("timeout",()=>{m("port",`Connection to ${t}:${e} timed out`,i),s.destroy(),n(!1)}),s.once("error",(o)=>{m("port",`Failed to connect to ${t}:${e}: ${o.message}`,i),s.destroy(),n(!1)})})}class rm{usedPorts=new Set;hostname;verbose;maxRetries;constructor(e="0.0.0.0",t,r=50){this.hostname=e,this.verbose=t,this.maxRetries=r}async getNextAvailablePort(e,t=!1){if(this.usedPorts.has(e))return this.findNextAvailablePort(e+1,t);if(await tm(e,this.hostname,this.verbose))return this.findNextAvailablePort(e+1,t);if(t){if(!await em(e,this.hostname,3000,this.verbose))return m("port",`Port ${e} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(e+1,t)}return this.usedPorts.add(e),e}async findNextAvailablePort(e,t=!1){let r=await tl(e,this.hostname,this.verbose,this.maxRetries);if(t){if(!await em(r,this.hostname,3000,this.verbose))if(r<e+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(e){m("port",`Releasing port ${e}`,this.verbose),this.usedPorts.delete(e)}}var pP=new rm;import*as Us from"node:fs";import*as $e from"node:fs/promises";import{homedir as VC}from"node:os";import*as rl from"node:path";import*as Ks from"node:process";var zC=/^[a-zA-Z0-9._-]+$/;function Ft(){return rl.join(VC(),".stacks","rpx","registry.d")}function il(e){return typeof e==="string"&&e.length>0&&e.length<=128&&zC.test(e)}function nl(e,t){if(!il(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return rl.join(e,`${t}.json`)}function Pe(e){if(!Number.isInteger(e)||e<=0)return!1;try{return Ks.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function im(e){if(!e||typeof e!=="object")return!1;let t=e,r=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,i=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,n=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",s=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&il(t.id)&&(i||n)&&typeof t.to==="string"&&t.to.length>0&&s&&r&&typeof t.createdAt==="string"}async function GC(e){await $e.mkdir(e,{recursive:!0})}async function nm(e,t=Ft(),r){if(!im(e))throw Error(`invalid registry entry: ${JSON.stringify(e)}`);await GC(t);let i=nl(t,e.id),n=`${i}.tmp.${Ks.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{await $e.writeFile(n,s,{encoding:"utf8",mode:420}),await $e.rename(n,i),m("registry",`wrote entry ${e.id} → ${i}`,r)}catch(o){throw await $e.unlink(n).catch(()=>{}),o}}async function sl(e,t=Ft(),r){let i=nl(t,e);try{await $e.unlink(i),m("registry",`removed entry ${e}`,r)}catch(n){if(n.code!=="ENOENT")throw n}}async function qC(e,t=Ft(),r){let i=nl(t,e);try{let n=await $e.readFile(i,"utf8"),s=JSON.parse(n);if(!im(s))return m("registry",`entry ${e} failed validation, removing`,r),await $e.unlink(i).catch(()=>{}),null;return s}catch(n){if(n.code==="ENOENT")return null;if(n instanceof SyntaxError)return m("registry",`entry ${e} has invalid JSON, removing`,r),await $e.unlink(i).catch(()=>{}),null;throw n}}async function $t(e=Ft(),t){let r;try{r=await $e.readdir(e)}catch(n){if(n.code==="ENOENT")return[];throw n}let i=[];for(let n of r){if(!n.endsWith(".json"))continue;let s=n.slice(0,-5);if(!il(s))continue;let o=await qC(s,e,t);if(o)i.push(o)}return i}async function Pi(e=Ft(),t){let r=await $t(e,t),i=0;for(let n of r){if(n.pid===void 0)continue;if(!Pe(n.pid))m("registry",`GC: pid ${n.pid} for ${n.id} is dead, removing`,t),await sl(n.id,e,t).catch(()=>{}),i++}return i}function Ws(e,t={}){let r=t.dir??Ft(),i=t.debounceMs??100,n=t.pollMs??Math.max(i*2,250),s=t.verbose;Us.mkdirSync(r,{recursive:!0});let o=null,a=!1,c=null,l=!1,f=(y)=>JSON.stringify(y.map((w)=>({id:w.id,from:w.from,to:w.to,path:w.path,pid:w.pid,pathRewrites:w.pathRewrites,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,static:w.static,loadBalancer:w.loadBalancer})).sort((w,C)=>w.id.localeCompare(C.id))),u=()=>{if(o=null,a)return;$t(r,s).then((y)=>(c=f(y),e(y))).catch((y)=>{m("registry",`watcher onChange failed: ${y}`,s)})},h=()=>{if(a)return;if(o)clearTimeout(o);o=setTimeout(u,i)},p=setInterval(()=>{if(a||l)return;l=!0,$t(r,s).then((y)=>{if(f(y)!==c)h()}).catch((y)=>{m("registry",`watcher poll failed: ${y}`,s)}).finally(()=>{l=!1})},n),g=Us.watch(r,{persistent:!0},(y,w)=>{if(w&&/\.tmp\.\d+\.\d+$/.test(w))return;h()});return g.on("error",(y)=>{m("registry",`watcher error: ${y}`,s)}),h(),{close:()=>{if(a=!0,o)clearTimeout(o);clearInterval(p),g.close()}}}var QC=120000,eS=200,tS=30000,rS=3000,iS=4000;class al{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(e){this.resolver=e.resolver,this.registryDir=e.registryDir??Ft(),this.rpxDir=e.rpxDir??Ai.join(ZC(),".stacks","rpx"),this.verbose=e.verbose??!1,this.startupTimeoutMs=e.startupTimeoutMs??QC,this.pollIntervalMs=e.pollIntervalMs??eS,this.restartDelayMs=e.restartDelayMs??rS,this.killGraceMs=e.killGraceMs??iS,this.launch=e.launcher??sS(this.verbose),this.probePort=e.probePort??nS,this.pickPort=e.pickPort??((r)=>tl(r,"127.0.0.1")),this.isHostRoutable=e.isHostRoutable??(()=>!1),this.onSiteActivating=e.onSiteActivating,this.now=e.now??Date.now,this.writeEntry=e.writeEntry??nm,this.removeEntry=e.removeEntry??sl;let t=e.reapIntervalMs??tS;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(e){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(e);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(e),t=void 0;if(!t){let r=this.resolver.resolve(e);if(!r)return{kind:"unknown"};t=await this.start(r)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:e};if(t.status==="failed")return{kind:"failed",host:e,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:e,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(e){try{this.onSiteActivating?.(e.host)}catch{}let t=new Map;if(!e.selfRegisters)for(let a of e.routes){if(t.has(a.portEnv))continue;let c=await this.pickPort(a.defaultPort??3000);t.set(a.portEnv,c)}let r=Ai.join(this.rpxDir,"sites",`${e.id}.log`);await om.mkdir(Ai.dirname(r),{recursive:!0}).catch(()=>{});let i=this.buildEnv(e,t),n=null,s;try{n=this.launch({command:e.command,cwd:e.dir,env:i,logPath:r})}catch(a){s=`failed to spawn: ${a.message}`}let o={site:e,status:s?"failed":"starting",handle:n,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:s?this.now():0,error:s,logPath:r,exited:!1,ready:Promise.resolve()};if(this.sites.set(e.host,o),s)return x.warn(`rpx: site ${e.host} ${s}`),o;return x.info(`rpx: booting ${e.host} → ${e.command} (${e.dir})`),n.exited.then((a)=>this.onProcessExit(o,a)).catch(()=>{}),o.ready=this.driveReadiness(o).catch((a)=>{m("sites",`readiness loop for ${e.host} threw: ${a}`,this.verbose)}),o}async onProcessExit(e,t){if(e.exited=!0,this.stopped||this.sites.get(e.site.host)!==e)return;if(e.status==="ready"){x.warn(`rpx: ${e.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(e.site.host);for(let r of e.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{})}else if(e.status==="starting")this.fail(e,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(e){let{site:t}=e,r=this.now()+this.startupTimeoutMs,i=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,e.ports);while(this.now()<r&&!this.stopped){if(e.status!=="starting"||e.exited)return;if(await i()){if(await this.publishRoutes(e),e.status==="starting")e.status="ready",x.success(`rpx: ${t.host} ready`);return}await ol(this.pollIntervalMs)}if(e.status==="starting")this.fail(e,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(e,t){let r=e.routes.filter((n)=>n.readyGate??Vt(n.path)==="/").map((n)=>t.get(n.portEnv)).filter((n)=>typeof n==="number"),i=r.length>0?r:[...t.values()];return async()=>{for(let n of i)if(!await this.probePort(n))return!1;return i.length>0}}async publishRoutes(e){let{site:t,ports:r}=e;if(t.selfRegisters||t.routes.length===0)return;let i=t.routes.find((c)=>Vt(c.path)==="/")??t.routes[0],n=r.get(i.portEnv);if(n===void 0)return;let s=[];for(let c of t.routes){if(c===i)continue;let l=r.get(c.portEnv);if(l===void 0)continue;s.push({from:Vt(c.path),to:`localhost:${l}`,stripPrefix:c.stripPrefix??!1})}let o={id:t.id,from:`localhost:${n}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:s.length>0?s:void 0,pid:e.handle?.pid};await this.writeEntry(o,this.registryDir,this.verbose),e.routeIds=[t.id];let a=this.now()+2000;while(this.now()<a&&!this.isHostRoutable(t.host))await ol(50)}fail(e,t){e.status="failed",e.error=t,e.failedAt=this.now(),x.warn(`rpx: site ${e.site.host} failed — ${t}`),this.killProcess(e)}buildEnv(e,t){let r={};for(let[i,n]of Object.entries(Xe.env))if(typeof n==="string")r[i]=n;Object.assign(r,e.env);for(let[i,n]of t)r[i]=String(n);return r.RPX_SITE_HOST=e.host,r.RPX_SITE_URL=`https://${e.host}`,r}readLogTail(e,t=40){try{return JC(e.logPath,"utf8").split(`
245
+ `).slice(-t).join(`
246
+ `).trim()}catch{return""}}async stop(e){let t=this.sites.get(e);if(!t)return;this.sites.delete(e);for(let r of t.routeIds)await this.removeEntry(r,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),x.info(`rpx: stopped ${e}`)}async killProcess(e){let t=e.handle;if(!t)return;e.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(()=>{}),ol(this.killGraceMs+500)]),clearTimeout(r)}async reapIdle(){if(this.stopped)return;let e=this.now();for(let[t,r]of this.sites){let i=r.site.idleTimeoutMs;if(i<=0)continue;let n=e-r.lastAccess;if((r.status==="ready"||e-r.startedAt>this.startupTimeoutMs)&&n>i)m("sites",`reaping ${t} (idle ${Math.round(n/1000)}s)`,this.verbose),await this.stop(t)}}list(){let e=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:e-t.startedAt,idleMs:e-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((e)=>this.stop(e)))}}function ol(e){return new Promise((t)=>setTimeout(t,e))}async function nS(e){let t=new AbortController,r=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${e}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(r)}}function sS(e){let t=oS();return({command:r,cwd:i,env:n,logPath:s})=>{let o=YC(s,"a");try{let a=XC("sh",["-c",r],{cwd:i,env:n,detached:!0,stdio:["ignore",o,o],...t?{uid:t.uid,gid:t.gid}:{}}),c=a.pid;if(c===void 0)throw Error("spawn returned no pid");let l=new Promise((f)=>{a.once("exit",(u)=>{f(u)}),a.once("error",()=>{f(null)})}).finally(()=>{try{sm(o)}catch{}});return m("sites",`spawned pid ${c}: sh -c ${r} (cwd ${i})`,e),{pid:c,exited:l,stop:(f="SIGTERM")=>{try{Xe.kill(-c,f)}catch{try{a.kill(f)}catch{}}}}}catch(a){try{sm(o)}catch{}throw a}}}function oS(){if(Xe.platform==="win32")return null;if(!(typeof Xe.getuid==="function"&&Xe.getuid()===0))return null;let t=Number.parseInt(Xe.env.SUDO_UID??"",10),r=Number.parseInt(Xe.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(r)||r<=0)return null;return{uid:t,gid:r}}function Lr(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}var aS=`
247
+ :root { color-scheme: light dark }
248
+ * { box-sizing: border-box }
249
+ body {
250
+ margin: 0; min-height: 100vh; display: grid; place-items: center;
251
+ font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
252
+ background: #0b0c0f; color: #e7e9ee;
253
+ }
254
+ .card { width: min(92vw, 540px); padding: 2.25rem 2.5rem; }
255
+ .row { display: flex; align-items: center; gap: .75rem; }
256
+ h1 { font-size: 1.15rem; margin: 0; font-weight: 600; letter-spacing: -.01em }
257
+ p { margin: .5rem 0 0; color: #9aa1ad }
258
+ code { color: #cbd2dc; background: #16181d; padding: .1rem .4rem; border-radius: 5px }
259
+ pre {
260
+ margin: 1.25rem 0 0; padding: 1rem; max-height: 40vh; overflow: auto;
261
+ background: #16181d; border: 1px solid #23262d; border-radius: 8px;
262
+ font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color: #aeb6c2;
263
+ white-space: pre-wrap; word-break: break-word;
264
+ }
265
+ .spinner {
266
+ width: 16px; height: 16px; border-radius: 50%;
267
+ border: 2px solid #3a3f4b; border-top-color: #8ab4f8;
268
+ animation: spin .8s linear infinite;
269
+ }
270
+ .dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
271
+ @keyframes spin { to { transform: rotate(360deg) } }
272
+ `;function am(e,t,r){return`<!doctype html>
273
+ <html lang="en">
274
+ <head>
275
+ <meta charset="utf-8">
276
+ <meta name="viewport" content="width=device-width, initial-scale=1">
277
+ ${r>0?`<meta http-equiv="refresh" content="${r}">`:""}
278
+ <title>${Lr(e)}</title>
279
+ <style>${aS}</style>
280
+ </head>
281
+ <body><main class="card">${t}</main></body>
282
+ </html>`}function cm(e){let t=Math.max(1,Math.round(e.sinceMs/1000)),r=e.logTail?`<pre>${Lr(e.logTail)}</pre>`:"",i=`
283
+ <div class="row"><div class="spinner"></div><h1>Starting ${Lr(e.host)}…</h1></div>
284
+ <p>rpx is booting this site's dev server on demand. This page reloads itself —
285
+ it'll switch to the app as soon as it's ready (usually a few seconds).</p>
286
+ <p>Booting for ${t}s.</p>
287
+ ${r}`;return new Response(am(`Starting ${e.host}`,i,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function lm(e){let t=e.logTail?`<pre>${Lr(e.logTail)}</pre>`:"<p>No output was captured.</p>",r=`
288
+ <div class="row"><div class="dot"></div><h1>${Lr(e.host)} failed to start</h1></div>
289
+ <p>${Lr(e.error)}</p>
290
+ ${t}
291
+ <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(am(`${e.host} failed`,r,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}import{exec as cS}from"node:child_process";import ki from"node:fs";import lS from"node:os";import dm from"node:path";import*as zt from"node:process";import{promisify as fS}from"node:util";var Ri=fS(cS);function fm(e){let t=e.trim().toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t.endsWith(".localhost.")}var rt=zt.platform==="win32"?dm.join(zt.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",um="# rpx",uS="# Added by rpx",Ni=new Set(["127.0.0.1","::1"]),cl=!1;async function mm(e){if(zt.platform==="win32")throw Error("Administrator privileges required on Windows");if(hm()){let{stdout:i}=await Ri(e);return i}let t=ll(),r=e.replace(/'/g,"'\\''");try{if(t){let{stdout:i}=await Ri(`echo '${t}' | sudo -S sh -c '${r}' 2>/dev/null`);return cl=!0,i}if(cl)try{let{stdout:i}=await Ri(`sudo -n sh -c '${r}'`);return i}catch(i){m("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:i}=await Ri(`sudo -n sh -c '${r}'`);return cl=!0,i}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(i){throw Error(`Failed to execute sudo command: ${i.message}`)}}function Di(e){let t=e.indexOf("#"),r=(t===-1?e:e.slice(0,t)).trim();if(!r)return null;let i=t===-1?"":e.slice(t+1).trim(),[n,...s]=r.split(/\s+/);if(!n||s.length===0)return null;let o=/^rpx(?::pid=(\d+))?$/.exec(i);return{address:n,names:s,comment:i,rpxPid:o?.[1]?Number.parseInt(o[1],10):null,rpxManaged:o!==null}}function gm(e,t){let r=Di(e);return r!==null&&Ni.has(r.address)&&r.names.includes(t)}function hS(e,t){let r=new Set(t),i=new Set,n=e.split(`
292
+ `),s=[],o=0;while(o<n.length){let a=n[o];if(a.trim()===uS){let l=[],f=o+1;while(f<n.length){let h=n[f];if(h.trim()===""||h.trim().startsWith("#"))break;l.push(h),f++}let u=l.filter((h)=>{let d=Di(h),p=d!==null&&Ni.has(d.address)&&d.names.some((g)=>r.has(g));if(p){for(let g of d.names)if(r.has(g))i.add(g)}return!p});if(u.length>0||l.length===0)s.push(a,...u);o=f;continue}let c=Di(a);if(c?.rpxManaged&&Ni.has(c.address)&&c.names.some((l)=>r.has(l))){for(let l of c.names)if(r.has(l))i.add(l);o++;continue}s.push(a),o++}while(s.length>0&&s[s.length-1].trim()==="")s.pop();return{content:`${s.join(`
293
+ `)}
294
+ `,removed:[...i]}}function dS(e,t){let r=[],i=new Set,n=[];for(let s of e.split(`
295
+ `)){let o=Di(s);if(o?.rpxManaged&&o.rpxPid!==null&&Ni.has(o.address)&&!t(o.rpxPid)){r.push(...o.names),i.add(o.rpxPid);continue}n.push(s)}while(n.length>0&&n[n.length-1].trim()==="")n.pop();return{content:`${n.join(`
296
+ `)}
297
+ `,removed:r,stalePids:[...i]}}async function fl(e){try{return await ki.promises.readFile(rt,"utf-8")}catch{return m("hosts","Reading hosts file requires elevated permissions, using sudo",e),mm(`cat "${rt}"`)}}async function ul(e,t){let r=dm.join(lS.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await ki.promises.writeFile(r,e,"utf8"),await mm(`cat "${r}" | tee "${rt}" > /dev/null`)}finally{await ki.promises.unlink(r).catch((i)=>{m("hosts",`Failed to remove temporary file: ${i}`,t)})}}async function IP(e,t){let r=e.filter((n)=>!fm(n)),i=e.filter((n)=>fm(n));if(i.length>0)m("hosts",`Skipping /etc/hosts for loopback dev names: ${i.join(", ")}`,t);if(r.length===0)return;m("hosts",`Adding hosts: ${r.join(", ")}`,t),m("hosts",`Using hosts file at: ${rt}`,t);try{let n;try{n=await fl(t)}catch(l){throw console.log(" Could not read hosts file — skipping hosts setup"),m("hosts",`sudo read also failed: ${l}`,t),Error(`Cannot read hosts file: ${l}`)}let s=n.split(`
298
+ `),o=r.filter((l)=>!s.some((f)=>gm(f,l)));if(o.length===0){m("hosts","All hosts already exist in hosts file",t);return}let a=zt.pid,c=o.map((l)=>`
299
+ 127.0.0.1 ${l} ${um}:pid=${a}
300
+ ::1 ${l} ${um}:pid=${a}`).join(`
301
+ `);try{await ul(n+c,t),console.log(` Hosts updated: ${o.join(", ")}`)}catch(l){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),o.forEach((f)=>{console.log(` 127.0.0.1 ${f}`),console.log(` ::1 ${f}`)}),console.log(` Or run: sudo nano ${rt}`)}}catch(n){m("hosts",`Failed to manage hosts file: ${n.message}`,t)}}async function _P(e,t){m("hosts",`Removing hosts: ${e.join(", ")}`,t);try{let r;try{r=await fl(t)}catch(s){throw m("hosts",`sudo read also failed: ${s}`,t),Error(`Cannot read hosts file: ${s}`)}let{content:i,removed:n}=hS(r,e);if(n.length===0){m("hosts","No matching rpx-managed hosts found to remove",t);return}try{await ul(i,t),m("hosts",`Hosts removed successfully: ${n.join(", ")}`,t)}catch(s){m("hosts","Could not clean up hosts file automatically",t)}}catch(r){m("hosts",`Failed to clean up hosts file: ${r.message}`,t)}}async function jP(e,t){m("hosts",`Checking hosts: ${e}`,t);let r;try{r=await ki.promises.readFile(rt,"utf-8")}catch(n){m("hosts",`Error reading hosts file: ${n}`,t);try{let s=ll(),o;if(s)o=`echo '${s}' | sudo -S cat "${rt}" 2>/dev/null`;else o=`sudo -n cat "${rt}" 2>/dev/null || cat "${rt}" 2>/dev/null || echo ""`;let{stdout:a}=await Ri(o);r=a}catch(s){return m("hosts",`Cannot read hosts file, assuming entries don't exist: ${s}`,t),e.map(()=>!1)}}let i=r.split(`
302
+ `);return e.map((n)=>i.some((s)=>gm(s,n)))}async function UP(e=Pe){let t;try{t=await ki.promises.readFile(rt,"utf-8")}catch{return[]}let r=[];for(let i of t.split(`
303
+ `)){let n=Di(i);if(n?.rpxManaged&&n.rpxPid!==null&&Ni.has(n.address)&&!e(n.rpxPid))r.push(...n.names)}return[...new Set(r)]}async function Oi(e={}){let t=e.isAlive??Pe,r;try{r=await fl(e.verbose)}catch(o){return m("hosts",`stale hosts GC: cannot read hosts file: ${o}`,e.verbose),[]}let{content:i,removed:n,stalePids:s}=dS(r,t);if(n.length===0)return[];try{return await ul(i,e.verbose),m("hosts",`stale hosts GC: removed ${n.join(", ")} (dead pid(s): ${s.join(", ")})`,e.verbose),[...new Set(n)]}catch(o){return m("hosts",`stale hosts GC: write failed: ${o}`,e.verbose),[]}}var mS=5000;function Ae(){return it.join(bm(),".stacks","rpx")}function Gs(e=Ae()){return it.join(e,"daemon.pid")}async function Br(e=Ae()){try{let t=await ye.readFile(Gs(e),"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 gS(e=Ae()){let t=await Br(e);return t!==null&&Pe(t)}async function Cm(e=Ae()){await ye.mkdir(e,{recursive:!0});let t=Gs(e);while(!0){try{let i=await ye.open(t,"wx");try{await i.write(`${E.pid}
304
+ `)}finally{await i.close()}return t}catch(i){if(i.code!=="EEXIST")throw i}let r=await Br(e);if(r!==null&&Pe(r))throw Error(`rpx daemon already running (pid=${r})`);await ye.unlink(t).catch(()=>{})}}async function Mr(e=Ae()){await ye.unlink(Gs(e)).catch(()=>{})}var Vs=new Map;function zs(e){for(let[t,r]of Vs)if(!e.has(t))Oc(r),Vs.delete(t)}function pS(e,t){let r=gd(t??"localhost:1");if(e.upstreams.length!==r.length)return!1;return e.upstreams.every((i,n)=>i.url===r[n])}function Sm(e){let t=e.cleanUrls??!1,r=Vt(e.path),i=Sd(e.auth);if(e.static)return{static:Od(e.static,t),cleanUrls:t,basePath:r,auth:i};let n=e.from??"localhost:1",s=pd(n),o=new URL(s.startsWith("http")?s:`http://${s}`),a=Vs.get(e.id);if(a&&!pS(a,n))Oc(a),a=void 0;if(!a)a=yd(n,e.loadBalancer),vd(a),Vs.set(e.id,a);return{sourceHost:o.host,upstreamPool:a,cleanUrls:t,changeOrigin:e.changeOrigin??!1,pathRewrites:e.pathRewrites,basePath:r,auth:i}}function yS(e){return e.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??e[0]??"rpx.localhost"}async function Hs(e,t,r=[],i=!1){let n=await $t(t,e.verbose),s=[...new Set([...n.map((f)=>f.to).filter(Boolean),...r])],o=yS(s),a=[...new Set([o,...s,"rpx.localhost"])],c=hd(s,o,e.verbose);if(typeof e.https==="object"&&typeof c.https==="object")c.https={...c.https,...e.https};let l=await Nc(c);if(l&&(i||!Cc(Ac,a)))m("daemon",`regenerating shared cert for host(s): ${a.join(", ")}`,e.verbose),kc(),l=null;if(!l)m("daemon","no usable cert on disk, generating one via tlsx",e.verbose),await md({...c,forceRegenerate:!0}),l=await Nc(c);if(!l)throw Error("failed to bootstrap TLS for rpx daemon");return l}async function wS(e,t,r,i){let n=E.env.SUDO_PASSWORD,s=E.env.HOME??bm(),o=[E.execPath,...E.argv.slice(1)],a=[`HOME=${s}`,`PATH=${E.env.PATH??""}`];if(i)a.push("RPX_VERBOSE=1");for(let[p,g]of Object.entries(E.env))if(g!==void 0&&p!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(p))a.push(`${p}=${g}`);let c=n?["-S","-p","","env",...a,...o]:["-n","env",...a,...o];m("daemon",`elevating daemon via sudo for privileged ports ${t}/${r}`,i);let l=vm("sudo",c,{detached:!0,stdio:["pipe","ignore","ignore"]}),f=null,u=null;if(l.once("error",(p)=>{f=p}),l.once("exit",(p)=>{u=p??0}),n&&l.stdin)l.stdin.write(`${n}
305
+ `),l.stdin.end();l.unref();let h=Gs(e),d=Date.now()+15000;while(Date.now()<d){if(f)throw f;let p=await Br(e);if(p!==null&&Pe(p)){if(i)x.success(`rpx daemon elevated to root (pid=${p}, https on :${t})`);return{httpsPort:t,httpPort:r,pidPath:h,done:Promise.resolve(),stop:async()=>{try{E.kill(p,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(u!==null&&u!==0)throw Error(`rpx daemon could not elevate to bind :${t} (sudo exited ${u}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((g)=>setTimeout(g,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${e})`)}var pm=!1;function dl(){if(pm)return;pm=!0,E.on("uncaughtException",(e)=>{x.error(`rpx daemon: uncaught exception (continuing): ${e?.stack??e}`)}),E.on("unhandledRejection",(e)=>{x.error(`rpx daemon: unhandled rejection (continuing): ${e}`)})}function $m(e,t,r){let i;try{i=new URL(e.url)}catch{return new Response("Bad Request",{status:400})}let n=(e.headers.get("host")??i.hostname).split(":")[0];if(i.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let s=t.challengeStore.handlePath(i.pathname);if(s!==void 0)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(r){let s=Kd(r,i.pathname);if(s!=null)return new Response(s,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(n))t.ensureCert(n).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${n}${i.pathname}${i.search}`}})}async function fA(e={}){dl();let t=e.verbose??!1,r=e.rpxDir??Ae(),i=e.registryDir??it.join(r,"registry.d"),n=e.httpsPort??443,s=e.httpPort??80,o=e.https===!1;if(e.localCa)Jc(e.localCa,e.onDemandTls);let a=e.hostname??"::",c=e.hostname==null,l=e.gcIntervalMs??mS;if(E.env.RPX_DAEMON_WORKER==="1")return CS({rpxDir:E.env.RPX_WORKER_RPXDIR??r,registryDir:E.env.RPX_WORKER_REGISTRYDIR??i,httpsPort:Number.parseInt(E.env.RPX_WORKER_HTTPSPORT??"",10)||n,hostname:E.env.RPX_WORKER_HOSTNAME??a,verbose:E.env.RPX_WORKER_VERBOSE==="1"||t});let f=!o&&n>0&&n<1024||s>0&&s<1024,u=typeof E.getuid==="function"&&E.getuid()===0;if(E.platform!=="win32"&&f&&!u)return wS(r,n,s,t);let h=Math.max(1,e.workers??(Number.parseInt(E.env.RPX_WORKERS??"",10)||1));if(h>1){if(o)throw Error("rpx daemon: https: false is not supported with workers > 1 (the cluster shares the HTTPS port only); run a single process");if(e.onDemandSites?.enabled)x.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return SS(e,{rpxDir:r,registryDir:i,httpsPort:n,httpPort:s,hostname:a,verbose:t,gcIntervalMs:l,workers:h})}let d=await Cm(r),p=new Map,g=(S,R)=>Kc(p,S,R);function y(S){p=jc(S.map((fe)=>({host:fe.to,path:fe.path,route:Sm(fe)}))),zs(new Set(S.map((fe)=>fe.id)));let R=Array.from(p.keys());m("daemon",`routing table now covers ${R.length} host(s): ${R.join(", ")||"<empty>"}`,t)}await Pi(i,t).catch((S)=>{m("daemon",`initial gc failed: ${S}`,t)}),await Oi({verbose:t}).catch((S)=>{m("daemon",`stale hosts GC on start failed: ${S}`,t)});let w=await $t(i,t);y(w),await _r({rpxDir:r,verbose:t}).catch((S)=>{m("daemon",`DNS reconcile on start failed: ${S}`,t)}),await Fi(w,{rpxDir:r,verbose:t,ownerPid:E.pid}).catch((S)=>{m("daemon",`DNS setup on start failed: ${S}`,t)});let C=[];if(e.productionCerts&&!o){if(C=await Vc(e.productionCerts,t),t&&C.length>0)x.info(`SNI: serving ${C.length} real cert(s): ${C.map((S)=>S.serverName).join(", ")}`)}let A=null;if(e.localCa&&!o){let S=await Xc(e.localCa,{verbose:t,onDemandTls:e.onDemandTls}),R=new Set(S.entries.map((fe)=>fe.serverName));if(C=[...S.entries,...C.filter((fe)=>!R.has(fe.serverName))],A=S.defaultTls,t)x.info(`Local CA: ${S.leafMinted?`minted leaf (${S.renewalReason})`:"reusing leaf"} for ${[...R].join(", ")}; valid until ${S.notAfter.toISOString()}`)}let T=new Set,P=null,D;if(e.onDemandSites?.enabled){if(P=new al({resolver:el(e.onDemandSites),registryDir:i,rpxDir:r,verbose:t,startupTimeoutMs:e.onDemandSites.startupTimeoutMs,isHostRoutable:(S)=>Uc(p,S)!==void 0,onSiteActivating:(S)=>{_i(S)}}),D=async(S)=>{let R=await P.onRequest(S);switch(R.kind){case"ready":return{retry:!0};case"starting":return cm({host:R.host,sinceMs:R.sinceMs,logTail:R.logTail});case"failed":return lm({host:R.host,error:R.error,logTail:R.logTail});case"unknown":default:return}},t)x.info("rpx: on-demand sites enabled")}let N=Bc(g,t,D),ae=Ic(t),J=null;if(!o&&C.length===0)J=await Hs(e,i);let xt=e.onDemandTls,nt=xt?.enabled&&!o?new _s({config:xt,certsDir:xt.certsDir??e.productionCerts?.certsDir??it.join(r,"on-demand-certs"),initial:C,verbose:t,onCertAdded:(S)=>{if(zc()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",t),setTimeout(()=>E.kill(E.pid,"SIGTERM"),10).unref();else We(S)}}):null;function Mt(S){if(S.length>0)return Hc({sni:S,defaultTls:A,maxTlsContexts:e.maxTlsContexts,verbose:t});return Bs({key:J.key,cert:J.cert,ca:J.ca,requestCert:!1,rejectUnauthorized:!1})}function Gt(S){try{return Bun.serve(S)}catch(R){let fe=R instanceof Error?R.message:String(R),Ur=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(fe);if(!c||S.hostname!=="::"||!Ur)throw R;return m("daemon",`no IPv6 on this host (${fe}); binding 0.0.0.0`,e.verbose),Bun.serve({...S,hostname:"0.0.0.0"})}}function jr(S){return Gt({port:n,hostname:a,reusePort:hl(),tls:Mt(S),fetch(R,fe){return N(R,fe)},websocket:ae,error(R){return m("daemon",`https server error: ${R}`,t),new Response(`Server Error: ${R.message}`,{status:500})}})}let Bi=(S)=>[...new Set(S.map((R)=>R.to).filter(Boolean))],Bt=(S)=>{if(!J)return C;return ud([...Bi(S),...T,"rpx.localhost"],J)},st=o?null:jr(nt?nt.sniEntries():C.length>0?C:Bt(w)),It=null,k=!1;async function We(S){if(Tt||o)return;if(It=S,k)return;k=!0;try{while(!Tt&&It){let R=It;It=null,m("daemon",`rebuilding :443 with ${R.length} SNI cert(s)`,t),st?.stop(!1);let fe,Ur=!1,xl=60,Im=500;for(let Qs=0;!Tt&&!Ur;Qs++)try{st=jr(R),Ur=!0;break}catch(_m){if(fe=_m,Qs>=xl)break;await new Promise((jm)=>setTimeout(jm,Math.min(25*2**Math.min(Qs,4),Im)))}if(!Ur)x.error(`rpx: CRITICAL — could not rebind :443 after ${xl} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${fe?.message}`)}}finally{k=!1}}let Ee=null;if(o)Ee=Gt({port:s,hostname:a,reusePort:hl(),fetch(S,R){return N(S,R)},websocket:ae,error(S){return m("daemon",`http server error: ${S}`,t),new Response(`Server Error: ${S.message}`,{status:500})}});else if(s>0)Ee=Gt({port:s,hostname:a,fetch(S){return $m(S,nt,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t){if(o)x.success(`rpx daemon listening on http://${a}:${Ee?.port??s} (https disabled)`);else x.success(`rpx daemon listening on https://${a}:${n}${Ee?` (http→https on :${s})`:""}`);x.info(`pid file: ${d}`),x.info(`registry: ${i}`)}async function Ii(S){if(Tt||C.length>0||nt||!J)return;try{J=await Hs(e,i,[...T]),await We(Bt(S))}catch(R){m("daemon",`TLS sync on registry change failed: ${R}`,t)}}async function _i(S){if(Tt||C.length>0||nt||!J||!S)return;if(T.has(S))return;T.add(S);try{J=await Hs(e,i,[...T],!0);let R=await $t(i,t);await We(Bt(R))}catch(R){m("daemon",`dev cert refresh for ${S} failed: ${R}`,t)}}let ji=Ws((S)=>{y(S),Ii(S),Fi(S,{rpxDir:r,verbose:t,ownerPid:E.pid}).catch((R)=>{m("daemon",`DNS sync on registry change failed: ${R}`,t)})},{dir:i,verbose:t}),qt=setInterval(()=>{Pi(i,t).then((S)=>{if(S>0)m("daemon",`gc reaped ${S} stale entries`,t)}).catch((S)=>{m("daemon",`periodic gc failed: ${S}`,t)}),Oi({verbose:t}).then((S)=>{if(S.length>0)m("daemon",`gc reaped stale hosts entries: ${S.join(", ")}`,t)}).catch((S)=>{m("daemon",`periodic hosts gc failed: ${S}`,t)})},l);if(typeof qt.unref==="function")qt.unref();let Tt=!1,Sl,Zs=new Promise((S)=>{Sl=S});async function $l(){if(Tt)return Zs;if(Tt=!0,clearInterval(qt),ji.close(),await P?.stopAll().catch((S)=>{m("daemon",`site supervisor stopAll failed: ${S}`,t)}),st?.stop(!1),Ee?.stop(!1),await Ir({rpxDir:r,verbose:t}).catch((S)=>{m("daemon",`DNS teardown failed: ${S}`,t)}),zs(new Set),await Mr(r),t)x.info("rpx daemon stopped");return Sl(),Zs}let El=(S)=>{m("daemon",`received ${S}, shutting down`,t),$l().catch(()=>{})};return E.once("SIGINT",El),E.once("SIGTERM",El),{stop:$l,done:Zs,httpsPort:st&&typeof st.port==="number"?st.port:o?0:n,httpPort:Ee&&typeof Ee.port==="number"?Ee.port:s,pidPath:d,ensureCert:(S)=>nt?nt.ensureCert(S):Promise.resolve(!1),listSites:()=>P?.list()??[]}}function ml(e){return it.join(e,"cluster-sni.json")}async function ym(e,t,r,i=null){let n=ml(e),s=`${n}.${E.pid}.tmp`;await ye.writeFile(s,JSON.stringify({sni:t,dev:r,defaultTls:i}),"utf8"),await ye.rename(s,n)}async function wm(e){try{return JSON.parse(await ye.readFile(ml(e),"utf8"))}catch{return{sni:[],dev:null}}}function vS(e){if(e.sni.length>0)return Hc({sni:e.sni,defaultTls:e.defaultTls??null});if(e.dev)return Bs({key:e.dev.key,cert:e.dev.cert,ca:e.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function bS(){let e=E.execPath,t=E.env.RPX_WORKER_BIN;if(t)return[e,t,"daemon:start"];let r=it.basename(e).toLowerCase();if((r==="bun"||r==="node"||r.startsWith("bun-"))&&E.argv[1])return[e,E.argv[1],"daemon:start"];return[e,"daemon:start"]}async function CS(e){dl();let{rpxDir:t,registryDir:r,httpsPort:i,hostname:n,verbose:s}=e,o=new Map,a=(D,N)=>Kc(o,D,N),c=(D)=>{o=jc(D.map((N)=>({host:N.to,path:N.path,route:Sm(N)}))),zs(new Set(D.map((N)=>N.id)))};c(await $t(r,s));let l=Bc(a,s),f=Ic(s),u=!1,h=(D)=>Bun.serve({port:i,hostname:n,reusePort:!0,tls:vS(D),fetch(N,ae){return l(N,ae)},websocket:f,error(N){return m("daemon",`worker https error: ${N}`,s),new Response(`Server Error: ${N.message}`,{status:500})}}),d=h(await wm(t));async function p(){if(u)return;let D=await wm(t),N=null;for(let J=0;J<20&&!u;J++)try{N=h(D);break}catch{await new Promise((xt)=>setTimeout(xt,25))}if(!N){m("daemon","worker reloadTls: could not bind new listener; keeping current",s);return}let ae=d;d=N,ae.stop(!1)}let g=Ws((D)=>c(D),{dir:r,verbose:s}),y=()=>{p().catch(()=>{})};E.on("SIGHUP",y);let w=()=>{let D=E.removeListener??E.off;if(typeof D==="function")D.call(E,"SIGHUP",y)},C,A=new Promise((D)=>{C=D});async function T(){if(u)return A;return u=!0,w(),g.close(),d.stop(!1),zs(new Set),C(),A}let P=()=>{T().then(()=>E.exit(0)).catch(()=>E.exit(0))};if(E.once("SIGTERM",P),E.once("SIGINT",P),s)x.success(`rpx worker (pid ${E.pid}) serving :${i}`);return{stop:T,done:A,httpsPort:typeof d.port==="number"?d.port:i,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function SS(e,t){dl();let{rpxDir:r,registryDir:i,httpsPort:n,httpPort:s,hostname:o,verbose:a,gcIntervalMs:c,workers:l}=t,f=await Cm(r),u=[];if(e.productionCerts)u=await Vc(e.productionCerts,a);let h=null;if(e.localCa){let k=await Xc(e.localCa,{verbose:a,onDemandTls:e.onDemandTls}),We=new Set(k.entries.map((Ee)=>Ee.serverName));u=[...k.entries,...u.filter((Ee)=>!We.has(Ee.serverName))],h=k.defaultTls}let d=null;if(u.length===0)d=await Hs(e,i);let p=d?{key:d.key,cert:d.cert,ca:Array.isArray(d.ca)?d.ca.join(`
306
+ `):d.ca}:null,g=!1,y=[];function w(k){for(let We of y)try{We.kill(k)}catch{}}async function C(k){await ym(r,Ms(k,e.maxTlsContexts,a),p,h),w("SIGHUP")}let A=e.onDemandTls,T=A?.enabled?new _s({config:A,certsDir:A.certsDir??e.productionCerts?.certsDir??it.join(r,"on-demand-certs"),initial:u,verbose:a,onCertAdded:(k)=>{if(zc()==="restart")m("on-demand","certificate installed; restarting supervised gateway to reload TLS",a),setTimeout(()=>E.kill(E.pid,"SIGTERM"),10).unref();else C(k)}}):null;await ym(r,Ms(T?T.sniEntries():u,e.maxTlsContexts,a),p,h);let P=await $t(i,a);await _r({rpxDir:r,verbose:a}).catch((k)=>{m("daemon",`DNS reconcile on start failed: ${k}`,a)}),await Fi(P,{rpxDir:r,verbose:a,ownerPid:E.pid}).catch((k)=>{m("daemon",`DNS setup on start failed: ${k}`,a)}),await Pi(i,a).catch(()=>{}),await Oi({verbose:a}).catch(()=>{});let D=Ws((k)=>{Fi(k,{rpxDir:r,verbose:a,ownerPid:E.pid}).catch((We)=>{m("daemon",`DNS sync on registry change failed: ${We}`,a)})},{dir:i,verbose:a}),N=setInterval(()=>{Pi(i,a).catch(()=>{}),Oi({verbose:a}).catch(()=>{})},c);N.unref?.();let ae=null;if(s>0)ae=Bun.serve({port:s,hostname:o,fetch(k){return $m(k,T,e.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let J=10,xt=60000,nt=30000,Mt=0,Gt=Date.now();function jr(){if(g)return;let k={...E.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:r,RPX_WORKER_REGISTRYDIR:i,RPX_WORKER_HTTPSPORT:String(n),RPX_WORKER_HOSTNAME:o,RPX_WORKER_VERBOSE:a?"1":"0"},We=Bun.spawn(bS(),{env:k,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(Ee,Ii){if(g)return;let _i=y.indexOf(Ee);if(_i!==-1)y.splice(_i,1);let ji=Date.now();if(ji-Gt>xt)Gt=ji,Mt=0;if(Mt++,Mt>J){x.error(`rpx: worker keeps exiting (code ${Ii}); giving up after ${J} restarts in ${Math.round(xt/1000)}s`);return}let qt=Math.min(nt,100*2**Math.min(Mt,8));m("daemon",`worker exited (code ${Ii}); respawning in ${qt}ms (restart ${Mt}/${J})`,a),setTimeout(jr,qt).unref?.()}});y.push(We)}for(let k=0;k<l;k++)jr();if(a)x.success(`rpx coordinator listening on https://${o}:${n} via ${l} worker(s)${ae?` (http→https on :${s})`:""}`),x.info(`pid file: ${f}`);let Bi,Bt=new Promise((k)=>{Bi=k});async function st(){if(g)return Bt;if(g=!0,clearInterval(N),D.close(),ae?.stop(!1),w("SIGTERM"),await Promise.race([Promise.all(y.map((k)=>k.exited)),new Promise((k)=>setTimeout(k,3000))]),w("SIGKILL"),await Ir({rpxDir:r,verbose:a}).catch((k)=>{m("daemon",`DNS teardown failed: ${k}`,a)}),await Mr(r),await ye.unlink(ml(r)).catch(()=>{}),a)x.info("rpx coordinator stopped");return Bi(),Bt}let It=(k)=>{m("daemon",`coordinator received ${k}, shutting down`,a),st().catch(()=>{})};return E.once("SIGINT",It),E.once("SIGTERM",It),{stop:st,done:Bt,httpsPort:n,httpPort:s,pidPath:f,ensureCert:(k)=>T?T.ensureCert(k):Promise.resolve(!1),listSites:()=>[]}}function $S(){let e=E.execPath,t=it.basename(e).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&E.argv[1])return[e,E.argv[1],"daemon:start"];return[e,"daemon:start"]}async function uA(e={}){let t=e.rpxDir??Ae(),r=e.verbose??!1;await _r({rpxDir:t,verbose:r}).catch((f)=>{m("daemon",`DNS reconcile before ensureDaemonRunning: ${f}`,r)});let i=await Br(t);if(i!==null&&Pe(i))return m("daemon",`ensureDaemonRunning: already running pid=${i}`,r),{pid:i,spawned:!1};if(i!==null)m("daemon",`ensureDaemonRunning: clearing stale pid=${i}`,r),await Mr(t);await ye.mkdir(t,{recursive:!0});let n=e.spawnCommand??$S();if(n.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");m("daemon",`spawning daemon: ${n.join(" ")}`,r);let s=vm(n[0],n.slice(1),{detached:!0,stdio:"ignore",cwd:e.spawnCwd??E.cwd(),env:e.spawnEnv?{...E.env,...e.spawnEnv}:E.env});s.unref();let o=null;s.once("error",(f)=>{o=f});let a=e.startupTimeoutMs??5000,c=e.pollIntervalMs??50,l=Date.now()+a;while(Date.now()<l){if(o)throw o;let f=await Br(t);if(f!==null&&Pe(f))return m("daemon",`daemon registered with pid=${f}`,r),{pid:f,spawned:!0};await new Promise((u)=>setTimeout(u,c))}if(o)throw o;throw Error(`rpx daemon failed to start within ${a}ms (rpxDir=${t})`)}async function hA(e={}){let t=e.rpxDir??Ae(),r=e.verbose??!1,i=e.timeoutMs??5000,n=e.pollIntervalMs??50,s=e.forceAfterTimeout??!0,o=await Br(t);if(o===null||!Pe(o)){if(o!==null)await Mr(t);return await _r({rpxDir:t,verbose:r}).catch(()=>{}),{stopped:!1,pid:o,forced:!1}}try{E.kill(o,"SIGTERM")}catch(c){let l=c.code;if(l==="ESRCH")return await Mr(t),{stopped:!1,pid:o,forced:!1};if(l==="EPERM")Dt(`kill -TERM ${o}`);else throw c}let a=Date.now()+i;while(Date.now()<a){if(!Pe(o))return m("daemon",`daemon pid=${o} stopped cleanly`,r),{stopped:!0,pid:o,forced:!1};await new Promise((c)=>setTimeout(c,n))}if(!s)throw Error(`rpx daemon (pid=${o}) did not exit within ${i}ms`);m("daemon",`daemon pid=${o} did not exit, escalating to SIGKILL`,r);try{E.kill(o,"SIGKILL")}catch(c){let l=c.code;if(l==="EPERM")Dt(`kill -KILL ${o}`);else if(l!=="ESRCH")throw c}return await Mr(t),await Ir({rpxDir:t,verbose:r}).catch((c)=>{m("daemon",`DNS teardown after SIGKILL: ${c}`,r)}),{stopped:!0,pid:o,forced:!0}}async function dA(e={}){let t=e.rpxDir??Ae();if(await gS(t))return;await _r({rpxDir:t,verbose:e.verbose})}import*as Lt from"node:fs/promises";import{homedir as ES}from"node:os";import*as gl from"node:path";var qs=1,xS="dns-state.json",Em=["com","test","dev","app","page","local","localhost","example","invalid"];function xm(){return gl.join(ES(),".stacks","rpx")}function pl(e=xm()){return gl.join(e,xS)}async function Ys(e=xm()){try{let t=await Lt.readFile(pl(e),"utf8"),r=JSON.parse(t);if(r.version!==qs||!Array.isArray(r.resolvers))return null;return{version:qs,resolvers:r.resolvers.filter((i)=>typeof i==="string"),domains:Array.isArray(r.domains)?r.domains.filter((i)=>typeof i==="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 Tm(e,t){await Lt.mkdir(e,{recursive:!0}),await Lt.writeFile(pl(e),`${JSON.stringify(t,null,2)}
307
+ `,"utf8")}async function yl(e){await Lt.rm(pl(e),{force:!0})}function Pm(e){let t=e.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}var TS=new Set(["test","localhost","local","example","invalid","internal","home","lan"]);function PS(e){let t=Pm(e);if(!t)return null;let r=t.split(".");if(r.length<2)return null;let i=r[r.length-1];if(TS.has(i))return r.slice(-2).join(".");return t}function wl(e){let t=new Set;for(let r of e){let i=PS(r);if(i)t.add(i)}return Array.from(t).sort()}function vl(e){let t=new Set;for(let r of e){let i=Pm(r);if(i)t.add(i)}return Array.from(t).sort()}var Xs=15353,AS="# managed-by: rpx",Nm="/etc/resolver",Re=null,Js=new Set;function Dm(e){return{id:e.readUInt16BE(0),flags:e.readUInt16BE(2),qdcount:e.readUInt16BE(4),ancount:e.readUInt16BE(6),nscount:e.readUInt16BE(8),arcount:e.readUInt16BE(10)}}function Om(e,t,r=0){let i=[],n=t,s=0;while(!0){if(n>=e.length||++s>128)break;let o=e[n];if(o===0){n++;break}if((o&192)===192){if(n+1>=e.length||r>=10)break;let a=e.readUInt16BE(n)&16383,{name:c}=Om(e,a,r+1);if(c)i.push(c);n+=2;break}if(n++,n+o>e.length)break;i.push(e.subarray(n,n+o).toString("ascii")),n+=o}return{name:i.join("."),newOffset:n}}function RS(e,t){let{name:r,newOffset:i}=Om(e,t),n=e.readUInt16BE(i),s=e.readUInt16BE(i+2);return{question:{name:r,type:n,class:s},newOffset:i+4}}function Li(e){let t=e.split("."),r=[];for(let i of t)r.push(Buffer.from([i.length])),r.push(Buffer.from(i,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function kS(e,t,r){let i=[],n=Buffer.alloc(12);n.writeUInt16BE(e,0),n.writeUInt16BE(33152,2),n.writeUInt16BE(1,4),n.writeUInt16BE(1,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),i.push(n),i.push(Li(t.name));let s=Buffer.alloc(4);s.writeUInt16BE(t.type,0),s.writeUInt16BE(t.class,2),i.push(s),i.push(Li(t.name));let o=Buffer.alloc(10);if(o.writeUInt16BE(t.type,0),o.writeUInt16BE(1,2),o.writeUInt32BE(300,4),t.type===1){o.writeUInt16BE(4,8),i.push(o);let a=r.split(".").map((c)=>Number.parseInt(c,10));i.push(Buffer.from(a))}else if(t.type===28)o.writeUInt16BE(16,8),i.push(o),i.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return n.writeUInt16BE(33155,2),n.writeUInt16BE(0,6),Buffer.concat([n,Li(t.name),s]);return Buffer.concat(i)}function NS(e,t){let r=[],i=Buffer.alloc(12);i.writeUInt16BE(e,0),i.writeUInt16BE(33155,2),i.writeUInt16BE(1,4),i.writeUInt16BE(0,6),i.writeUInt16BE(0,8),i.writeUInt16BE(0,10),r.push(i),r.push(Li(t.name));let n=Buffer.alloc(4);return n.writeUInt16BE(t.type,0),n.writeUInt16BE(t.class,2),r.push(n),Buffer.concat(r)}async function DS(e,t){if(Et.platform!=="darwin")return!1;let r=vl(e);if(r.length===0)return!1;if(Re){for(let i of r)Js.add(i);return m("dns","DNS server already running — merged domains",t),!0}return Js=new Set(r),new Promise((i)=>{Re=Am.createSocket("udp4"),Re.on("error",(n)=>{m("dns",`DNS server error: ${n.message}`,t),Re?.close(),Re=null,i(!1)}),Re.on("message",(n,s)=>{try{let o=Dm(n),{question:a}=RS(n,12);m("dns",`Query for ${a.name} type ${a.type} from ${s.address}`,t);let c=a.name.toLowerCase(),l=!1;for(let u of Js)if(c===u||c.endsWith(`.${u}`)){l=!0;break}let f;if(l&&(a.type===1||a.type===28))f=kS(o.id,a,"127.0.0.1"),m("dns",`Responding with localhost for ${a.name}`,t);else f=NS(o.id,a),m("dns",`NXDOMAIN for ${a.name}`,t);Re?.send(f,s.port,s.address)}catch(o){m("dns",`Error processing DNS query: ${o}`,t)}}),Re.on("listening",()=>{let n=Re?.address();m("dns",`DNS server listening on ${n?.address}:${n?.port}`,t),i(!0)});try{Re.bind(Xs,"127.0.0.1")}catch(n){m("dns",`Failed to bind DNS server: ${n}`,t),i(!1)}})}function Fm(e){if(Re)m("dns","Stopping DNS server",e),Re.close(),Re=null,Js=new Set}function SA(){return Re!==null}async function OS(e,t=500){let r=e.trim().toLowerCase().replace(/\.$/,"");if(!r)return!1;return new Promise((i)=>{let n=Am.createSocket("udp4"),s=setTimeout(()=>{n.close(),i(!1)},t);n.on("message",(a)=>{clearTimeout(s),n.close();try{let c=Dm(a);i(c.ancount>0)}catch{i(!1)}}),n.on("error",()=>{clearTimeout(s),n.close(),i(!1)});let o=FS(r,1);n.send(o,Xs,"127.0.0.1",(a)=>{if(a)clearTimeout(s),n.close(),i(!1)})})}function FS(e,t){let r=Buffer.alloc(12);r.writeUInt16BE(1,0),r.writeUInt16BE(256,2),r.writeUInt16BE(1,4);let i=Buffer.concat([Li(e),Buffer.from([0,t,0,1])]);return Buffer.concat([r,i])}function LS(){return`${AS}
308
+ nameserver 127.0.0.1
309
+ port ${Xs}
310
+ `}function Mi(e){return km.join(Nm,e)}function MS(e){return e.includes("127.0.0.1")&&e.includes(String(Xs))}async function BS(e){try{return await Rm.readFile(Mi(e),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function bl(e){if(Et.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:r,isProcessElevated:i}=await import("./chunk-er1mtkha.js");if(!i()&&!r()){m("dns","Cannot flush DNS cache without SUDO_PASSWORD",e);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),m("dns","DNS cache flushed",e)}catch(n){m("dns",`Could not flush DNS cache: ${n}`,e)}}function Lm(e){if(!/^[a-z0-9.-]+$/.test(e))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(e)}`)}async function IS(e,t){Lm(e);let{execSudoSync:r}=await import("./chunk-er1mtkha.js"),i=LS().replace(/\n/g,"\\n"),n=`bash -c 'mkdir -p ${Nm} && printf "%b" "${i}" > ${Mi(e)}'`;r(n),m("dns",`Created ${Mi(e)}`,t)}async function _S(e,t){Lm(e);let{execSudoSync:r}=await import("./chunk-er1mtkha.js");r(`rm -f ${Mi(e)}`),m("dns",`Removed ${Mi(e)}`,t)}async function $A(e,t){return Bm({domains:t??[],verbose:e})}async function jS(e,t){if(Et.platform!=="darwin")return!0;let{getSudoPassword:r,isProcessElevated:i}=await import("./chunk-er1mtkha.js");if(!i()&&!r())return m("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let n of e)await IS(n,t);return await bl(t),!0}catch(n){return m("dns",`Failed to create resolver file: ${n}`,t),!1}}async function Cl(e,t){if(Et.platform!=="darwin")return;let{getSudoPassword:r,isProcessElevated:i}=await import("./chunk-er1mtkha.js");if(!i()&&!r())return;try{for(let n of e)await _S(n,t);await bl(t)}catch(n){m("dns",`Failed to remove resolver files: ${n}`,t)}}async function Mm(e){if(Et.platform!=="darwin")return[];let t=[];for(let r of Em){let i=await BS(r);if(i&&MS(i))await Cl([r],e),t.push(r)}return t}async function Bm(e){let t=e.rpxDir??Ae(),r=vl(e.domains);if(r.length===0)return!1;let i=wl(r),n=await DS(r,e.verbose);if(!n){let a=r[0];if(a&&await OS(a))n=!0;else m("dns","Dev DNS server not available on 127.0.0.1:15353",e.verbose)}if(!n)return!1;if(!await jS(i,e.verbose))return!1;let o={version:qs,resolvers:i,domains:r,ownerPid:e.ownerPid??Et.pid,updatedAt:new Date().toISOString()};return await Tm(t,o),!0}async function Fi(e,t={}){let r=e.map((c)=>c.to).filter(Boolean),i=t.rpxDir??Ae(),n=wl(r),a=((await Ys(i))?.resolvers??[]).filter((c)=>!n.includes(c));if(a.length>0)await Cl(a,t.verbose);if(n.length===0){Fm(t.verbose),await yl(i);return}await Bm({domains:r,rpxDir:i,verbose:t.verbose,ownerPid:t.ownerPid??Et.pid})}async function Ir(e={}){let t=e.rpxDir??Ae();Fm(e.verbose);let i=(await Ys(t))?.resolvers??[];await Cl(i,e.verbose),await Mm(e.verbose),await yl(t)}async function EA(e){await Ir({verbose:e})}async function _r(e={}){let t=e.rpxDir??Ae(),r=await Ys(t),i=r?.ownerPid!=null&&Pe(r.ownerPid);if(r&&!i){m("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,e.verbose),await Ir(e);return}let n=await Mm(e.verbose);if(n.length>0)m("dns",`reconcile: removed legacy TLD resolvers: ${n.join(", ")}`,e.verbose);await bl(e.verbose)}
311
+ export{x as a,id as b,lb as c,Wt as d,bc as e,Cc as f,fb as g,ub as h,tt as i,St as j,Sc as k,yi as l,$c as m,nd as n,Rs as o,wi as p,vi as q,Ec as r,Ac as s,ud as t,hd as u,bi as v,ET as w,Rc as x,xT as y,TT as z,md as A,kc as B,Nc as C,Dc as D,PT as E,Ns as F,pd as G,yd as H,wd as I,Ds as J,Ci as K,vd as L,Oc as M,kb as N,Sd as O,$d as P,MT as Q,Dd as R,Od as S,iC as T,nC as U,sC as V,Fd as W,Id as X,Bc as Y,Ic as Z,_d as _,Kd as $,Ls as aa,_c as ba,Wd as ca,Vt as da,pC as ea,jc as fa,Uc as ga,Kc as ha,Hd as ia,Ms as ja,Hc as ka,Bs as la,yC as ma,Vc as na,zc as oa,Gc as pa,zd as qa,_s as ra,SC as sa,$C as ta,EC as ua,xC as va,TC as wa,AC as xa,Jc as ya,RC as za,kC as Aa,DC as Ba,Xc as Ca,Qc as Da,Yd as Ea,jC as Fa,UC as Ga,WC as Ha,el as Ia,dP as Ja,tm as Ka,tl as La,rm as Ma,pP as Na,Ft as Oa,il as Pa,Pe as Qa,nm as Ra,sl as Sa,qC as Ta,$t as Ua,Pi as Va,Ws as Wa,al as Xa,Lr as Ya,cm as Za,lm as _a,um as $a,Di as ab,gm as bb,hS as cb,dS as db,IP as eb,_P as fb,jP as gb,UP as hb,Oi as ib,qs as jb,Em as kb,Pm as lb,PS as mb,wl as nb,vl as ob,Xs as pb,AS as qb,DS as rb,Fm as sb,SA as tb,OS as ub,Mi as vb,MS as wb,$A as xb,Mm as yb,Bm as zb,Fi as Ab,Ir as Bb,EA as Cb,_r as Db,Ae as Eb,Gs as Fb,Br as Gb,gS as Hb,Cm as Ib,Mr as Jb,fA as Kb,$S as Lb,uA as Mb,hA as Nb,dA as Ob};