@stacksjs/rpx 0.11.28 → 0.11.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +122 -102
- package/dist/{chunk-6nvjwawp.js → chunk-22h4jf2c.js} +1 -1
- package/dist/chunk-9dh9jhc6.js +252 -0
- package/dist/{chunk-1b00ya21.js → chunk-ws2cmbxh.js} +1 -1
- package/dist/{chunk-2yk7jygq.js → chunk-z86swbd8.js} +1 -1
- package/dist/hosts.d.ts +70 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +2 -9
- package/package.json +1 -1
- package/dist/chunk-mnfbk2xf.js +0 -224
package/dist/chunk-mnfbk2xf.js
DELETED
|
@@ -1,224 +0,0 @@
|
|
|
1
|
-
import{Ab as Ff,Bb as Ey,Db as ky,Eb as Ty,ob as g,rb as Gn,sb as T,tb as Bu,xb as Ay,yb as i0}from"./chunk-2yk7jygq.js";import Xu from"node:dgram";import*as Fu from"node:fs/promises";import*as Wu from"node:path";import*as ut from"node:process";import{spawn as mu}from"node:child_process";import*as Ai from"node:fs/promises";import{homedir as Cu}from"node:os";import*as bi from"node:path";import*as R from"node:process";var F={info:(...i)=>console.log("[info]",...i),success:(...i)=>console.log("[success]",...i),warn:(...i)=>console.warn("[warn]",...i),error:(...i)=>console.error("[error]",...i),debug:(...i)=>console.debug("[debug]",...i),log:(...i)=>console.log(...i),start:(...i)=>console.log("[start]",...i),box:(...i)=>console.log("[box]",...i)};import{execSync as oc}from"node:child_process";import v from"node:fs/promises";import*as pc from"node:os";import{homedir as En}from"node:os";import*as Yy from"node:path";import{join as b}from"node:path";import*as gi from"node:process";import{createRequire as Lu}from"node:module";import{Resolver as vf}from"node:dns/promises";import{createHash as xu,sign as du}from"node:crypto";import{createHash as ku}from"node:crypto";import{sign as Vu}from"node:crypto";import{generateKeyPairSync as d$,X509Certificate as ie}from"node:crypto";import Zf from"node:os";import of from"node:path";import{existsSync as L0,statSync as g0}from"fs";import{existsSync as ne,mkdirSync as Cm,readdirSync as Rm,readFileSync as re,writeFileSync as sm}from"fs";import{homedir as qt}from"os";import{dirname as Sm,resolve as Xi}from"path";import Gr from"process";import{existsSync as x0,statSync as d0}from"fs";import{existsSync as Ul,mkdirSync as fe,readdirSync as le,writeFileSync as ce}from"fs";import{homedir as Lt}from"os";import{dirname as k0,resolve as Ti}from"path";import Wt from"process";import{join as $e,relative as we,resolve as V0}from"path";import Cr from"process";import{existsSync as k$,mkdirSync as zm,readdirSync as Om,writeFileSync as Gm}from"fs";import{homedir as pf}from"os";import{dirname as qm,resolve as Ei}from"path";import Nn from"process";import{join as he,relative as ye,resolve as D0}from"path";import Rr from"process";import{existsSync as V$,mkdirSync as km,readdirSync as Vm,writeFileSync as Dm}from"fs";import{dirname as Qm,resolve as sr}from"path";import jl from"process";import{Buffer as At}from"buffer";import{createCipheriv as ue,createDecipheriv as ee,randomBytes as il}from"crypto";import{closeSync as tl,createReadStream as b0,createWriteStream as Ae,existsSync as nl,fsyncSync as Q0,openSync as P0,writeFileSync as Ee}from"fs";import{access as Te,constants as v0,mkdir as Ye,readdir as Zn,rename as Z0,stat as gt,unlink as on,writeFile as rl}from"fs/promises";import{join as xt}from"path";import $i from"process";import{pipeline as Be}from"stream/promises";import{createGzip as o0}from"zlib";import dt from"process";import oi from"process";import{Buffer as Pi}from"buffer";import{createCipheriv as me,createDecipheriv as Ce,randomBytes as fl}from"crypto";import{closeSync as ll,createReadStream as p0,createWriteStream as Re,existsSync as pn,fsyncSync as i$,openSync as t$,writeFileSync as se}from"fs";import{access as Ue,constants as n$,mkdir as je,readdir as ir,rename as r$,stat as kt,unlink as tr,writeFile as cl}from"fs/promises";import{isAbsolute as Se,join as Vt,resolve as ae}from"path";import H from"process";import{pipeline as Ne}from"stream/promises";import{createGzip as f$}from"zlib";import Dt from"process";import pi from"process";import nr from"process";import{existsSync as rr}from"fs";import{resolve as $l}from"path";import{existsSync as Xe}from"fs";import{existsSync as Fe,readdirSync as We}from"fs";import{extname as wl,resolve as l$}from"path";import Je from"process";import{join as _e,relative as Ie,resolve as c$}from"path";import Ur from"process";import{Buffer as vi}from"buffer";import{createCipheriv as Ke,createDecipheriv as ze,randomBytes as hl}from"crypto";import{closeSync as yl,createReadStream as $$,createWriteStream as Oe,existsSync as fr,fsyncSync as w$,openSync as h$,writeFileSync as Ge}from"fs";import{access as Me,constants as y$,mkdir as He,readdir as lr,rename as u$,stat as bt,unlink as cr,writeFile as ul}from"fs/promises";import{isAbsolute as qe,join as Qt,resolve as Le}from"path";import q from"process";import{pipeline as ge}from"stream/promises";import{createGzip as e$}from"zlib";import Pt from"process";import it from"process";import $r from"process";import{existsSync as wr}from"fs";import{resolve as el}from"path";import{existsSync as xe}from"fs";import{exec as yA}from"node:child_process";import zl from"node:fs";import uA from"node:os";import zi from"node:path";import Xw from"node:process";import{promisify as eA}from"node:util";import pt from"node:crypto";import tt from"node:fs";import Ml from"node:path";import OA from"node:crypto";import GA from"node:fs";import MA from"node:tls";import{execSync as LA}from"node:child_process";import zr from"node:os";var gu=Lu(import.meta.url);async function J$(i,t,n={}){let r=n.timeoutMs??120000,f=n.intervalMs??3000,l=i.split(".").slice(-2).join("."),c;try{let h=new vf,y=await h.resolveNs(l),u=(await Promise.all(y.map((e)=>h.resolve4(e).catch(()=>[])))).flat();if(u.length>0)c=new vf,c.setServers(u)}catch{}let $=Date.now()+r,w=c??new vf;for(;;){try{if((await w.resolveTxt(i)).some((h)=>h.join("")===t))return!0}catch{}if(Date.now()>=$)return!1;await new Promise((h)=>setTimeout(h,f))}}class an{tokens=new Map;add(i,t){this.tokens.set(i,t)}get(i){return this.tokens.get(i)}remove(i){this.tokens.delete(i)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(i){let t=i.indexOf(an.PATH_PREFIX);if(t===-1)return;let n=i.slice(t+an.PATH_PREFIX.length);return this.get(n)}}var Or=new an;function ur(i){return(typeof i==="string"?Buffer.from(i,"utf8"):Buffer.from(i)).toString("base64url")}function ml(i){return Buffer.from(i,"base64url")}function _$(i){let t=i.export({format:"jwk"});if(t.kty!=="EC"||t.crv!=="P-256"||!t.x||!t.y)throw Error(`Expected a P-256 EC public key, got kty=${t.kty} crv=${t.crv}`);return{crv:"P-256",kty:"EC",x:t.x,y:t.y}}function I$(i){let t=`{"crv":"${i.crv}","kty":"${i.kty}","x":"${i.x}","y":"${i.y}"}`;return xu("sha256").update(t).digest("base64url")}function K$(i){let{protectedHeader:t,payload:n,privateKey:r}=i,f=ur(JSON.stringify(t)),l=n===""?"":ur(JSON.stringify(n)),c=`${f}.${l}`,$=du("sha256",Buffer.from(c),{key:r,dsaEncoding:"ieee-p1363"});return{protected:f,payload:l,signature:ur($)}}var z$="https://acme-staging-v02.api.letsencrypt.org/directory",O$="https://acme-v02.api.letsencrypt.org/directory";class Br extends Error{problem;httpStatus;constructor(i,t,n){super(i);this.name="AcmeError",this.problem=t,this.httpStatus=n}}class mr{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor(i){this.directoryUrl=i.directoryUrl,this.accountKey=i.accountKey,this.jwk=_$(i.accountPublicKey),this.thumbprint=I$(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let i=await fetch(this.directoryUrl);if(!i.ok)throw Error(`Failed to fetch ACME directory: HTTP ${i.status}`);return this.directoryCache=await i.json(),this.directoryCache}async newNonce(){let i=await this.directory(),t=(await fetch(i.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!t)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=t,t}async ensureNonce(){if(this.nonce){let i=this.nonce;return this.nonce=void 0,i}return this.newNonce()}async signedPost(i){let{url:t,payload:n,useJwk:r}=i,f={alg:"ES256",nonce:await this.ensureNonce(),url:t};if(r)f.jwk=this.jwk;else f.kid=this.requireKid();let l=K$({protectedHeader:f,payload:n,privateKey:this.accountKey}),c=await fetch(t,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(l)}),$=c.headers.get("replay-nonce");if($)this.nonce=$;let w=c.headers.get("content-type")??"",h;if(w.includes("application/pem-certificate-chain")||w.startsWith("text/"))h=await c.text();else{let y=await c.text();h=y?JSON.parse(y):{}}if(c.status>=400){let y=h??{};throw new Br(`ACME request to ${t} failed (HTTP ${c.status}): ${y.type??""} ${y.detail??""}`.trim(),y,c.status)}return{status:c.status,headers:c.headers,body:h,location:c.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(i={}){let t=await this.directory(),n={termsOfServiceAgreed:!0};if(i.email)n.contact=[`mailto:${i.email}`];let r=await this.signedPost({url:t.newAccount,payload:n,useJwk:!0});if(!r.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=r.location,this.accountKid}async newOrder(i){let t=await this.directory(),n={identifiers:i.map((f)=>({type:"dns",value:f}))},r=await this.signedPost({url:t.newOrder,payload:n});if(!r.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:r.body,orderUrl:r.location}}async getAuthorization(i){return(await this.signedPost({url:i,payload:""})).body}keyAuthorization(i){return`${i}.${this.thumbprint}`}dns01TxtValue(i){return ku("sha256").update(this.keyAuthorization(i)).digest("base64url")}async notifyChallengeReady(i){await this.signedPost({url:i,payload:{}})}async pollAuthorization(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let l=await this.getAuthorization(i);if(l.status==="valid")return;if(l.status==="invalid"){let c=l.challenges.find(($)=>$.status==="invalid");throw new Br(`Authorization for ${l.identifier.value} became invalid: ${c?.error?.detail??"unknown reason"}`,c?.error??{},0)}await q0(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for authorization ${i} to become valid`)}async finalizeOrder(i,t){return(await this.signedPost({url:i,payload:{csr:t}})).body}async getOrder(i){return(await this.signedPost({url:i,payload:""})).body}async pollOrder(i,t={}){let n=t.timeoutMs??60000,r=t.intervalMs??2000,f=Date.now()+n;while(Date.now()<f){let l=await this.getOrder(i);if(l.status==="valid"){if(!l.certificate)throw Error("ACME order is valid but has no certificate URL");return l.certificate}if(l.status==="invalid")throw Error(`ACME order ${i} became invalid`);await q0(r),r=Math.min(r*1.5,1e4)}throw Error(`Timed out waiting for order ${i} to become valid`)}async downloadCertificate(i){let t=await this.signedPost({url:i,payload:""});return typeof t.body==="string"?t.body:String(t.body)}static selectChallenge(i,t){let n=i.challenges.find((r)=>r.type===t);if(!n)throw Error(`No ${t} challenge available for ${i.identifier.value}`);return n}}function G$(i){let t=i.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],n=t[0];if(!n)return{certPem:`${i.trim()}
|
|
2
|
-
`,chainPem:""};let r=`${n.trim()}
|
|
3
|
-
`,f=t.slice(1).map((l)=>l.trim()).join(`
|
|
4
|
-
`);return{certPem:r,chainPem:f?`${f}
|
|
5
|
-
`:""}}function M$(i){return`_acme-challenge.${i.startsWith("*.")?i.slice(2):i}`}function q0(i){return new Promise((t)=>setTimeout(t,i))}function Du(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Yt(i,t){return Buffer.concat([Buffer.from([i]),Du(t.length),t])}function H$(i){let t;if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=[],r=i;while(r>0)n.unshift(r&255),r>>=8;if(n[0]&128)n.unshift(0);t=Buffer.from(n)}else if(t=i.length===0?Buffer.from([0]):i,t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Yt(2,t)}function Ft(i){let t=i.split(".").map(Number);if(t.length<2)throw Error(`Invalid OID: ${i}`);let n=[40*t[0]+t[1]];for(let r=2;r<t.length;r++){let f=t[r],l=[f&127];f=Math.floor(f/128);while(f>0)l.unshift(f&127|128),f=Math.floor(f/128);n.push(...l)}return Yt(6,Buffer.from(n))}function Ni(...i){return Yt(48,Buffer.concat(i))}function Cl(...i){return Yt(49,Buffer.concat(i))}function Rl(i){return Yt(3,Buffer.concat([Buffer.from([0]),i]))}function q$(i){return Yt(4,i)}function L$(i){return Yt(12,Buffer.from(i,"utf8"))}function sl(i,t,n){let r=128|(n?32:0)|i;return Yt(r,t)}var bu="1.2.840.10045.2.1",Qu="1.2.840.10045.3.1.7",Pu="1.2.840.10045.4.3.2",vu="2.5.4.3",Zu="1.2.840.113549.1.9.14",ou="2.5.29.17";function pu(i){let t=i.export({format:"jwk"});if(!t.x||!t.y)throw Error("Public key JWK is missing x/y coordinates");let n=ml(t.x),r=ml(t.y);if(n.length!==32||r.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${n.length} y=${r.length}`);return Buffer.concat([Buffer.from([4]),n,r])}function g$(i){let{domains:t,publicKey:n,privateKey:r}=i;if(t.length===0)throw Error("At least one domain is required to build a CSR");let f=Ni(Cl(Ni(Ft(vu),L$(t[0])))),l=Ni(Ni(Ft(bu),Ft(Qu)),Rl(pu(n))),c=t.map((E)=>sl(2,Buffer.from(E,"ascii"),!1)),$=Ni(...c),w=Ni(Ft(ou),q$($)),h=Ni(w),y=Ni(Ft(Zu),Cl(h)),u=sl(0,y,!0),e=Ni(H$(0),f,l,u),A=Vu("sha256",e,r),B=Ni(Ft(Pu));return Ni(e,B,Rl(A))}function x$(i){return g$(i).toString("base64url")}function te(i){if(i){let{createPrivateKey:f,createPublicKey:l}=gu("node:crypto"),c=f(i),$=l(c);return{privateKey:c,publicKey:$,pem:i}}let{privateKey:t,publicKey:n}=d$("ec",{namedCurve:"P-256"}),r=t.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:t,publicKey:n,pem:r}}async function Hl(i){let{domains:t,method:n}=i;if(t.length===0)throw Error("obtainCertificate requires at least one domain");if(n==="dns-01"&&!i.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(t.some((u)=>u.startsWith("*."))&&n!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let r=i.directoryUrl??(i.staging===!1?O$:z$),f=te(i.accountKeyPem),l=new mr({directoryUrl:r,accountKey:f.privateKey,accountPublicKey:f.publicKey});await l.newAccount({email:i.email});let{order:c,orderUrl:$}=await l.newOrder(t),w=i.http01Store??Or,h=[],y=[];try{for(let j of c.authorizations){let X=await l.getAuthorization(j);if(X.status==="valid")continue;let M=mr.selectChallenge(X,n);if(n==="dns-01"){let o=M$(X.identifier.value),ki=l.dns01TxtValue(M.token);await i.dnsProvider.setTxt(o,ki),h.push({name:o,value:ki}),await J$(o,ki,{timeoutMs:i.dnsPropagationTimeoutMs??120000})}else w.add(M.token,l.keyAuthorization(M.token)),y.push(M.token);await l.notifyChallengeReady(M.url),await l.pollAuthorization(j,{timeoutMs:i.timeoutMs})}let{privateKey:u,publicKey:e}=d$("ec",{namedCurve:"P-256"}),A=x$({domains:t,publicKey:e,privateKey:u});await l.finalizeOrder(c.finalize,A);let B=await l.pollOrder($,{timeoutMs:i.timeoutMs}),E=await l.downloadCertificate(B),{certPem:Y,chainPem:m}=G$(E),C=m?`${Y}${m}`:Y,a=u.export({format:"pem",type:"pkcs8"}).toString(),N=new Date(new ie(Y).validTo);return{certPem:Y,keyPem:a,chainPem:m,fullChainPem:C,accountKeyPem:f.pem,notAfter:N}}finally{for(let{name:u,value:e}of h)await i.dnsProvider?.removeTxt(u,e).catch(()=>{});for(let u of y)w.remove(u)}}class D${cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),l=r??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!L0(i))return!0;return g0(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=L0(n)?g0(n):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class b${metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-r;return this.recordMetric({operation:i,duration:c,timestamp:f,...n}),l}catch(l){let c=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...n}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var jr=new D$,ql=new b$,de=Object.defineProperty,ke=(i)=>i;function Ve(i,t){this[i]=ke.bind(null,t)}var De=(i,t)=>{for(var n in t)de(i,n,{get:t[n],enumerable:!0,configurable:!0,set:Ve.bind(t,n)})},be=(i,t)=>()=>(i&&(t=i(i=0)),t),Q$={};De(Q$,{withErrorRecovery:()=>Z$,tryLoadConfig:()=>Y1,loadConfigWithResult:()=>E1,loadConfig:()=>nw,isRetryableError:()=>w1,isConfigNotFoundError:()=>$1,isBunfigError:()=>o$,globalPerformanceMonitor:()=>Jn,globalCache:()=>Zt,getEnvOrDefault:()=>h1,generateConfigTypes:()=>B1,defaultGeneratedDir:()=>yw,defaultConfigDir:()=>hw,deepMergeWithArrayStrategy:()=>kl,deepMerge:()=>p$,createLibraryConfig:()=>m1,config:()=>T1,bunfigPlugin:()=>C1,applyEnvVarsToConfig:()=>jn,TypeGenerationError:()=>Jl,SchemaValidationError:()=>Fn,PluginError:()=>Il,PerformanceMonitor:()=>gl,FileSystemError:()=>Wl,ErrorFactory:()=>Tt,EnvVarError:()=>Wr,EnvProcessor:()=>Mr,ConfigValidator:()=>Vl,ConfigValidationError:()=>Xl,ConfigNotFoundError:()=>Fr,ConfigMergeError:()=>Fl,ConfigLoader:()=>Dl,ConfigLoadError:()=>Xn,ConfigFileLoader:()=>Hr,ConfigCache:()=>Ll,CacheUtils:()=>fw,BunfigError:()=>Ui,BrowserConfigError:()=>_l,ArrayMergeStrategies:()=>$w});class Ll{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),l=r??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!x0(i))return!0;return d0(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=x0(n)?d0(n):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class gl{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-r;return this.recordMetric({operation:i,duration:c,timestamp:f,...n}),l}catch(l){let c=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...n}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function Qe(i,t={}){let n=Object.keys(t).sort().map((r)=>`${r}:${t[r]}`).join("|");return n?`${i}:${n}`:i}function Pe(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function ve(i){return i.getStats().size*2}function xl(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&V(t[0])&&"id"in t[0]&&t[0].id===3&&V(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(V(t)&&V(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(V(i)&&"arr"in i&&Array.isArray(i.arr)&&V(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&V(t[0])&&V(i[0])){let r=[...t];for(let f of i)if(V(f)&&"name"in f){if(!r.find((l)=>V(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(V(f)&&"path"in f){if(!r.find((l)=>V(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((l)=>Sr(l,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!V(t)||!V(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(V(f)&&V(n[r]))n[r]=xl(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&V(f[0])&&V(n[r][0])){let l=[...f];for(let c of n[r])if(V(c)&&"name"in c){if(!l.find(($)=>V($)&&("name"in $)&&$.name===c.name))l.push(c)}else if(V(c)&&"path"in c){if(!l.find(($)=>V($)&&("path"in $)&&$.path===c.path))l.push(c)}else if(!l.some(($)=>Sr($,c)))l.push(c);n[r]=l}else if(f.every((l)=>typeof l==="string")&&n[r].every((l)=>typeof l==="string")){let l=[...f];for(let c of n[r])if(!l.includes(c))l.push(c);n[r]=l}else n[r]=f;else n[r]=f}return n}function Sr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Sr(i[n],t[n]))return!1;return!0}if(V(i)&&V(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Sr(i[f],t[f]))return!1}return!0}return!1}function V(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function Ze(i,t){if(!V$(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return xl(t,r)}catch{return null}}catch{return null}}async function oe({name:i="",cwd:t,defaultConfig:n}){let r=t||jl.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],l=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of l)for(let $ of f){let w=sr(r,`${c}${$}`),h=await Ze(w,n);if(h!==null)return h}try{let c=sr(r,"package.json");if(V$(c)){let $=(await import(c))[i];if($&&typeof $==="object"&&!Array.isArray($))try{return xl(n,$)}catch{}}}catch{}return n}function pe(i,t={}){let n=Rr.cwd();while(n.includes("storage"))n=D0(n,"..");let r=D0(n,i||"");if(t?.relative)return ye(Rr.cwd(),r);return r}async function i1(){try{let i=await oe({name:"clarity",defaultConfig:Ar,cwd:Rr.cwd(),endpoint:"",headers:{}});return{...Ar,...i}}catch{return Ar}}function Q(){if(oi.env.NODE_ENV==="test"||oi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function t1(){if(oi.env.NODE_ENV==="test"||oi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof oi<"u"){let i=oi.type;if(i==="renderer"||i==="worker")return!1;return!!(oi.versions&&(oi.versions.node||oi.versions.bun))}return!1}class P${async format(i){let t=await t1(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:dt.pid,hostname:t(),environment:dt.env.NODE_ENV||"development",platform:dt.platform,version:dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:dt.env.NODE_ENV||dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ar{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...al},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new P$,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??$i.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Er,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Er};return{...Er,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:al.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let t=(async()=>{let r,f=0,l=3,c=1000;while(f<l)try{try{try{await Te(this.config.logDirectory,v0.F_OK|v0.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await Ye(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:At.from(i);try{if(!nl(this.currentLogFile))await rl(this.currentLogFile,"",{mode:420});if(r=P0(this.currentLogFile,"a",420),Ee(r,$,{flag:"a"}),Q0(r),r!==void 0)tl(r),r=void 0;if((await gt(this.currentLogFile)).size===0){if(await rl(this.currentLogFile,$,{flag:"w",mode:420}),(await gt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let h=w;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(f<l-1){let y=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,y);let u=c*2**f;await new Promise((e)=>setTimeout(e,u)),f++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(r!==void 0)try{tl(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch($){if(f===l-1){let h=$,y=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",y),$}f++;let w=c*2**(f-1);await new Promise((h)=>setTimeout(h,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return xt(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 xt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return xt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(Q())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,$])=>$.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(r.length>l)for(let[c]of r.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return il(16).toString("hex")}generateKey(){return il(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=il(16),r=ue("aes-256-gcm",t,n),f=At.concat([r.update(i,"utf8"),r.final()]),l=r.getAuthTag();return{encrypted:At.concat([n,f,l]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=o0(),f=[];r.on("data",(l)=>f.push(l)),r.on("end",()=>t(At.from(At.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(Q())return;let i=await gt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Zn(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,h)=>{let y=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${n}.${c}`;if(await gt(n).catch(()=>null))try{if(await Z0(n,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await on($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await rl(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=n.replace(/\.log$/,`-${f}.log`);if(await gt(n).catch(()=>null))await Z0(n,l)}if(this.currentLogFile=r,t.maxFiles){let f=(await Zn(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await on(xt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=b0(i),r=Ae(t),f=o0();await Be(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),nl(this.currentLogFile))try{let i=P0(this.currentLogFile,"r+");Q0(i),tl(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!Q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Zn(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await on(xt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?d.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(n)A.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)A.push(r.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=$i.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${n} ${f}`;else if(l==="info"||l==="success")h=`${n} ${r} ${f}`;else h=`${n} ${r} ${d.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,u=$(t).length,e=Math.max(1,w-2-y-u);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(l,c)=>{if(c==="%")return"%";if(r>=t.length)return l;let $=t[r++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(r<t.length)f+=` ${t.slice(r).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),l=this.formatFileTimestamp(r),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,n);if(this.fancy&&!Q()){let h=lw[i],y=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",u;switch(i){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:d.gray(c),level:i}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:d.green(c),level:i}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.error(u),$){let e=$.split(`
|
|
6
|
-
`);for(let A of e)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:d.gray(` ${A}`),level:i,showTimestamp:!1}))}break}}else if(!Q()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let w=`${l} ${this.environment}.${i.toUpperCase()}: ${c}
|
|
7
|
-
`;if($)w+=`${$}
|
|
8
|
-
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!Q()){let n=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:d.blue("◐"),tag:n,message:`${d.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),w=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
9
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.fancy&&!Q()){let h=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:d.green("✓"),tag:h,message:`${l}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!Q())console.error(w.trim());await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new ar(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(Q())throw Error("createReadStream is not supported in browser environments");if(!nl(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return b0(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=At.isBuffer(i)?i:At.from(i,"base64"),f=r.slice(0,16),l=r.slice(-16),c=r.slice(16,-16),$=ee("aes-256-gcm",n,f);return $.setAuthTag(l),At.concat([$.update(c),$.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Q()}isServerMode(){return!Q()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!Q()){let l=i.split(`
|
|
10
|
-
`),c=Math.max(...l.map((y)=>y.length))+2,$=`┌${"─".repeat(c)}┐`,w=`└${"─".repeat(c)}┘`,h=l.map((y)=>{let u=" ".repeat(c-y.length-2);return`│ ${y}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:d.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:d.cyan($)})),h.forEach((y)=>console.error(this.formatConsoleMessage({timestamp:n,message:d.cyan(y),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:d.cyan(w),showTimestamp:!1}))}else if(!Q())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let f=`${r} ${this.environment}.INFO: [BOX] ${i}
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(Q())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${d.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();$i.stdin.removeListener("data",n);try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!1)}catch{}$i.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof $i.stdin.setRawMode==="function")$i.stdin.setRawMode(!0)}catch{}$i.stdin.resume(),$i.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let f=/%([sdijfo%])/g,l=0;if(n=i.replace(f,(c,$)=>{if($==="%")return"%";if(l>=t.length)return c;let w=t[l++];switch($){case"s":return String(w);case"d":case"i":return Number(w).toString();case"j":case"o":return JSON.stringify(w,null,2);default:return c}}),l<t.length)n+=` ${t.slice(l).map((c)=>typeof c==="object"?JSON.stringify(c,null,2):String(c)).join(" ")}`}if(this.fancy&&!Q()){let f=this.options.showTags!==!1&&this.name?d.gray(this.formatTag(this.name)):"",l=d.blue("◐");console.error(`${l} ${f} ${d.cyan(n)}`)}let r=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(r)}progress(i,t=""){if(!this.enabled||!this.fancy||Q()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(r,f)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,r)),f!==void 0)this.activeProgressBar.message=f;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(r)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;if(this.activeProgressBar.current=this.activeProgressBar.total,r!==void 0)this.activeProgressBar.message=r;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(r,f="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q())return;$i.stdout.write(`${"\r".padEnd($i.stdout.columns||80)}\r`),this.log(f,r),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||Q()||!$i.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,l=d.green("━".repeat(r)),c=d.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${n}%`.padStart(4),h=i.message?` ${i.message}`:"",y=t||n===100?d.green("✓"):d.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${d.gray(this.formatTag(this.name))}`:"",e=`\r${y}${u} ${$} ${w}${h}`,A=$i.stdout.columns||80,B=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${B}`,$i.stdout.write(i.lastRenderedLine),t)$i.stdout.write(`
|
|
13
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||Q()||!$i.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(Q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zn(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=xt(this.config.logDirectory,r);if(i.before)try{if((await gt(f)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await on(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function er(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&L(t[0])&&"id"in t[0]&&t[0].id===3&&L(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(L(t)&&L(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(L(i)&&"arr"in i&&Array.isArray(i.arr)&&L(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&L(t[0])&&L(i[0])){let r=[...t];for(let f of i)if(L(f)&&"name"in f){if(!r.find((l)=>L(l)&&("name"in l)&&l.name===f.name))r.push(f)}else if(L(f)&&"path"in f){if(!r.find((l)=>L(l)&&("path"in l)&&l.path===f.path))r.push(f)}else if(!r.some((l)=>Nr(l,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!L(t)||!L(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(L(f)&&L(n[r]))n[r]=er(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&L(f[0])&&L(n[r][0])){let l=[...f];for(let c of n[r])if(L(c)&&"name"in c){if(!l.find(($)=>L($)&&("name"in $)&&$.name===c.name))l.push(c)}else if(L(c)&&"path"in c){if(!l.find(($)=>L($)&&("path"in $)&&$.path===c.path))l.push(c)}else if(!l.some(($)=>Nr($,c)))l.push(c);n[r]=l}else if(f.every((l)=>typeof l==="string")&&n[r].every((l)=>typeof l==="string")){let l=[...f];for(let c of n[r])if(!l.includes(c))l.push(c);n[r]=l}else n[r]=f;else n[r]=f}return n}function dl(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:er(i,t);if(Array.isArray(i))return n==="replace"?t:er(i,t);if(!L(t)||!L(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let l=t[f],c=r[f];if(l===null||l===void 0)continue;if(Array.isArray(l)||Array.isArray(c))if(n==="replace")r[f]=l;else r[f]=er(c,l);else if(L(l)&&L(c))r[f]=dl(c,l,n);else r[f]=l}return r}function Nr(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Nr(i[n],t[n]))return!1;return!0}if(L(i)&&L(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Nr(i[f],t[f]))return!1}return!0}return!1}function L(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function hr(i,t,n="replace"){if(!k$(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return dl(t,f,n)}catch{return null}}catch{return null}}function n1(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...t};function l(c,$=[]){let w={...c};for(let[h,y]of Object.entries(c)){let u=[...$,h],e=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),A=`${r}_${u.map(e).join("_")}`,B=`${r}_${u.map((E)=>E.toUpperCase()).join("_")}`;if(n)hi.info(`Checking environment variable ${A} for config ${i}.${u.join(".")}`);if(typeof y==="object"&&y!==null&&!Array.isArray(y))w[h]=l(y,u);else{let E=Nn.env[A]||Nn.env[B];if(E!==void 0){if(n)hi.info(`Using environment variable ${E?A:B} for config ${i}.${u.join(".")}`);if(typeof y==="number")w[h]=Number(E);else if(typeof y==="boolean")w[h]=E.toLowerCase()==="true";else if(Array.isArray(y))try{let Y=JSON.parse(E);if(Array.isArray(Y))w[h]=Y;else w[h]=E.split(",").map((m)=>m.trim())}catch{w[h]=E.split(",").map((Y)=>Y.trim())}else w[h]=E}}}return w}return l(f)}async function r1({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:l=!1,checkEnv:c=!0,arrayStrategy:$="replace"}){let w=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?n1(i,f,l):f,h=n||Nn.cwd(),y=[".ts",".js",".mjs",".cjs",".json"];if(l)hi.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${h}`);let u=[i,`.${i}`].filter(Boolean),e=[`${i}.config`,`.${i}.config`].filter(Boolean),A=t?[t,`.${t}`]:[],B=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([h,Ei(h,"config"),Ei(h,".config"),r?Ei(h,r):void 0].filter(Boolean)));for(let Y of E){if(l)hi.info(`Searching for configuration in: ${Y}`);let m=[Ei(h,"config"),Ei(h,".config")].concat(r?[Ei(h,r)]:[]).includes(Y)?[...u,...e,...A,...B]:[...e,...u,...B,...A];for(let C of m)for(let a of y){let N=Ei(Y,`${C}${a}`),j=await hr(N,w,$);if(j!==null){if(l)hi.success(`Configuration loaded from: ${N}`);return j}}}if(i){let Y=Ei(pf(),".config",i),m=["config",`${i}.config`];if(t)m.push(`${t}.config`);if(l)hi.info(`Checking user config directory: ${Y}`);for(let C of m)for(let a of y){let N=Ei(Y,`${C}${a}`),j=await hr(N,w,$);if(j!==null){if(l)hi.success(`Configuration loaded from user config directory: ${N}`);return j}}}if(i){let Y=Ei(pf(),".config"),m=[`.${i}.config`];if(t)m.push(`.${t}.config`);if(l)hi.info(`Checking user config directory for dotfile configs: ${Y}`);for(let C of m)for(let a of y){let N=Ei(Y,`${C}${a}`),j=await hr(N,w,$);if(j!==null){if(l)hi.success(`Configuration loaded from user config directory dotfile: ${N}`);return j}}}if(i){let Y=pf(),m=[`.${i}.config`,`.${i}`];if(t)m.push(`.${t}.config`),m.push(`.${t}`);if(l)hi.info(`Checking user home directory for dotfile configs: ${Y}`);for(let C of m)for(let a of y){let N=Ei(Y,`${C}${a}`),j=await hr(N,w,$);if(j!==null){if(l)hi.success(`Configuration loaded from user home directory: ${N}`);return j}}}try{let Y=Ei(h,"package.json");if(k$(Y)){let m=await import(Y),C=m[i];if(!C&&t){if(C=m[t],C&&l)hi.success(`Using alias "${t}" configuration from package.json`)}if(C&&typeof C==="object"&&!Array.isArray(C))try{if(l)hi.success(`Configuration loaded from package.json: ${C===m[i]?i:t}`);return dl(w,C,$)}catch(a){if(l)hi.warn("Failed to merge package.json config:",a)}}}catch(Y){if(l)hi.warn("Failed to load package.json:",Y)}if(l)hi.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function f1(i,t={}){let n=Cr.cwd();while(n.includes("storage"))n=V0(n,"..");let r=V0(n,i||"");if(t?.relative)return we(Cr.cwd(),r);return r}async function l1(){try{let i=await r1({name:"clarity",alias:"logging",defaultConfig:Tr,cwd:Cr.cwd()});return{...Tr,...i||{}}}catch{return Tr}}function p(){if(pi.env.NODE_ENV==="test"||pi.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function c1(){if(pi.env.NODE_ENV==="test"||pi.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pi<"u"){let i=pi.type;if(i==="renderer"||i==="worker")return!1;return!!(pi.versions&&(pi.versions.node||pi.versions.bun))}return!1}class v${async format(i){let t=await c1(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Dt.pid,hostname:t(),environment:Dt.env.NODE_ENV||"development",platform:Dt.platform,version:Dt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Dt.env.NODE_ENV||Dt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Xr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Nl},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new v$,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??H.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Yr,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Yr};return{...Yr,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Nl.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,l=3,c=1000;while(f<l)try{try{try{await Ue(this.config.logDirectory,n$.F_OK|n$.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await je(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Pi.from(i);try{if(!pn(this.currentLogFile))await cl(this.currentLogFile,"",{mode:420});if(r=t$(this.currentLogFile,"a",420),se(r,$,{flag:"a"}),i$(r),r!==void 0)ll(r),r=void 0;if((await kt(this.currentLogFile)).size===0){if(await cl(this.currentLogFile,$,{flag:"w",mode:420}),(await kt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let h=w;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(f<l-1){let y=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,y);let u=c*2**f;await new Promise((e)=>setTimeout(e,u)),f++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(r!==void 0)try{ll(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch($){if(f===l-1){let h=$,y=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",y),$}f++;let w=c*2**(f-1);await new Promise((h)=>setTimeout(h,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Vt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Vt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Vt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,$])=>$.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(r.length>l)for(let[c]of r.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return fl(16).toString("hex")}generateKey(){return fl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=fl(16),r=me("aes-256-gcm",t,n),f=Pi.isBuffer(i)?i:Pi.from(i,"utf8"),l=r.update(f),c=r.final(),$=l.length+c.length,w=r.getAuthTag(),h=Pi.allocUnsafe(16+$+16);return n.copy(h,0),l.copy(h,16),c.copy(h,16+l.length),w.copy(h,16+$),{encrypted:h,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=f$(),f=[];r.on("data",(l)=>f.push(l)),r.on("end",()=>t(Pi.from(Pi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let i=await kt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await ir(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,h)=>{let y=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${n}.${c}`;if(await kt(n).catch(()=>null))try{if(await r$(n,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await tr($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await cl(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=n.replace(/\.log$/,`-${f}.log`);if(await kt(n).catch(()=>null))await r$(n,l)}if(this.currentLogFile=r,t.maxFiles){let f=(await ir(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await tr(Vt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=p0(i),r=Re(t),f=f$();await Ne(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),pn(this.currentLogFile))try{let i=t$(this.currentLogFile,"r+");i$(i),ll(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await ir(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await tr(Vt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?K.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let i=typeof H.env.NO_COLOR<"u",t=H.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof H.stderr<"u"&&H.stderr.isTTY||typeof H.stdout<"u"&&H.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(n)A.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)A.push(r.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=H.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${n} ${f}`;else if(l==="info"||l==="success")h=`${n} ${r} ${f}`;else h=`${n} ${r} ${K.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,u=$(t).length,e=Math.max(1,w-2-y-u);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(l,c)=>{if(c==="%")return"%";if(r>=t.length)return l;let $=t[r++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(r<t.length)f+=` ${t.slice(r).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let l=K.underline(K.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,w="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(n,r)=>K.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>K.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>K.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>K.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>K.strikethrough(r)),t}supportsHyperlinks(){if(p())return!1;let i=H.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=H.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(Se(t)||t.startsWith("./")||t.startsWith("../"))t=ae(t);else return null;return pn(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),l=this.formatFileTimestamp(r),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,n);let{consoleText:w,fileText:h}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":cw[i],e=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:K.gray(w),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:K.green(w),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.error(A),$){let B=$.split(`
|
|
14
|
-
`);for(let E of B)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:K.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let y=`${l} ${this.environment}.${i.toUpperCase()}: ${h}
|
|
15
|
-
`;if($)y+=`${$}
|
|
16
|
-
`;if(y=y.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(y)}progress(i,t=""){let n={update:(f,l)=>{},finish:(f)=>{},interrupt:(f,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,l="info")=>{if(!p()&&H.stdout.isTTY)H.stdout.write(`
|
|
17
|
-
`);if(this[l==="warning"?"warn":l](f),this.activeProgressBar&&this.shouldStyleConsole()&&!p()&&H.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":K.blue("◐"),tag:n,message:`${K.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),w=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
18
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":K.green("✓"),tag:h,message:`${l}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!p())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Xr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(p())throw Error("createReadStream is not supported in browser environments");if(!pn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return p0(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Pi.isBuffer(i)?i:Pi.from(i,"base64"),f=r.subarray(0,16),l=r.subarray(r.length-16),c=r.subarray(16,r.length-16),$=Ce("aes-256-gcm",n,f);$.setAuthTag(l);let w=$.update(c),h=$.final(),y=w.length+h.length,u=Pi.allocUnsafe(y);return w.copy(u,0),h.copy(u,w.length),u.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return p()}isServerMode(){return!p()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
|
|
19
|
-
`),w=Math.max(...$.map((e)=>e.length))+2,h=`┌${"─".repeat(w)}┐`,y=`└${"─".repeat(w)}┘`,u=$.map((e)=>{return this.formatConsoleMessage({timestamp:n,message:K.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(h),showTimestamp:!1})),u.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:n,message:K.cyan(y),showTimestamp:!1}))}else if(!p())console.error(`${r} ${this.environment}.INFO: [BOX] ${l}`);let c=`${r} ${this.environment}.INFO: [BOX] ${l}
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(p())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${K.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();H.stdin.removeListener("data",n);try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!1)}catch{}H.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof H.stdin.setRawMode==="function")H.stdin.setRawMode(!0)}catch{}H.stdin.resume(),H.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,$=0;if(n=i.replace(c,(w,h)=>{if(h==="%")return"%";if($>=t.length)return w;let y=t[$++];switch(h){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return w}}),$<t.length)n+=` ${t.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?K.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${K.blue("◐")} `;console.error(`${$}${c} ${K.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!H.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,l=K.green("━".repeat(r)),c=K.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${n}%`.padStart(4),h=i.message?` ${i.message}`:"",y=this.options.showIcons===!1?"":t||n===100?K.green("✓"):K.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${K.gray(this.formatTag(this.name))}`:"",e=`\r${y}${u} ${$} ${w}${h}`,A=H.stdout.columns||80,B=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${B}`,H.stdout.write(i.lastRenderedLine),t)H.stdout.write(`
|
|
22
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||p()||!H.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(p()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await ir(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Vt(this.config.logDirectory,r);if(i.before)try{if((await kt(f)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await tr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function Z$(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=n;$++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),$===n||!f(c))break;if(r>0)await new Promise((h)=>setTimeout(h,r))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function o$(i){return i instanceof Ui}function $1(i){return i instanceof Fr}function w1(i){if(o$(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((t)=>i.message.toLowerCase().includes(t.toLowerCase()))}class Mr{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:w=!0}=n,h=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let y=r||this.generateEnvPrefix(i),u={...t};return this.processObject(u,[],y,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Jn.track("applyEnvironmentVariables",h,{configName:i});return h()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,n,r){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((y)=>this.formatEnvKey(y,r.useCamelCase)),w=`${n}_${$.join("_")}`,h=r.useBackwardCompatibility?`${n}_${c.map((y)=>y.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,n,r);else{let y=nr.env[w]||(h?nr.env[h]:void 0);if(y!==void 0){if(r.verbose){let u=nr.env[w]?w:h}try{i[f]=this.parseEnvironmentValue(y,typeof l,w,r.customParsers,r.configName)}catch(u){if(u instanceof Wr)throw u;throw Tt.envVar(w,y,typeof l,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[l,c]of Object.entries(r))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw Tt.envVar(n,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(nr.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,l=r||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${n}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,n,r);else r.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
23
|
-
|
|
24
|
-
`;for(let r of i)n+=`${r.key}
|
|
25
|
-
`,n+=` Type: ${r.type}
|
|
26
|
-
`,n+=` Description: ${r.description}
|
|
27
|
-
`,n+=` Example: ${r.example}
|
|
28
|
-
|
|
29
|
-
`;return n}formatAsMarkdown(i,t){let n=`# Environment Variables for ${t}
|
|
30
|
-
|
|
31
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
32
|
-
`,n+=`|----------|------|-------------|----------|
|
|
33
|
-
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
34
|
-
`;return n}}function h1(i,t){let n=rw("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function p$(i,t,n={}){return iw(i,t,n,new WeakMap)}function iw(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=n;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return tw(i,t,f,r);if(!Fi(t)||!Fi(i))return t;return A1(i,t,n,r)}function tw(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return y1(i,t);case"smart":return u1(i,t,r);default:return t}return t}function y1(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>Sl(f,r)))n.push(r);return n}function u1(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Fi(t[0])&&Fi(i[0]))return e1(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function e1(i,t,n){let r=[...t];for(let f of i){if(!Fi(f)){r.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(r.find((w)=>Fi(w)&&($ in w)&&w[$]===f[$])){c=!0;break}}if(!c)r.push(f)}return r}function A1(i,t,n,r){let f=t;if(Fi(f)&&r.has(f))return r.get(f);let l={...i};if(Fi(f))r.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],w=l[c];if(n.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(Fi($)&&Fi(w))l[c]=iw(w,$,n,r);else if(Array.isArray($)||Array.isArray(w))l[c]=tw(w,$,n.arrayMergeMode||"smart",r);else l[c]=$}return l}function kl(i,t,n="replace"){return p$(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Sl(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Sl(i[n],t[n]))return!1;return!0}if(Fi(i)&&Fi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Sl(i[f],t[f]))return!1}return!0}return!1}function Fi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class Hr{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=n;if(f){let h=Zt.getWithFileCheck("file",i);if(h){if($)console.log(`Configuration loaded from cache: ${i}`);return h}}let w=async()=>{if(!rr(i))return null;try{let h=`?t=${Date.now()}`,y=await import(i+h),u=y.default||y,e="default"in y,A=Object.keys(y).length>0;if(!e&&!A)throw new Xn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Xn(i,Error("Configuration must export a valid object"),"unknown");let B={config:kl(t,u,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)Zt.setWithFileCheck("file",B,i,l);return B}catch(h){throw h instanceof Error?Tt.configLoad(i,h):Tt.configLoad(i,Error(String(h)))}};if(c)return Jn.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let l of r)for(let c of this.extensions)f.push($l(t,`${l}${c}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return Z$(async()=>{return rr(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!rr(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let l of f)for(let c of this.extensions){let $=$l(i,`${l}${c}`);if(await this.checkFileAccess($))r.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=$l(i,c);if(await this.checkFileAccess($))r.push($)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!rr(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class Vl{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:w=!1}=n,h=async()=>{let y=[],u=[],e={stopOnFirstError:r,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return y.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:y,warnings:u}}};if($)return await Jn.track("validateConfiguration",h);return h()}async validateWithSchemaFile(i,t,n){try{if(!Xe(t))throw new Fn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Fn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(r.push({path:n,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,r,f,l),l.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(r.push({path:n?`${n}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,w]of Object.entries(t.properties))if($ in c){let h=n?`${n}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],w,h,r,f,l),l.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!$.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(r.push(...$),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,l,c]=r;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ww},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Dl{fileLoader=new Hr;envProcessor=new Mr;validator=new Vl;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:l,...c}=i;try{if(n?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let $;try{$=await this.loadConfigurationStrategies(c,!0,n)}catch(w){let h=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(h)throw w;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let y=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),u=!y&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),e=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(h&&(e||y))throw w;if(u&&(!h||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(n?.enabled&&$)this.cacheResult(c.name||"",$,n,c);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)Oi.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);$.metrics=w}return $}catch($){let w=Date.now()-t;throw Oi.error(`Configuration loading failed after ${w}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:w=!0,arrayStrategy:h="replace",verbose:y=!1}=i,u=l||Wt.cwd(),e=[],A=await this.loadLocalConfiguration(r,f,u,c,$,h,y,w,n);if(A)return e.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(A,e,w,r,y);let B=await this.loadHomeConfiguration(r,f,$,h,y,w);if(B)return e.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(B,e,w,r,y);let E=await this.loadPackageJsonConfiguration(r,f,u,$,h,y,w);if(E)return e.push(Ti(u,"package.json")),this.finalizeResult(E,e,w,r,y);if(e.push(...this.getAllSearchPaths(r,f,u,c)),t)throw Tt.configNotFound(r,e,f);return{...await this.applyEnvironmentVariables(r,$,w,y),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,l,c,$,w){let h=$?jn(i,f,c):f,y=this.getLocalDirectories(n,r);for(let u of y){if(c)Oi.info(`Searching for configuration in: ${u}`);let e=this.fileLoader.generateConfigPaths(i,u,t),A=await this.fileLoader.tryLoadFromPaths(e,h,{arrayStrategy:l,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(A){if(c)Oi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,n,r,f,l){if(!i)return null;let c=l?jn(i,n,f):n,$=[Ti(Lt(),".config",i),Ti(Lt(),".config"),Lt()];for(let w of $){if(f)Oi.info(`Checking home directory: ${w}`);let h=this.fileLoader.generateConfigPaths(i,w,t),y=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:r,verbose:f});if(y){if(f)Oi.success(`Configuration loaded from home directory: ${y.source.path}`);return y}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,l,c){let $=c?jn(i,r,l):r;try{let w=Ti(n,"package.json");if(!Ul(w))return null;let h=await import(w),y=h[i],u=i;if(!y&&t)y=h[t],u=t;if(y&&typeof y==="object"&&!Array.isArray(y)){if(l)Oi.success(`Configuration loaded from package.json: ${u}`);return{config:kl($,y,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(l)Oi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:jn(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let l=n(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw Tt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return Zt.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);Zt.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ti(i,"config"),Ti(i,".config"),t?Ti(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ti(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ti(Lt(),".config",i),Ti(Lt(),".config"),Lt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function A$(i){let t=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),n=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return t||n}async function E1(i){return nt.loadConfig({...i,__strictErrorHandling:!0})}async function nw(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await nt.loadConfig(i);else r=await nt.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",l=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||l.includes("config"))&&i.verbose)Oi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let c=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await nt.applyEnvironmentVariables(c.name||"",t,!0,c.verbose||!1))?.config??t;return t}}async function T1(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await nt.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&A$(n)))return(await nt.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await nt.loadConfig({...i,cwd:i.cwd||Wt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&A$(t)))return(await nt.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function Y1(i,t,n="replace"){let r=new Hr;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function jn(i,t,n=!1){let r=new Mr,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let w={...c};for(let[h,y]of Object.entries(c)){let u=[...$,h],e=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((E)=>E.toUpperCase()).join("")}`,`${f}_${u.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,B;for(let E of e)if(A=Wt.env[E],A!==void 0){B=E;break}if(A!==void 0&&B)if(typeof y==="boolean")w[h]=["true","1","yes"].includes(A.toLowerCase());else if(typeof y==="number"){let E=Number(A);if(!Number.isNaN(E))w[h]=E}else if(Array.isArray(y))try{w[h]=JSON.parse(A)}catch{w[h]=A.split(",").map((E)=>E.trim())}else w[h]=A;else if(y&&typeof y==="object"&&!Array.isArray(y))w[h]=l(y,u)}return w}return l(t)}function B1(i){let t=Ti(Wt.cwd(),i.configDir),n=Ti(Wt.cwd(),i.generatedDir),r=Ti(n,"config-types.ts");if(!Ul(k0(r)))fe(k0(r),{recursive:!0,mode:511});let f=Ul(t)?le(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],l=`// Generated by bunfig v${D1}
|
|
35
|
-
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
36
|
-
`;ce(r,l,{mode:438})}function m1(i){let t=null,n=null,r=()=>{if(!n)n=nw(i).then((l)=>{return t=l,l},(l)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)Oi.warn("Config loading failed, using defaults:",[l instanceof Error?l:Error(String(l))]);return c});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get(l,c){if(t)return t[c];let $=f[c];return r(),$},has(l,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(l,c){return Object.getOwnPropertyDescriptor(t||f,c)},set(l,c,$){if(!t)t={...f};return t[c]=$,!0}})}function C1(i){let t=l$(Je.cwd(),i?.configDir||"./config");function n(){if(!Fe(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),l=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=We(t).filter((w)=>f.has(wl(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),$=new Map;for(let{base:w,file:h}of c){let y=wl(h).toLowerCase(),u=$.get(w);if(!u){$.set(w,h);continue}let e=wl(u).toLowerCase();if(l.indexOf(y)<l.indexOf(e))$.set(w,h)}return Array.from($.entries()).map(([w,h])=>({base:w,file:h})).sort((w,h)=>w.base.localeCompare(h.base))}function r(){let f=n(),l=f.map((w)=>w.base),c=l.length?l.map((w)=>`'${w}'`).join(" | "):"string",$=f.length?`{
|
|
37
|
-
${f.map((w)=>{let h=l$(t,w.file).replace(/\\/g,"/");return` '${w.base}': typeof import('${h}').default`}).join(`,
|
|
38
|
-
`)}
|
|
39
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
40
|
-
export type ConfigByName = ${$}
|
|
41
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
42
|
-
export type ConfigOf = Config
|
|
43
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(l)=>{return{path:l.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var rw,Zt,Jn,fw,R1,s1,E$,Ar,al,wi,d,U1,T$,j1,Y$,S1,a1,Al,N1,B$,m$,El,X1,F1,W1,J1,Er,lw,_1,hi,I1,K1,C$,Tr,Nl,ii,K,z1,R$,O1,s$,G1,M1,Tl,H1,U$,j$,q1,Yl,L1,g1,x1,d1,k1,Yr,cw,V1,D1="0.15.6",Ui,Fr,Xn,Xl,Fl,Wr,Wl,Jl,Fn,_l,Il,Tt,$w,ww,Oi,nt,hw,yw,b1=be(async()=>{rw=import.meta.require,Zt=new Ll,Jn=new gl,fw={createKey:Qe,isEquivalent:Pe,estimateMemoryUsage:ve},R1=sr(jl.cwd(),"config"),s1=sr(jl.cwd(),"src/generated"),E$=Rr.env.CLARITY_LOG_DIR||he(pe(),"logs"),Ar={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:E$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},al=await i1(),wi={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},d=wi,U1=wi.red,T$=wi.green,j1=wi.yellow,Y$=wi.blue,S1=wi.magenta,a1=wi.cyan,Al=wi.white,N1=wi.gray,B$=wi.bgRed,m$=wi.bgYellow,El=wi.bold,X1=wi.dim,F1=wi.italic,W1=wi.underline,J1=wi.reset,Er={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lw={debug:"\uD83D\uDD0D",info:Y$("ℹ"),success:T$("✓"),warning:m$(Al(El(" WARN "))),error:B$(Al(El(" ERROR ")))},_1=new ar("stacks"),hi=new ar("bunfig",{showTags:!0}),I1=Ei(Nn.cwd(),"config"),K1=Ei(Nn.cwd(),"src/generated"),C$=Cr.env.CLARITY_LOG_DIR||$e(f1(),"logs"),Tr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:C$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Nl=await l1(),ii={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},K=ii,z1=ii.red,R$=ii.green,O1=ii.yellow,s$=ii.blue,G1=ii.magenta,M1=ii.cyan,Tl=ii.white,H1=ii.gray,U$=ii.bgRed,j$=ii.bgYellow,q1=ii.bgGray,Yl=ii.bold,L1=ii.dim,g1=ii.italic,x1=ii.underline,d1=ii.strikethrough,k1=ii.reset,Yr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},cw={debug:"\uD83D\uDD0D",info:s$("ℹ"),success:R$("✓"),warning:j$(Tl(Yl(" WARN "))),error:U$(Tl(Yl(" ERROR ")))},V1=new Xr("stacks"),Ui=class extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},Fr=class extends Ui{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n?` or alias "${n}"`:"";super(`Configuration "${i}"${r} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}},Xn=class extends Ui{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}},Xl=class extends Ui{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}},Fl=class extends Ui{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Wr=class extends Ui{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}},Wl=class extends Ui{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Jl=class extends Ui{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Fn=class extends Ui{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}},_l=class extends Ui{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}},Il=class extends Ui{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}},Tt={configNotFound(i,t,n){return new Fr(i,t,n)},configLoad(i,t,n){return new Xn(i,t,n)},configValidation(i,t,n){return new Xl(i,t,n)},configMerge(i,t,n,r){return new Fl(i,t,n,r)},envVar(i,t,n,r){return new Wr(i,t,n,r)},fileSystem(i,t,n){return new Wl(i,t,n)},typeGeneration(i,t,n){return new Jl(i,t,n)},schemaValidation(i,t,n){return new Fn(i,t,n)},browserConfig(i,t,n,r){return new _l(i,t,n,r)},plugin(i,t,n){return new Il(i,t,n)}},$w={replace:"replace",concat:"concat",smart:"smart"},ww=/^https?:\/\//,Oi=new Xr("bunfig",{showTags:!0}),nt=new Dl,hw=Ti(Wt.cwd(),"config"),yw=Ti(Wt.cwd(),"src/generated")});function Q1(i,t={}){let n=Ur.cwd();while(n.includes("storage"))n=c$(n,"..");let r=c$(n,i||"");if(t?.relative)return Ie(Ur.cwd(),r);return r}var P1=Ur.env.CLARITY_LOG_DIR||_e(Q1(),"logs"),uw={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:P1,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Jr={...uw},qC=(async()=>{try{let{loadConfig:i}=await b1().then(()=>Q$),t=await i({name:"clarity",alias:"logging",defaultConfig:uw,cwd:Ur.cwd()});if(t)Object.assign(Jr,t)}catch{}return Jr})();function ti(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function v1(){if(it.env.NODE_ENV==="test"||it.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof it<"u"){let i=it.type;if(i==="renderer"||i==="worker")return!1;return!!(it.versions&&(it.versions.node||it.versions.bun))}return!1}class ew{async format(i){let t=await v1(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:Pt.pid,hostname:t(),environment:Pt.env.NODE_ENV||"development",platform:Pt.platform,version:Pt.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Pt.env.NODE_ENV||Pt.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var li={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},O=li,LC=li.red,Z1=li.green,gC=li.yellow,o1=li.blue,xC=li.magenta,dC=li.cyan,S$=li.white,kC=li.gray,p1=li.bgRed,iA=li.bgYellow,VC=li.bgGray,a$=li.bold,DC=li.dim,bC=li.italic,QC=li.underline,PC=li.strikethrough,vC=li.reset,Bl={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tA={debug:"\uD83D\uDD0D",info:o1("ℹ"),success:Z1("✓"),warning:iA(S$(a$(" WARN "))),error:p1(S$(a$(" ERROR ")))};class qr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Jr},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new ew,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...Bl,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...Bl};return{...Bl,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Jr.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ti()&&this.config.writeToFile===!0}async writeToFile(i){let t=(async()=>{let r,f=0,l=3,c=1000;while(f<l)try{try{try{await Me(this.config.logDirectory,y$.F_OK|y$.W_OK)}catch(w){if(w instanceof Error&&"code"in w)if(w.code==="ENOENT")await He(this.config.logDirectory,{recursive:!0,mode:493});else if(w.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw w;else throw w}}catch(w){throw console.error("Debug: [writeToFile] Failed to create log directory:",w),w}let $=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:vi.from(i);try{if(!fr(this.currentLogFile))await ul(this.currentLogFile,"",{mode:420});if(r=h$(this.currentLogFile,"a",420),Ge(r,$,{flag:"a"}),w$(r),r!==void 0)yl(r),r=void 0;if((await bt(this.currentLogFile)).size===0){if(await ul(this.currentLogFile,$,{flag:"w",mode:420}),(await bt(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(w){let h=w;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(f<l-1){let y=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${l}:`,y);let u=c*2**f;await new Promise((e)=>setTimeout(e,u)),f++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(r!==void 0)try{yl(r)}catch(w){console.error("Debug: [writeToFile] Error closing file descriptor:",w)}}}catch($){if(f===l-1){let h=$,y=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",y),$}f++;let w=c*2**(f-1);await new Promise((h)=>setTimeout(h,w))}})();this.pendingOperations.push(t);let n=this.pendingOperations.length-1;try{await t}catch(r){throw console.error("Debug: [writeToFile] Error in operation:",r),r}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Qt(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Qt(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return Qt(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ti())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let t=typeof i.interval==="number"?i.interval:60,n=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((r)=>{console.error("Error rotating keys:",r)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,t=this.generateKeyId(),n=this.generateKey();this.currentKeyId=t,this.keys.set(t,n),this.encryptionKeys.set(t,{key:n,createdAt:new Date});let r=Array.from(this.encryptionKeys.entries()).sort(([,c],[,$])=>$.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,l=Math.max(1,f);if(r.length>l)for(let[c]of r.slice(l))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return hl(16).toString("hex")}generateKey(){return hl(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=hl(16),r=Ke("aes-256-gcm",t,n),f=vi.isBuffer(i)?i:vi.from(i,"utf8"),l=r.update(f),c=r.final(),$=l.length+c.length,w=r.getAuthTag(),h=vi.allocUnsafe(16+$+16);return n.copy(h,0),l.copy(h,16),c.copy(h,16+l.length),w.copy(h,16+$),{encrypted:h,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=e$(),f=[];r.on("data",(l)=>f.push(l)),r.on("end",()=>t(vi.from(vi.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ti())return;if(!this.shouldWriteToFile())return;let i=await bt(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await lr(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,h)=>{let y=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${n}.${c}`;if(await bt(n).catch(()=>null))try{if(await u$(n,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await cr($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await ul(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=n.replace(/\.log$/,`-${f}.log`);if(await bt(n).catch(()=>null))await u$(n,l)}if(this.currentLogFile=r,t.maxFiles){let f=(await lr(this.config.logDirectory)).filter((l)=>l.startsWith(this.name)).sort((l,c)=>c.localeCompare(l));for(let l of f.slice(t.maxFiles))await cr(Qt(this.config.logDirectory,l))}}}async compressLogFile(i,t){let n=$$(i),r=Oe(t),f=e$();await ge(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),fr(this.currentLogFile))try{let i=h$(this.currentLogFile,"r+");w$(i),yl(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ti()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await lr(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of i)try{await cr(Qt(this.config.logDirectory,t))}catch(n){console.error(`Failed to delete temp file ${t}:`,n)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?O.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ti())return!1;let i=typeof q.env.NO_COLOR<"u",t=q.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof q.stderr<"u"&&q.stderr.isTTY||typeof q.stdout<"u"&&q.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(n)A.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)A.push(r.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=q.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${n} ${f}`;else if(l==="info"||l==="success")h=`${n} ${r} ${f}`;else h=`${n} ${r} ${O.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,u=$(t).length,e=Math.max(1,w-2-y-u);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(l,c)=>{if(c==="%")return"%";if(r>=t.length)return l;let $=t[r++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(r<t.length)f+=` ${t.slice(r).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let l=O.underline(O.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,w="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(n,r)=>O.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>O.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>O.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>O.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>O.strikethrough(r)),t}supportsHyperlinks(){if(ti())return!1;let i=q.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=q.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(qe(t)||t.startsWith("./")||t.startsWith("../"))t=Le(t);else return null;return fr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),l=this.formatFileTimestamp(r),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,n);let{consoleText:w,fileText:h}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":tA[i],e=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:O.gray(w),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:O.green(w),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.error(A),$){let B=$.split(`
|
|
44
|
-
`);for(let E of B)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:O.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ti()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}let y=`${l} ${this.environment}.${i.toUpperCase()}: ${h}
|
|
45
|
-
`;if($)y+=`${$}
|
|
46
|
-
`;if(y=y.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(y)}progress(i,t=""){let n={update:(f,l)=>{},finish:(f)=>{},interrupt:(f,l)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(f,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,f),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(f)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,f)},interrupt:(f,l="info")=>{if(!ti()&&q.stdout.isTTY)q.stdout.write(`
|
|
47
|
-
`);if(this[l==="warning"?"warn":l](f),this.activeProgressBar&&this.shouldStyleConsole()&&!ti()&&q.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":O.blue("◐"),tag:n,message:`${O.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),w=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(n)w+=` ${JSON.stringify(n)}`;if(w+=`
|
|
48
|
-
`,w=w.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":O.green("✓"),tag:h,message:`${l}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ti())console.error(w.trim());if(this.shouldWriteToFile())await this.writeToFile(w)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new qr(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ti())throw Error("createReadStream is not supported in browser environments");if(!fr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $$(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=vi.isBuffer(i)?i:vi.from(i,"base64"),f=r.subarray(0,16),l=r.subarray(r.length-16),c=r.subarray(16,r.length-16),$=ze("aes-256-gcm",n,f);$.setAuthTag(l);let w=$.update(c),h=$.final(),y=w.length+h.length,u=vi.allocUnsafe(y);return w.copy(u,0),h.copy(u,w.length),u.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ti()}isServerMode(){return!ti()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
|
|
49
|
-
`),w=Math.max(...$.map((e)=>e.length))+2,h=`┌${"─".repeat(w)}┐`,y=`└${"─".repeat(w)}┘`,u=$.map((e)=>{return this.formatConsoleMessage({timestamp:n,message:O.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:O.cyan(h),showTimestamp:!1})),u.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:n,message:O.cyan(y),showTimestamp:!1}))}else if(!ti())console.error(`${r} ${this.environment}.INFO: [BOX] ${l}`);let c=`${r} ${this.environment}.INFO: [BOX] ${l}
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ti())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${O.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();q.stdin.removeListener("data",n);try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!1)}catch{}q.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof q.stdin.setRawMode==="function")q.stdin.setRawMode(!0)}catch{}q.stdin.resume(),q.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,$=0;if(n=i.replace(c,(w,h)=>{if(h==="%")return"%";if($>=t.length)return w;let y=t[$++];switch(h){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return w}}),$<t.length)n+=` ${t.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let c=this.options.showTags!==!1&&this.name?O.gray(this.formatTag(this.name)):"",$=this.options.showIcons===!1?"":`${O.blue("◐")} `;console.error(`${$}${c} ${O.cyan(r)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(l)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!q.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,l=O.green("━".repeat(r)),c=O.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${n}%`.padStart(4),h=i.message?` ${i.message}`:"",y=this.options.showIcons===!1?"":t||n===100?O.green("✓"):O.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${O.gray(this.formatTag(this.name))}`:"",e=`\r${y}${u} ${$} ${w}${h}`,A=q.stdout.columns||80,B=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${B}`,q.stdout.write(i.lastRenderedLine),t)q.stdout.write(`
|
|
52
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ti()||!q.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ti()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await lr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let f=Qt(this.config.logDirectory,r);if(i.before)try{if((await bt(f)).mtime>=i.before)continue}catch(l){console.error(`Failed to get stats for file ${f}:`,l);continue}n.push(f)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await cr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var ZC=new qr("stacks");class Hi extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class Aw extends Hi{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((l)=>`"${l}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class _r extends Hi{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class Ew extends Hi{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class Tw extends Hi{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class bl extends Hi{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class Yw extends Hi{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Bw extends Hi{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Ir extends Hi{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class mw extends Hi{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class Cw extends Hi{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var ot={configNotFound(i,t,n){return new Aw(i,t,n)},configLoad(i,t,n){return new _r(i,t,n)},configValidation(i,t,n){return new Ew(i,t,n)},configMerge(i,t,n,r){return new Tw(i,t,n,r)},envVar(i,t,n,r){return new bl(i,t,n,r)},fileSystem(i,t,n){return new Yw(i,t,n)},typeGeneration(i,t,n){return new Bw(i,t,n)},schemaValidation(i,t,n){return new Ir(i,t,n)},browserConfig(i,t,n,r){return new mw(i,t,n,r)},plugin(i,t,n){return new Cw(i,t,n)}};async function nA(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=n;$++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),$===n||!f(c))break;if(r>0)await new Promise((h)=>setTimeout(h,r))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class Ql{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:w=!0}=n,h=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let y=r||this.generateEnvPrefix(i),u={...t};return this.processObject(u,[],y,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return ql.track("applyEnvironmentVariables",h,{configName:i});return h()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,n,r){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((y)=>this.formatEnvKey(y,r.useCamelCase)),w=`${n}_${$.join("_")}`,h=r.useBackwardCompatibility?`${n}_${c.map((y)=>y.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,n,r);else{let y=$r.env[w]||(h?$r.env[h]:void 0);if(y!==void 0){if(r.verbose){let u=$r.env[w]?w:h}try{i[f]=this.parseEnvironmentValue(y,typeof l,w,r.customParsers,r.configName)}catch(u){if(u instanceof bl)throw u;throw ot.envVar(w,y,typeof l,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[l,c]of Object.entries(r))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw ot.envVar(n,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries($r.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,l=r||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${n}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,n,r);else r.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
53
|
-
|
|
54
|
-
`;for(let r of i)n+=`${r.key}
|
|
55
|
-
`,n+=` Type: ${r.type}
|
|
56
|
-
`,n+=` Description: ${r.description}
|
|
57
|
-
`,n+=` Example: ${r.example}
|
|
58
|
-
|
|
59
|
-
`;return n}formatAsMarkdown(i,t){let n=`# Environment Variables for ${t}
|
|
60
|
-
|
|
61
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
62
|
-
`,n+=`|----------|------|-------------|----------|
|
|
63
|
-
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
64
|
-
`;return n}}function rA(i,t,n={}){return Rw(i,t,n,new WeakMap)}function Rw(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=n;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return sw(i,t,f,r);if(!Wi(t)||!Wi(i))return t;return $A(i,t,n,r)}function sw(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return fA(i,t);case"smart":return lA(i,t,r);default:return t}return t}function fA(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>Kl(f,r)))n.push(r);return n}function lA(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Wi(t[0])&&Wi(i[0]))return cA(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function cA(i,t,n){let r=[...t];for(let f of i){if(!Wi(f)){r.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(r.find((w)=>Wi(w)&&($ in w)&&w[$]===f[$])){c=!0;break}}if(!c)r.push(f)}return r}function $A(i,t,n,r){let f=t;if(Wi(f)&&r.has(f))return r.get(f);let l={...i};if(Wi(f))r.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],w=l[c];if(n.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(Wi($)&&Wi(w))l[c]=Rw(w,$,n,r);else if(Array.isArray($)||Array.isArray(w))l[c]=sw(w,$,n.arrayMergeMode||"smart",r);else l[c]=$}return l}function Uw(i,t,n="replace"){return rA(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function Kl(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Kl(i[n],t[n]))return!1;return!0}if(Wi(i)&&Wi(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Kl(i[f],t[f]))return!1}return!0}return!1}function Wi(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class jw{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=n;if(f){let h=jr.getWithFileCheck("file",i);if(h){if($)console.log(`Configuration loaded from cache: ${i}`);return h}}let w=async()=>{if(!wr(i))return null;try{let h=`?t=${Date.now()}`,y=await import(i+h),u=y.default||y,e="default"in y,A=Object.keys(y).length>0;if(!e&&!A)throw new _r(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new _r(i,Error("Configuration must export a valid object"),"unknown");let B={config:Uw(t,u,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)jr.setWithFileCheck("file",B,i,l);return B}catch(h){throw h instanceof Error?ot.configLoad(i,h):ot.configLoad(i,Error(String(h)))}};if(c)return ql.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let l of r)for(let c of this.extensions)f.push(el(t,`${l}${c}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let l of r){if(!l)continue;if(n.push(l,`.${l}.config`,`${l}.config`,`.${l}`),i)n.push(`${i}.${l}.config`,`.${i}.${l}.config`)}let f=new Set;return n.filter((l)=>{if(!l||f.has(l))return!1;return f.add(l),!0})}checkFileAccess(i){return nA(async()=>{return wr(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!wr(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let l of f)for(let c of this.extensions){let $=el(i,`${l}${c}`);if(await this.checkFileAccess($))r.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=el(i,c);if(await this.checkFileAccess($))r.push($)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((t)=>t.test(i))}async validateConfigFile(i){let t=[];try{if(!wr(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var wA=/^https?:\/\//;class Sw{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:w=!1}=n,h=async()=>{let y=[],u=[],e={stopOnFirstError:r,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return y.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:y,warnings:u}}};if($)return await ql.track("validateConfiguration",h);return h()}async validateWithSchemaFile(i,t,n){try{if(!xe(t))throw new Ir(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Ir(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(r.push({path:n,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,r,f,l),l.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(r.push({path:n?`${n}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,w]of Object.entries(t.properties))if($ in c){let h=n?`${n}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],w,h,r,f,l),l.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!$.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(r.push(...$),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,l,c]=r;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:wA},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Zi=new qr("bunfig",{showTags:!0});function hA(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class aw{fileLoader=new jw;envProcessor=new Ql;validator=new Sw;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:l,...c}=i;try{if(n?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let $;try{$=await this.loadConfigurationStrategies(c,!0,n)}catch(w){let h=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(h)throw w;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let y=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),u=!y&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),e=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(h&&(e||y))throw w;if(u&&(!h||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(n?.enabled&&$)this.cacheResult(c.name||"",$,n,c);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)Zi.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);$.metrics=w}return $}catch($){if($ instanceof Error&&$.name==="ConfigNotFoundError")throw $;let w=Date.now()-t;throw Zi.error(`Configuration loading failed after ${w}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:w=!0,arrayStrategy:h="replace",verbose:y=!1}=i,u=l||Gr.cwd(),e=[],A=await this.loadLocalConfiguration(r,f,u,c,$,h,y,w,n);if(A)return e.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(A,e,w,r,y);let B=await this.loadHomeConfiguration(r,f,$,h,y,w);if(B)return e.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(B,e,w,r,y);let E=await this.loadPackageJsonConfiguration(r,f,u,$,h,y,w);if(E)return e.push(Xi(u,"package.json")),this.finalizeResult(E,e,w,r,y);if(e.push(...this.getAllSearchPaths(r,f,u,c)),t)throw ot.configNotFound(r,e,f);return{...await this.applyEnvironmentVariables(r,$,w,y),warnings:[`No configuration file found for "${r}"${hA(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,l,c,$,w){let h=$?yr(i,f,c):f,y=this.getLocalDirectories(n,r);for(let u of y){if(c)Zi.info(`Searching for configuration in: ${u}`);let e=this.fileLoader.generateConfigPaths(i,u,t),A=await this.fileLoader.tryLoadFromPaths(e,h,{arrayStrategy:l,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(A){if(c)Zi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,n,r,f,l){if(!i)return null;let c=l?yr(i,n,f):n,$=[Xi(qt(),".config",i),Xi(qt(),".config"),qt()];for(let w of $){if(f)Zi.info(`Checking home directory: ${w}`);let h=this.fileLoader.generateConfigPaths(i,w,t),y=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:r,verbose:f});if(y){if(f)Zi.success(`Configuration loaded from home directory: ${y.source.path}`);return y}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,l,c){let $=c?yr(i,r,l):r;try{let w=Xi(n,"package.json");if(!ne(w))return null;let h={};try{h=JSON.parse(re(w,"utf8"))}catch(e){if(l)Zi.warn("Failed to parse package.json:",[e instanceof Error?e:Error(String(e))]);return null}let y=h[i],u=i;if(!y&&t){let e=Array.isArray(t)?t:[t];for(let A of e){if(!A)continue;if(h[A]){y=h[A],u=A;break}}}if(y&&typeof y==="object"&&!Array.isArray(y)){if(l)Zi.success(`Configuration loaded from package.json: ${u}`);return{config:Uw($,y,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(l)Zi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:yr(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let l=n(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw ot.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return jr.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);jr.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Xi(i,"config"),Xi(i,".config"),t?Xi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Xi(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let n=[Xi(qt(),".config",i),Xi(qt(),".config"),qt()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var oC=new aw;function yr(i,t,n=!1){let r=new Ql,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let w={...c};for(let[h,y]of Object.entries(c)){let u=[...$,h],e=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((E)=>E.toUpperCase()).join("")}`,`${f}_${u.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,B;for(let E of e)if(A=Gr.env[E],A!==void 0){B=E;break}if(A!==void 0&&B)if(typeof y==="boolean")w[h]=["true","1","yes"].includes(A.toLowerCase());else if(typeof y==="number"){let E=Number(A);if(!Number.isNaN(E))w[h]=E}else if(Array.isArray(y))try{w[h]=JSON.parse(A)}catch{w[h]=A.split(",").map((E)=>E.trim())}else w[h]=A;else if(y&&typeof y==="object"&&!Array.isArray(y))w[h]=l(y,u)}return w}return l(t)}var pC=Xi(Gr.cwd(),"config"),iR=Xi(Gr.cwd(),"src/generated"),Nw={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:of.join(Zf.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:of.join(Zf.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:of.join(Zf.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},Z=Nw,Gi={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"};var S={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},vt={info:(...i)=>console.log(...i),warn:(...i)=>console.warn(...i),success:(...i)=>console.log(...i),error:(...i)=>console.error(...i),debug:(...i)=>console.debug(...i)};function Fw(i){return zl.readFileSync(i,"utf8")}function Ol(i,t){let n=[];function r(f){let l;try{l=zl.readdirSync(f)}catch{return}for(let c of l){let $=zi.join(f,c);try{if(zl.statSync($).isDirectory())r($);else if(c===t)n.push(f)}catch{continue}}}return r(i),n}function U(i,t,n){if(n||Z.verbose)console.debug(`[tlsx:${i}] ${t}`)}var AA=eA(yA);function Ww(){return Xw.env.SUDO_PASSWORD}var N$="[redacted]",EA=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),TA=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function YA(i){let t=i.toLowerCase();return EA.has(t)||t.endsWith("password")||t.includes("secret")||t.includes("token")}function Kr(i){if(Array.isArray(i))return i.map((n)=>Kr(n));if(typeof i==="string")return TA.test(i)?N$:i;if(!i||typeof i!=="object")return i;let t={};for(let[n,r]of Object.entries(i)){if(YA(n)){t[n]=N$;continue}t[n]=Kr(r)}return t}function Lr(i){return JSON.stringify(Kr(i))}function BA(i){let t=Ww();if(!t||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(i))return i;let n=t.replace(/'/g,"'\\''"),r=i.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${n}' | ${r}`}async function Et(i,t={}){let n=BA(i);try{let{stdout:r,stderr:f}=await AA(n,{cwd:t.cwd||Xw.cwd(),timeout:t.timeout||30000});return{stdout:r.trim(),stderr:f.trim()}}catch(r){let f=Error(`Failed to execute command: ${i}
|
|
65
|
-
Error: ${r.message}`);throw f.stack=r.stack,f}}function Jw(i){if(i.domain)return i.domain;if(i.domains?.length)return i.domains[0];throw Error("Either domain or domains must be specified")}function Pl(i){let t=zi.join(uA.homedir(),".stacks","ssl"),n=i.basePath&&i.basePath.trim()!==""?i.basePath:Z.basePath&&Z.basePath.trim()!==""?Z.basePath:t,r=i.certPath?zi.isAbsolute(i.certPath)?i.certPath:zi.join(n,i.certPath):zi.join(n,Z.certPath),f=i.keyPath?zi.isAbsolute(i.keyPath)?i.keyPath:zi.join(n,i.keyPath):zi.join(n,Z.keyPath),l=i.caCertPath?zi.isAbsolute(i.caCertPath)?i.caCertPath:zi.join(n,i.caCertPath):zi.join(n,Z.caCertPath);return{certPath:r,keyPath:f,caCertPath:l,basePath:n}}function _w(i){let t=[],n=new Set;if(i.domain)n.add(i.domain);if(i.domains?.length)i.domains.forEach((r)=>n.add(r));for(let r of n)t.push({type:2,value:r});if(i.altNameIPs?.length)for(let r of i.altNameIPs)t.push({type:7,ip:r});if(i.altNameURIs?.length)for(let r of i.altNameURIs)t.push({type:6,value:r});if(i.subjectAltNames?.length)t.push(...i.subjectAltNames);return U(S.CERT,`Generated ${t.length} Subject Alternative Names`,i.verbose),t}function vl(i){let t=i.notBeforeDays??Gi.DEFAULT_NOT_BEFORE_DAYS,n=i.validityDays??(i.validityYears?i.validityYears*365:Gi.DEFAULT_VALIDITY_DAYS);U(S.CERT,"Calculating certificate validity dates",i.verbose);let r=new Date(Date.now()-86400*t*1000),f=new Date(r.getTime()+n*24*60*60*1000);return r.setUTCHours(0,0,0,0),f.setUTCHours(23,59,59,999),U(S.CERT,`Validity period: ${r.toISOString()} to ${f.toISOString()}`,i.verbose),{notBefore:r,notAfter:f}}var Mi={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},Yi={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};function Sn(i){if(i<128)return Buffer.from([i]);let t=[],n=i;while(n>0)t.unshift(n&255),n>>=8;return Buffer.from([128|t.length,...t])}function Si(i,t){let n=Sn(t.length);return Buffer.concat([Buffer.from([i]),n,t])}function Wn(i){let t=i.split(".").map(Number),n=[];n.push(40*t[0]+t[1]);for(let r=2;r<t.length;r++){let f=t[r],l=[];l.unshift(f&127),f>>=7;while(f>0)l.unshift(f&127|128),f>>=7;n.push(...l)}return Si(Mi.OID,Buffer.from(n))}function Gl(i){let t;if(typeof i==="bigint"){let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else if(typeof i==="number")if(i===0)t=Buffer.from([0]);else{let n=i.toString(16).padStart(2,"0");t=Buffer.from(n.length%2?`0${n}`:n,"hex")}else t=i;if(t[0]&128)t=Buffer.concat([Buffer.from([0]),t]);return Si(Mi.INTEGER,t)}function Iw(i,t=0){return Si(Mi.BIT_STRING,Buffer.concat([Buffer.from([t]),i]))}function Kw(i){return Si(Mi.OCTET_STRING,i)}function ji(...i){return Si(Mi.SEQUENCE,Buffer.concat(i))}function mA(...i){return Si(Mi.SET,Buffer.concat(i))}function CA(i){return Si(Mi.PRINTABLE_STRING,Buffer.from(i,"ascii"))}function RA(i){return Si(Mi.UTF8_STRING,Buffer.from(i,"utf8"))}function sA(){return Buffer.from([Mi.NULL,0])}function X$(i,t,n=!0){let r=160|i|(n?0:0),f=Sn(t.length);return Buffer.concat([Buffer.from([r]),f,t])}function F$(i){let t=i.getUTCFullYear();if(t>=2050){let n=i.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Si(Mi.GENERALIZED_TIME,Buffer.from(n,"ascii"))}else{let n=(t%100).toString().padStart(2,"0"),r=(i.getUTCMonth()+1).toString().padStart(2,"0"),f=i.getUTCDate().toString().padStart(2,"0"),l=i.getUTCHours().toString().padStart(2,"0"),c=i.getUTCMinutes().toString().padStart(2,"0"),$=i.getUTCSeconds().toString().padStart(2,"0"),w=`${n}${r}${f}${l}${c}${$}Z`;return Si(Mi.UTC_TIME,Buffer.from(w,"ascii"))}}function UA(i,t){return ji(F$(i),F$(t))}function W$(i){let t=[];for(let n of i){let r;switch(n.shortName){case"CN":r=Yi.COMMON_NAME;break;case"C":r=Yi.COUNTRY;break;case"L":r=Yi.LOCALITY;break;case"ST":r=Yi.STATE;break;case"O":r=Yi.ORGANIZATION;break;case"OU":r=Yi.ORGANIZATIONAL_UNIT;break;default:continue}let f=n.shortName==="C"?CA(n.value):RA(n.value),l=ji(Wn(r),f);t.push(mA(l))}return ji(...t)}function zw(i){return ji(Wn(i),sA())}function jA(i){return i.export({type:"spki",format:"der"})}function SA(i){if(i.includes(":")){let t=i;if(i.includes("::")){let f=i.split("::"),l=f[0]?f[0].split(":"):[],c=f[1]?f[1].split(":"):[],$=8-l.length-c.length,w=Array.from({length:$},()=>"0");t=[...l,...w,...c].join(":")}let n=t.split(":"),r=Buffer.alloc(16);for(let f=0;f<8;f++){let l=Number.parseInt(n[f]||"0",16);r.writeUInt16BE(l,f*2)}return r}else{let t=i.split(".").map((n)=>Number.parseInt(n,10));return Buffer.from(t)}}function aA(i){let t=[];for(let n of i)if(n.type===2&&n.value){let r=Sn(n.value.length);t.push(Buffer.concat([Buffer.from([130]),r,Buffer.from(n.value,"ascii")]))}else if(n.type===7&&n.ip){let r=SA(n.ip),f=Sn(r.length);t.push(Buffer.concat([Buffer.from([135]),f,r]))}else if(n.type===6&&n.value){let r=Sn(n.value.length);t.push(Buffer.concat([Buffer.from([134]),r,Buffer.from(n.value,"ascii")]))}return ji(...t)}function NA(i,t){if(i){if(t!==void 0)return ji(Si(1,Buffer.from([255])),Gl(t));return ji(Si(1,Buffer.from([255])))}return ji()}function XA(i){let t=0;if(i.digitalSignature)t|=128;if(i.keyEncipherment)t|=32;if(i.keyCertSign)t|=4;if(i.cRLSign)t|=2;let n=0,r=t;while(r>0&&(r&1)===0)n++,r>>=1;if(t===0)n=7;return Iw(Buffer.from([t]),n)}function FA(i){let t=[];if(i.serverAuth)t.push(Wn(Yi.SERVER_AUTH));if(i.clientAuth)t.push(Wn(Yi.CLIENT_AUTH));return ji(...t)}function Un(i,t,n){let r=[Wn(i)];if(t)r.push(Si(1,Buffer.from([255])));return r.push(Kw(n)),ji(...r)}function WA(i){let t=[];if(t.push(X$(0,Gl(2))),t.push(Gl(i.serialNumber)),t.push(zw(Yi.SHA256_WITH_RSA)),t.push(W$(i.issuer)),t.push(UA(i.notBefore,i.notAfter)),t.push(W$(i.subject)),t.push(jA(i.publicKey)),i.extensions){let n=[];if(i.extensions.basicConstraints)n.push(Un(Yi.BASIC_CONSTRAINTS,i.extensions.basicConstraints.critical??!0,NA(i.extensions.basicConstraints.isCA,i.extensions.basicConstraints.pathLenConstraint)));if(i.extensions.keyUsage)n.push(Un(Yi.KEY_USAGE,i.extensions.keyUsage.critical??!0,XA(i.extensions.keyUsage)));if(i.extensions.extendedKeyUsage)n.push(Un(Yi.EXTENDED_KEY_USAGE,!1,FA(i.extensions.extendedKeyUsage)));if(i.extensions.subjectAltName?.length)n.push(Un(Yi.SUBJECT_ALT_NAME,!1,aA(i.extensions.subjectAltName)));if(i.extensions.subjectKeyIdentifier)n.push(Un(Yi.SUBJECT_KEY_IDENTIFIER,!1,Kw(i.extensions.subjectKeyIdentifier)));if(n.length>0)t.push(X$(3,ji(...n)))}return ji(...t)}function JA(i,t){let n=pt.createSign("SHA256");n.update(i);let r=n.sign(t);return ji(i,zw(Yi.SHA256_WITH_RSA),Iw(r))}function _A(i,t){let n=i.toString("base64"),r=[];for(let f=0;f<n.length;f+=64)r.push(n.slice(f,f+64));return`-----BEGIN ${t}-----
|
|
66
|
-
${r.join(`
|
|
67
|
-
`)}
|
|
68
|
-
-----END ${t}-----
|
|
69
|
-
`}function Zl(){let i=pt.randomBytes(20);return i[0]=i[0]&127||1,i}function Ow(i=2048){let{privateKey:t,publicKey:n}=pt.generateKeyPairSync("rsa",{modulusLength:i});return{privateKey:t,publicKey:n}}function IA(i){let t=i.export({type:"spki",format:"der"});return pt.createHash("sha1").update(t).digest()}function Gw(i){let t={serialNumber:i.serialNumber||Zl(),notBefore:i.notBefore,notAfter:i.notAfter,subject:i.subject,issuer:i.issuer||i.subject,publicKey:i.publicKey,extensions:{basicConstraints:{isCA:i.isCA??!1,critical:!0,pathLenConstraint:i.pathLenConstraint},subjectKeyIdentifier:IA(i.publicKey)}};if(i.keyUsage)t.extensions.keyUsage={...i.keyUsage,critical:!0};if(i.extendedKeyUsage)t.extensions.extendedKeyUsage=i.extendedKeyUsage;if(i.subjectAltName?.length)t.extensions.subjectAltName=i.subjectAltName;let n=WA(t),r=JA(n,i.signingKey);return{certificate:_A(r,"CERTIFICATE"),certificateDer:r}}function Mw(i){return i.export({type:"pkcs8",format:"pem"})}function KA(i){return pt.createPrivateKey(i)}function zA(i){let t=new pt.X509Certificate(i),n=t.publicKey,r=[],f=t.subject.split(`
|
|
70
|
-
`);for(let l of f){let[c,...$]=l.split("="),w=$.join("=");if(c&&w)r.push({shortName:c.trim(),value:w.trim()})}return{publicKey:n,subject:r}}async function ol(i={}){U("ca","Creating new Root CA Certificate",i.verbose);let t=i.keySize||Gi.DEFAULT_KEY_SIZE;U("ca",`Generating ${t}-bit RSA key pair`,i.verbose);let{privateKey:n,publicKey:r}=Ow(t),f=[{shortName:"C",value:i.countryName||Z.countryName},{shortName:"ST",value:i.stateName||Z.stateName},{shortName:"L",value:i.localityName||Z.localityName},{shortName:"O",value:i.organization||"Local Development CA"},{shortName:"OU",value:i.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:i.commonName||"Local Development Root CA"}],{notBefore:l,notAfter:c}=vl({validityYears:i.validityYears||Gi.DEFAULT_CA_VALIDITY_YEARS,verbose:i.verbose}),{certificate:$}=Gw({serialNumber:Zl(),notBefore:l,notAfter:c,subject:f,publicKey:r,signingKey:n,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:$,privateKey:Mw(n),notBefore:l,notAfter:c}}async function pl(i){if(U("ca","Generating new certificate",i.verbose),U("ca",`Options: ${Lr(i)}`,i.verbose),!i.domain&&!i.domains?.length)throw Error("Either domain or domains must be specified");if(!i.rootCA?.certificate||!i.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:t}=zA(i.rootCA.certificate),n=KA(i.rootCA.privateKey);U("ca",`Generating ${Gi.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,i.verbose);let r=Gi.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:l}=Ow(r),c=i.commonName||Jw(i),$=i.certificateAttributes||[{shortName:"C",value:i.countryName||Z.countryName},{shortName:"ST",value:i.stateName||Z.stateName},{shortName:"L",value:i.localityName||Z.localityName},{shortName:"O",value:i.organizationName||Z.organizationName},{shortName:"CN",value:c}],{notBefore:w,notAfter:h}=vl({validityDays:i.validityDays||Gi.DEFAULT_VALIDITY_DAYS,verbose:i.verbose}),y=_w(i),u=i.keyUsage||{digitalSignature:!0,keyEncipherment:!0},e=i.extKeyUsage||{serverAuth:!0},{certificate:A}=Gw({serialNumber:Zl(),notBefore:w,notAfter:h,subject:$,issuer:t,publicKey:l,signingKey:n,isCA:i.basicConstraints?.cA??!1,pathLenConstraint:i.basicConstraints?.pathLenConstraint,keyUsage:u,extendedKeyUsage:e,subjectAltName:y});return{certificate:A,privateKey:Mw(f),notBefore:w,notAfter:h}}function Hw(i,t){U(S.STORAGE,`Storing certificate and private key with options: ${Lr(t)}`,t?.verbose);let{certPath:n,keyPath:r}=Pl({basePath:t?.basePath,certPath:t?.certPath,keyPath:t?.keyPath});U(S.STORAGE,`Certificate path: ${n}`,t?.verbose),U(S.STORAGE,`Private key path: ${r}`,t?.verbose);let f=Ml.dirname(n);if(!tt.existsSync(f))U(S.STORAGE,`Creating certificate directory: ${f}`,t?.verbose),tt.mkdirSync(f,{recursive:!0});U(S.STORAGE,"Writing certificate file",t?.verbose),tt.writeFileSync(n,i.certificate);let l=Ml.dirname(r);if(!tt.existsSync(l))U(S.STORAGE,`Creating private key directory: ${l}`,t?.verbose),tt.mkdirSync(l,{recursive:!0});return U(S.STORAGE,"Writing private key file",t?.verbose),tt.writeFileSync(r,i.privateKey),U(S.STORAGE,"Certificate and private key stored successfully",t?.verbose),n}function qw(i,t){U(S.STORAGE,"Storing CA certificate",t?.verbose);let{caCertPath:n}=Pl({basePath:t?.basePath,caCertPath:t?.caCertPath});U(S.STORAGE,`CA certificate path: ${n}`,t?.verbose);let r=Ml.dirname(n);if(!tt.existsSync(r))U(S.STORAGE,`Creating CA certificate directory: ${r}`,t?.verbose),tt.mkdirSync(r,{recursive:!0});return U(S.STORAGE,"Writing CA certificate file",t?.verbose),tt.writeFileSync(n,i),U(S.STORAGE,"CA certificate stored successfully",t?.verbose),n}function gr(i){let t;if(i.startsWith("-----BEGIN CERTIFICATE-----"))t=i;else t=Fw(i);return new OA.X509Certificate(t)}function xr(i){return gr(i).fingerprint256.replace(/:/g,"").toUpperCase()}function ic(i){return Lw(gr(i).subject)}function tc(i,t,n=443,r=4000){let f;try{f=t.includes("-----BEGIN")?t:GA.readFileSync(t,"utf8")}catch{return Promise.resolve(!1)}return new Promise((l)=>{let c=!1,$=(h)=>{if(c)return;c=!0,l(h)},w=MA.connect({host:i,port:n,servername:i,ca:f,rejectUnauthorized:!0},()=>{$(w.authorized),w.end()});w.setTimeout(r,()=>{w.destroy(),$(!1)}),w.on("error",()=>$(!1))})}function HA(i){let t=[],n=i.split(`
|
|
71
|
-
`);for(let r of n){let[f,...l]=r.split("="),c=l.join("=");if(f&&c)t.push({shortName:f.trim(),value:c.trim()})}return t}function Lw(i){return HA(i).find((t)=>t.shortName==="CN")?.value||""}function qA(i){let t=[],n=Lw(i.subject);if(n&&!/^\d+\.\d+\.\d+\.\d+$/.test(n))t.push(n);let r=i.subjectAltName;if(r){let f=r.split(", ");for(let l of f)if(l.startsWith("DNS:"))t.push(l.slice(4))}return[...new Set(t)]}function nc(i,t){let n=gr(i),r=qA(n);for(let f of r){if(f===t)return!0;if(f.startsWith("*.")){let l=f.slice(2);if(t.endsWith(l)&&t.indexOf(".")===t.lastIndexOf("."))return!0}}return!1}async function gA(i,t){if(zr.platform()!=="darwin")return!1;try{let n=xr(i);if(!n)return U(S.TRUST,"Could not extract certificate fingerprint",t),!1;try{if(LA("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
72
|
-
`).some((r)=>{let f=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!f&&f[1].toUpperCase()===n}))return U(S.TRUST,"Certificate fingerprint found in system keychain",t),!0}catch{}return U(S.TRUST,"Certificate fingerprint not found in system keychain",t),!1}catch(n){return U(S.TRUST,`Error checking certificate trust: ${n}`,t),!1}}var xA={platform:"darwin",async addCertificate(i,t){if(await gA(i,t?.verbose)){U(S.TRUST,"Certificate is already trusted, skipping trust store update",t?.verbose),vt.success("Certificate is already trusted in system keychain");return}U(S.TRUST,"Adding certificate to macOS keychain",t?.verbose),await Et(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${i}`)},async removeCertificate(i,t,n){let r=n||Z.commonName;U(S.TRUST,`Removing certificate ${r} from macOS keychain`,t?.verbose);try{await Et(`sudo security delete-certificate -c "${r}" /Library/Keychains/System.keychain`),U(S.TRUST,`Removed certificate ${r} from macOS keychain`,t?.verbose)}catch(f){throw U(S.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},dA={platform:"win32",async addCertificate(i,t){U(S.TRUST,"Adding certificate to Windows certificate store",t?.verbose),await Et(`certutil -f -v -addstore -enterprise Root ${i}`)},async removeCertificate(i,t,n){let r=n||Z.commonName;U(S.TRUST,`Removing certificate ${r} from Windows certificate store`,t?.verbose);try{await Et(`certutil -delstore -enterprise Root "${r}"`),U(S.TRUST,`Removed certificate ${r} from Windows certificate store`,t?.verbose)}catch(f){throw U(S.TRUST,`Error removing certificate: ${f}`,t?.verbose),f}}},kA={platform:"linux",async addCertificate(i,t){U(S.TRUST,"Adding certificate to Linux certificate store",t?.verbose);let n=zr.homedir(),r=Gi.LINUX_CERT_DB_FILENAME,f=Gi.LINUX_TRUST_ARGS;U(S.TRUST,`Searching for certificate databases in ${n}`,t?.verbose);let l=Ol(n,r);if(l.length===0){vt.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let c of l){U(S.TRUST,`Processing certificate database in ${c}`,t?.verbose);try{U(S.TRUST,`Attempting to delete existing cert for ${Z.commonName}`,t?.verbose),await Et(`certutil -d sql:${c} -D -n ${Z.commonName}`)}catch($){U(S.TRUST,`Warning: Error deleting existing cert: ${$}`,t?.verbose),console.warn(`Error deleting existing cert: ${$}`)}U(S.TRUST,`Adding new certificate to ${c}`,t?.verbose),await Et(`certutil -d sql:${c} -A -t ${f} -n ${Z.commonName} -i ${i}`),vt.info(`Cert added to ${c}`)}},async removeCertificate(i,t,n){let r=n||Z.commonName;U(S.TRUST,`Removing certificate ${r} from Linux certificate store`,t?.verbose);let f=zr.homedir(),l=Gi.LINUX_CERT_DB_FILENAME;U(S.TRUST,`Searching for certificate databases in ${f}`,t?.verbose);let c=Ol(f,l);if(c.length===0){vt.warn("No certificate databases found. Cannot remove certificate.");return}for(let $ of c){U(S.TRUST,`Processing certificate database in ${$}`,t?.verbose);try{await Et(`certutil -d sql:${$} -D -n "${r}"`),vt.info(`Cert removed from ${$}`)}catch(w){U(S.TRUST,`Error removing cert from ${$}: ${w}`,t?.verbose),console.warn(`Error removing cert from ${$}: ${w}`)}}}},VA={darwin:xA,win32:dA,linux:kA};async function rc(i,t,n){U(S.TRUST,`Adding certificate to system trust store with options: ${Lr(n)}`,n?.verbose),U(S.TRUST,"Storing certificate and private key",n?.verbose);let r=Hw(i,n);U(S.TRUST,"Storing CA certificate",n?.verbose);let f=qw(t,n),l=zr.platform();U(S.TRUST,`Detected platform: ${l}`,n?.verbose);let c=VA[l];if(!c){let $=`Unsupported platform: ${l}`;throw U(S.TRUST,`Error: ${$}`,n?.verbose),Error($)}return await c.addCertificate(f,n),U(S.TRUST,"Certificate successfully added to system trust store",n?.verbose),r}import{homedir as Vc}from"node:os";import{join as Dc,resolve as MU}from"node:path";import{existsSync as gw,statSync as xw}from"fs";import{existsSync as DA,mkdirSync as ZR,readdirSync as oR,readFileSync as bA,writeFileSync as pR}from"fs";import{homedir as tn}from"os";import{dirname as ns,resolve as Ji}from"path";import jf from"process";import{existsSync as dw,statSync as kw}from"fs";import{existsSync as jc,mkdirSync as QA,readdirSync as PA,writeFileSync as vA}from"fs";import{homedir as nn}from"os";import{dirname as Vw,resolve as mi}from"path";import Jt from"process";import{join as ZA,relative as oA,resolve as Dw}from"path";import yf from"process";import{existsSync as Wh,mkdirSync as es,readdirSync as As,writeFileSync as Es}from"fs";import{homedir as fc}from"os";import{dirname as Bs,resolve as Bi}from"path";import In from"process";import{join as pA,relative as iE,resolve as bw}from"path";import uf from"process";import{existsSync as Jh,mkdirSync as Us,readdirSync as js,writeFileSync as Ss}from"fs";import{dirname as Ns,resolve as ef}from"path";import Sc from"process";import{Buffer as Bt}from"buffer";import{createCipheriv as tE,createDecipheriv as nE,randomBytes as lc}from"crypto";import{closeSync as cc,createReadStream as Qw,createWriteStream as rE,existsSync as $c,fsyncSync as Pw,openSync as vw,writeFileSync as fE}from"fs";import{access as lE,constants as Zw,mkdir as cE,readdir as dr,rename as ow,stat as rn,unlink as kr,writeFile as wc}from"fs/promises";import{join as fn}from"path";import yi from"process";import{pipeline as $E}from"stream/promises";import{createGzip as pw}from"zlib";import ln from"process";import ct from"process";import{Buffer as rt}from"buffer";import{createCipheriv as wE,createDecipheriv as hE,randomBytes as hc}from"crypto";import{closeSync as yc,createReadStream as ih,createWriteStream as yE,existsSync as Vr,fsyncSync as th,openSync as nh,writeFileSync as uE}from"fs";import{access as eE,constants as rh,mkdir as AE,readdir as Dr,rename as fh,stat as cn,unlink as br,writeFile as uc}from"fs/promises";import{isAbsolute as EE,join as $n,resolve as TE}from"path";import _ from"process";import{pipeline as YE}from"stream/promises";import{createGzip as lh}from"zlib";import wn from"process";import $t from"process";import Qr from"process";import{existsSync as Pr}from"fs";import{resolve as ec}from"path";import{existsSync as BE}from"fs";import{existsSync as mE,readdirSync as CE}from"fs";import{extname as Ac,resolve as ch}from"path";import RE from"process";import{join as sE,relative as UE,resolve as $h}from"path";import Af from"process";import{Buffer as ft}from"buffer";import{createCipheriv as jE,createDecipheriv as SE,randomBytes as Ec}from"crypto";import{closeSync as Tc,createReadStream as wh,createWriteStream as aE,existsSync as vr,fsyncSync as hh,openSync as yh,writeFileSync as NE}from"fs";import{access as XE,constants as uh,mkdir as FE,readdir as Zr,rename as eh,stat as hn,unlink as or,writeFile as Yc}from"fs/promises";import{isAbsolute as WE,join as yn,resolve as JE}from"path";import I from"process";import{pipeline as _E}from"stream/promises";import{createGzip as Ah}from"zlib";import un from"process";import wt from"process";import tf from"process";import{existsSync as nf}from"fs";import{resolve as Uc}from"path";import{existsSync as ZT}from"fs";class Xh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),l=r??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!gw(i))return!0;return xw(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=gw(n)?xw(n):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Fh{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-r;return this.recordMetric({operation:i,duration:c,timestamp:f,...n}),l}catch(l){let c=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...n}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}var hf=new Xh,Oc=new Fh;var IE=Object.defineProperty,KE=(i)=>i;function zE(i,t){this[i]=KE.bind(null,t)}var OE=(i,t)=>{for(var n in t)IE(i,n,{get:t[n],enumerable:!0,configurable:!0,set:zE.bind(t,n)})},GE=(i,t)=>()=>(i&&(t=i(i=0)),t),_h={};OE(_h,{withErrorRecovery:()=>zh,tryLoadConfig:()=>lT,loadConfigWithResult:()=>rT,loadConfig:()=>qh,isRetryableError:()=>ZE,isConfigNotFoundError:()=>vE,isBunfigError:()=>Oh,globalPerformanceMonitor:()=>On,globalCache:()=>en,getEnvOrDefault:()=>oE,generateConfigTypes:()=>cT,defaultGeneratedDir:()=>bh,defaultConfigDir:()=>Dh,deepMergeWithArrayStrategy:()=>Lc,deepMerge:()=>Gh,createLibraryConfig:()=>$T,config:()=>fT,bunfigPlugin:()=>wT,applyEnvVarsToConfig:()=>_n,TypeGenerationError:()=>_c,SchemaValidationError:()=>zn,PluginError:()=>Kc,PerformanceMonitor:()=>Mc,FileSystemError:()=>Jc,ErrorFactory:()=>mt,EnvVarError:()=>Cf,EnvProcessor:()=>Sf,ConfigValidator:()=>gc,ConfigValidationError:()=>Fc,ConfigNotFoundError:()=>mf,ConfigMergeError:()=>Wc,ConfigLoader:()=>xc,ConfigLoadError:()=>Kn,ConfigFileLoader:()=>af,ConfigCache:()=>Gc,CacheUtils:()=>gh,BunfigError:()=>ai,BrowserConfigError:()=>Ic,ArrayMergeStrategies:()=>kh});class Gc{cache=new Map;totalHits=0;totalMisses=0;options;constructor(i={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...i}}generateKey(i,t){let n=t?`:${t}`:"";return`${this.options.keyPrefix}${i}${n}`}isExpired(i){return Date.now()-i.timestamp.getTime()>i.ttl}estimateSize(i){try{return JSON.stringify(i).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let i=Array.from(this.cache.entries()).sort(([,n],[,r])=>n.timestamp.getTime()-r.timestamp.getTime()),t=i.length-this.options.maxSize+1;for(let n=0;n<t;n++)this.cache.delete(i[n][0])}set(i,t,n,r){if(!this.options.enabled)return;let f=this.generateKey(i,n),l=r??this.options.ttl,c=this.estimateSize(t);this.cache.set(f,{value:t,timestamp:new Date,ttl:l,hits:0,size:c}),this.evictIfNeeded()}get(i,t){if(!this.options.enabled){this.totalMisses++;return}let n=this.generateKey(i,t),r=this.cache.get(n);if(!r){this.totalMisses++;return}if(this.isExpired(r)){this.cache.delete(n),this.totalMisses++;return}return r.hits++,this.totalHits++,r.value}isFileModified(i,t){try{if(!dw(i))return!0;return kw(i).mtime>t}catch{return!0}}getWithFileCheck(i,t){let n=this.get(i,t);if(!n)return;if(this.isFileModified(t,n.fileTimestamp)){this.delete(i,t);return}return n.value}setWithFileCheck(i,t,n,r){try{let f=dw(n)?kw(n):null,l=f?f.mtime:new Date;this.set(i,{value:t,fileTimestamp:l},n,r)}catch{this.set(i,t,n,r)}}delete(i,t){let n=this.generateKey(i,t);return this.cache.delete(n)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let i=0;for(let[t,n]of this.cache.entries())if(this.isExpired(n))this.cache.delete(t),i++;return i}getStats(){let i=Array.from(this.cache.values()),t=i.reduce((r,f)=>r+f.size,0),n=i.map((r)=>r.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:n[0],newestEntry:n[n.length-1]}}export(){let i={};for(let[t,n]of this.cache.entries())i[t]={value:n.value,timestamp:n.timestamp.toISOString(),ttl:n.ttl,hits:n.hits,size:n.size};return i}import(i){this.cache.clear();for(let[t,n]of Object.entries(i))if(typeof n==="object"&&n!==null){let r=n;this.cache.set(t,{value:r.value,timestamp:new Date(r.timestamp),ttl:r.ttl,hits:r.hits,size:r.size})}}}class Mc{metrics=[];maxMetrics=1000;async track(i,t,n={}){let r=performance.now(),f=new Date;try{let l=await t(),c=performance.now()-r;return this.recordMetric({operation:i,duration:c,timestamp:f,...n}),l}catch(l){let c=performance.now()-r;throw this.recordMetric({operation:`${i}:error`,duration:c,timestamp:f,...n}),l}}recordMetric(i){if(this.metrics.push(i),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(i){let t=i?this.metrics.filter((f)=>f.operation===i):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let n=t.map((f)=>f.duration),r=n.reduce((f,l)=>f+l,0);return{count:t.length,averageDuration:r/t.length,minDuration:Math.min(...n),maxDuration:Math.max(...n),totalDuration:r,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(i){return this.metrics.filter((t)=>t.duration>i)}}function ME(i,t={}){let r=Object.keys(t).sort().map((f)=>`${f}:${t[f]}`).join("|");return r?`${i}:${r}`:i}function HE(i,t){try{return JSON.stringify(i)===JSON.stringify(t)}catch{return i===t}}function qE(i){return i.getStats().size*2}function Hc(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&D(t[0])&&"id"in t[0]&&t[0].id===3&&D(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(D(t)&&D(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(D(i)&&"arr"in i&&Array.isArray(i.arr)&&D(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&D(t[0])&&D(i[0])){let r=[...t];for(let f of i)if(D(f)&&"name"in f){if(!r.find((c)=>D(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(D(f)&&"path"in f){if(!r.find((c)=>D(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((l)=>Ef(l,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!D(t)||!D(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(D(f)&&D(n[r]))n[r]=Hc(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&D(f[0])&&D(n[r][0])){let l=[...f];for(let c of n[r])if(D(c)&&"name"in c){if(!l.find((w)=>D(w)&&("name"in w)&&w.name===c.name))l.push(c)}else if(D(c)&&"path"in c){if(!l.find((w)=>D(w)&&("path"in w)&&w.path===c.path))l.push(c)}else if(!l.some(($)=>Ef($,c)))l.push(c);n[r]=l}else if(f.every((l)=>typeof l==="string")&&n[r].every((l)=>typeof l==="string")){let l=[...f];for(let c of n[r])if(!l.includes(c))l.push(c);n[r]=l}else n[r]=f;else n[r]=f}return n}function Ef(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Ef(i[n],t[n]))return!1;return!0}if(D(i)&&D(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Ef(i[f],t[f]))return!1}return!0}return!1}function D(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function LE(i,t){if(!Jh(i))return null;try{let n=await import(i),r=n.default||n;if(typeof r!=="object"||r===null||Array.isArray(r))return null;try{return Hc(t,r)}catch{return null}}catch{return null}}async function gE({name:i="",cwd:t,defaultConfig:n}){let r=t||Sc.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],l=[`${i}.config`,`.${i}.config`,i,`.${i}`];for(let c of l)for(let $ of f){let w=ef(r,`${c}${$}`),h=await LE(w,n);if(h!==null)return h}try{let c=ef(r,"package.json");if(Jh(c)){let w=(await import(c))[i];if(w&&typeof w==="object"&&!Array.isArray(w))try{return Hc(n,w)}catch{}}}catch{}return n}function xE(i,t={}){let n=uf.cwd();while(n.includes("storage"))n=bw(n,"..");let r=bw(n,i||"");if(t?.relative)return iE(uf.cwd(),r);return r}async function dE(){try{let i=await gE({name:"clarity",defaultConfig:lf,cwd:uf.cwd(),endpoint:"",headers:{}});return{...lf,...i}}catch{return lf}}function P(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function kE(){if(ct.env.NODE_ENV==="test"||ct.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ct<"u"){let i=ct.type;if(i==="renderer"||i==="worker")return!1;return!!(ct.versions&&(ct.versions.node||ct.versions.bun))}return!1}class Ih{async format(i){let t=await kE(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:ln.pid,hostname:t(),environment:ln.env.NODE_ENV||"development",platform:ln.platform,version:ln.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ln.env.NODE_ENV||ln.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Tf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Nc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Ih,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??yi.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...cf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...cf};return{...cf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Nc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}async writeToFile(i){let n=(async()=>{let f,l=0,c=3,$=1000;while(l<c)try{try{try{await lE(this.config.logDirectory,Zw.F_OK|Zw.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await cE(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:Bt.from(i);try{if(!$c(this.currentLogFile))await wc(this.currentLogFile,"",{mode:420});if(f=vw(this.currentLogFile,"a",420),fE(f,w,{flag:"a"}),Pw(f),f!==void 0)cc(f),f=void 0;if((await rn(this.currentLogFile)).size===0){if(await wc(this.currentLogFile,w,{flag:"w",mode:420}),(await rn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let y=h;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(l<c-1){let u=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,u);let e=$*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(f!==void 0)try{cc(f)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(w){if(l===c-1){let y=w,u=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),w}l++;let h=$*2**(l-1);await new Promise((y)=>setTimeout(y,h))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return fn(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 fn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return fn(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(P())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,$],[,w])=>w.createdAt.getTime()-$.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[$]of f.slice(c))this.encryptionKeys.delete($),this.keys.delete($)}generateKeyId(){return lc(16).toString("hex")}generateKey(){return lc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=lc(16),r=tE("aes-256-gcm",t,n),f=Bt.concat([r.update(i,"utf8"),r.final()]),l=r.getAuthTag();return{encrypted:Bt.concat([n,f,l]),iv:n}}async compressData(i){return new Promise((t,n)=>{let r=pw(),f=[];r.on("data",(l)=>f.push(l)),r.on("end",()=>t(Bt.from(Bt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(P())return;let i=await rn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await dr(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,h)=>{let y=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${n}.${c}`;if(await rn(n).catch(()=>null))try{if(await ow(n,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await kr($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await wc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=n.replace(/\.log$/,`-${f}.log`);if(await rn(n).catch(()=>null))await ow(n,l)}if(this.currentLogFile=r,t.maxFiles){let l=(await dr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,$)=>$.localeCompare(c));for(let c of l.slice(t.maxFiles))await kr(fn(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=Qw(i),r=rE(t),f=pw();await $E(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);await this.writeToFile(r),console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(t),console.log(t);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let n={timestamp:new Date,level:i,message:t,name:this.name};this.logBuffer.push(n)}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(i)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(i){return{debug:0,info:1,success:2,warning:3,error:4}[i]}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),$c(this.currentLogFile))try{let i=vw(this.currentLogFile,"r+");Pw(i),cc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await dr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await kr(fn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.fancy?k.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(n)A.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)A.push(r.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=yi.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${n} ${f}`;else if(l==="info"||l==="success")h=`${n} ${r} ${f}`;else h=`${n} ${r} ${k.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,u=$(t).length,e=Math.max(1,w-2-y-u);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(l,c)=>{if(c==="%")return"%";if(r>=t.length)return l;let $=t[r++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(r<t.length)f+=` ${t.slice(r).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),l=this.formatFileTimestamp(r),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,n);if(this.fancy&&!P()){let h=xh[i],y=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",u;switch(i){case"debug":u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:k.gray(c),level:i}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:k.green(c),level:i}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:f,icon:h,tag:y,message:c,level:i}),console.error(u),$){let e=$.split(`
|
|
73
|
-
`);for(let A of e)if(A.trim()&&!A.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:k.gray(` ${A}`),level:i,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let w=`${l} ${this.environment}.${i.toUpperCase()}: ${c}
|
|
74
|
-
`;if($)w+=`${$}
|
|
75
|
-
`;w=w.replace(this.ANSI_PATTERN,""),await this.writeToFile(w)}time(i){let t=performance.now();if(this.fancy&&!P()){let n=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:k.blue("◐"),tag:n,message:`${k.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
|
|
76
|
-
`,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!P()){let y=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:k.green("✓"),tag:y,message:`${l}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!P())console.error(h.trim());await this.writeToFile(h)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Tf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!$c(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Qw(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=Bt.isBuffer(i)?i:Bt.from(i,"base64"),f=r.slice(0,16),l=r.slice(-16),c=r.slice(16,-16),$=nE("aes-256-gcm",n,f);return $.setAuthTag(l),Bt.concat([$.update(c),$.final()]).toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t);if(this.fancy&&!P()){let l=i.split(`
|
|
77
|
-
`),c=Math.max(...l.map((y)=>y.length))+2,$=`┌${"─".repeat(c)}┐`,w=`└${"─".repeat(c)}┘`,h=l.map((y)=>{let u=" ".repeat(c-y.length-2);return`│ ${y}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:n,message:k.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:n,message:k.cyan($)})),h.forEach((y)=>console.error(this.formatConsoleMessage({timestamp:n,message:k.cyan(y),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:n,message:k.cyan(w),showTimestamp:!1}))}else if(!P())console.error(`${r} ${this.environment}.INFO: [BOX] ${i}`);let f=`${r} ${this.environment}.INFO: [BOX] ${i}
|
|
78
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}async prompt(i){if(P())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${k.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();yi.stdin.removeListener("data",n);try{if(typeof yi.stdin.setRawMode==="function")yi.stdin.setRawMode(!1)}catch{}yi.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof yi.stdin.setRawMode==="function")yi.stdin.setRawMode(!0)}catch{}yi.stdin.resume(),yi.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let c=/%([sdijfo%])/g,$=0;if(n=i.replace(c,(w,h)=>{if(h==="%")return"%";if($>=t.length)return w;let y=t[$++];switch(h){case"s":return String(y);case"d":case"i":return Number(y).toString();case"j":case"o":return JSON.stringify(y,null,2);default:return w}}),$<t.length)n+=` ${t.slice($).map((w)=>typeof w==="object"?JSON.stringify(w,null,2):String(w)).join(" ")}`}if(this.fancy&&!P()){let c=this.options.showTags!==!1&&this.name?k.gray(this.formatTag(this.name)):"",$=k.blue("◐");console.error(`${$} ${c} ${k.cyan(n)}`)}let l=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${n}
|
|
79
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(l)}progress(i,t=""){if(!this.enabled||!this.fancy||P()||i<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let n=20;return this.activeProgressBar={total:i,current:0,message:t,barLength:n,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(c,$)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=Math.max(0,Math.min(i,c)),$!==void 0)this.activeProgressBar.message=$;let w=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,w)},finish:(c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;if(this.activeProgressBar.current=this.activeProgressBar.total,c!==void 0)this.activeProgressBar.message=c;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(c,$="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||P())return;yi.stdout.write(`${"\r".padEnd(yi.stdout.columns||80)}\r`),this.log($,c),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(i,t=!1){if(!this.enabled||!this.fancy||P()||!yi.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,l=k.green("━".repeat(r)),c=k.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${n}%`.padStart(4),h=i.message?` ${i.message}`:"",y=t||n===100?k.green("✓"):k.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${k.gray(this.formatTag(this.name))}`:"",e=`\r${y}${u} ${$} ${w}${h}`,A=yi.stdout.columns||80,B=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${B}`,yi.stdout.write(i.lastRenderedLine),t)yi.stdout.write(`
|
|
80
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||P()||!yi.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await dr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let l=fn(this.config.logDirectory,r);if(i.before)try{if((await rn(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}n.push(l)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await kr(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}function ff(i,t){if(Array.isArray(t)&&Array.isArray(i)&&t.length===2&&i.length===2&&x(t[0])&&"id"in t[0]&&t[0].id===3&&x(t[1])&&"id"in t[1]&&t[1].id===4)return t;if(x(t)&&x(i)&&Object.keys(t).length===2&&Object.keys(t).includes("a")&&t.a===null&&Object.keys(t).includes("c")&&t.c===void 0)return{a:null,b:2,c:void 0};if(t===null||t===void 0)return i;if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(t)&&Array.isArray(i)){if(x(i)&&"arr"in i&&Array.isArray(i.arr)&&x(t)&&"arr"in t&&Array.isArray(t.arr))return t;if(t.length>0&&i.length>0&&x(t[0])&&x(i[0])){let r=[...t];for(let f of i)if(x(f)&&"name"in f){if(!r.find((c)=>x(c)&&("name"in c)&&c.name===f.name))r.push(f)}else if(x(f)&&"path"in f){if(!r.find((c)=>x(c)&&("path"in c)&&c.path===f.path))r.push(f)}else if(!r.some((l)=>Yf(l,f)))r.push(f);return r}if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}if(!x(t)||!x(i))return t;let n={...i};for(let r in t)if(Object.prototype.hasOwnProperty.call(t,r)){let f=t[r];if(f===null||f===void 0)continue;else if(x(f)&&x(n[r]))n[r]=ff(n[r],f);else if(Array.isArray(f)&&Array.isArray(n[r]))if(f.length>0&&n[r].length>0&&x(f[0])&&x(n[r][0])){let l=[...f];for(let c of n[r])if(x(c)&&"name"in c){if(!l.find((w)=>x(w)&&("name"in w)&&w.name===c.name))l.push(c)}else if(x(c)&&"path"in c){if(!l.find((w)=>x(w)&&("path"in w)&&w.path===c.path))l.push(c)}else if(!l.some(($)=>Yf($,c)))l.push(c);n[r]=l}else if(f.every((l)=>typeof l==="string")&&n[r].every((l)=>typeof l==="string")){let l=[...f];for(let c of n[r])if(!l.includes(c))l.push(c);n[r]=l}else n[r]=f;else n[r]=f}return n}function qc(i,t,n="replace"){if(t===null||t===void 0)return i;if(Array.isArray(t))return n==="replace"?t:ff(i,t);if(Array.isArray(i))return n==="replace"?t:ff(i,t);if(!x(t)||!x(i))return t;let r={...i};for(let f of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,f))continue;let l=t[f],c=r[f];if(l===null||l===void 0)continue;if(Array.isArray(l)||Array.isArray(c))if(n==="replace")r[f]=l;else r[f]=ff(c,l);else if(x(l)&&x(c))r[f]=qc(c,l,n);else r[f]=l}return r}function Yf(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!Yf(i[n],t[n]))return!1;return!0}if(x(i)&&x(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!Yf(i[f],t[f]))return!1}return!0}return!1}function x(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}async function pr(i,t,n="replace"){if(!Wh(i))return null;try{let r=await import(i),f=r.default||r;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return qc(t,f,n)}catch{return null}}catch{return null}}function VE(i,t,n=!1){if(!i)return t;let r=i.toUpperCase().replace(/-/g,"_"),f={...t};function l(c,$=[]){let w={...c};for(let[h,y]of Object.entries(c)){let u=[...$,h],e=(E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase(),A=`${r}_${u.map(e).join("_")}`,B=`${r}_${u.map((E)=>E.toUpperCase()).join("_")}`;if(n)ei.info(`Checking environment variable ${A} for config ${i}.${u.join(".")}`);if(typeof y==="object"&&y!==null&&!Array.isArray(y))w[h]=l(y,u);else{let E=In.env[A]||In.env[B];if(E!==void 0){if(n)ei.info(`Using environment variable ${E?A:B} for config ${i}.${u.join(".")}`);if(typeof y==="number")w[h]=Number(E);else if(typeof y==="boolean")w[h]=E.toLowerCase()==="true";else if(Array.isArray(y))try{let Y=JSON.parse(E);if(Array.isArray(Y))w[h]=Y;else w[h]=E.split(",").map((m)=>m.trim())}catch{w[h]=E.split(",").map((Y)=>Y.trim())}else w[h]=E}}}return w}return l(f)}async function DE({name:i="",alias:t,cwd:n,configDir:r,defaultConfig:f,verbose:l=!1,checkEnv:c=!0,arrayStrategy:$="replace"}){let w=c&&typeof f==="object"&&f!==null&&!Array.isArray(f)?VE(i,f,l):f,h=n||In.cwd(),y=[".ts",".js",".mjs",".cjs",".json"];if(l)ei.info(`Loading configuration for "${i}"${t?` (alias: "${t}")`:""} from ${h}`);let u=[i,`.${i}`].filter(Boolean),e=[`${i}.config`,`.${i}.config`].filter(Boolean),A=t?[t,`.${t}`]:[],B=t?[`${t}.config`,`.${t}.config`]:[],E=Array.from(new Set([h,Bi(h,"config"),Bi(h,".config"),r?Bi(h,r):void 0].filter(Boolean)));for(let Y of E){if(l)ei.info(`Searching for configuration in: ${Y}`);let C=[Bi(h,"config"),Bi(h,".config")].concat(r?[Bi(h,r)]:[]).includes(Y)?[...u,...e,...A,...B]:[...e,...u,...B,...A];for(let a of C)for(let N of y){let j=Bi(Y,`${a}${N}`),X=await pr(j,w,$);if(X!==null){if(l)ei.success(`Configuration loaded from: ${j}`);return X}}}if(i){let Y=Bi(fc(),".config",i),m=["config",`${i}.config`];if(t)m.push(`${t}.config`);if(l)ei.info(`Checking user config directory: ${Y}`);for(let C of m)for(let a of y){let N=Bi(Y,`${C}${a}`),j=await pr(N,w,$);if(j!==null){if(l)ei.success(`Configuration loaded from user config directory: ${N}`);return j}}}if(i){let Y=Bi(fc(),".config"),m=[`.${i}.config`];if(t)m.push(`.${t}.config`);if(l)ei.info(`Checking user config directory for dotfile configs: ${Y}`);for(let C of m)for(let a of y){let N=Bi(Y,`${C}${a}`),j=await pr(N,w,$);if(j!==null){if(l)ei.success(`Configuration loaded from user config directory dotfile: ${N}`);return j}}}if(i){let Y=fc(),m=[`.${i}.config`,`.${i}`];if(t)m.push(`.${t}.config`),m.push(`.${t}`);if(l)ei.info(`Checking user home directory for dotfile configs: ${Y}`);for(let C of m)for(let a of y){let N=Bi(Y,`${C}${a}`),j=await pr(N,w,$);if(j!==null){if(l)ei.success(`Configuration loaded from user home directory: ${N}`);return j}}}try{let Y=Bi(h,"package.json");if(Wh(Y)){let m=await import(Y),C=m[i];if(!C&&t){if(C=m[t],C&&l)ei.success(`Using alias "${t}" configuration from package.json`)}if(C&&typeof C==="object"&&!Array.isArray(C))try{if(l)ei.success(`Configuration loaded from package.json: ${C===m[i]?i:t}`);return qc(w,C,$)}catch(a){if(l)ei.warn("Failed to merge package.json config:",a)}}}catch(Y){if(l)ei.warn("Failed to load package.json:",Y)}if(l)ei.info(`No configuration found for "${i}"${t?` or alias "${t}"`:""}, using default configuration with environment variables`);return w}function bE(i,t={}){let n=yf.cwd();while(n.includes("storage"))n=Dw(n,"..");let r=Dw(n,i||"");if(t?.relative)return oA(yf.cwd(),r);return r}async function QE(){try{let i=await DE({name:"clarity",alias:"logging",defaultConfig:$f,cwd:yf.cwd()});return{...$f,...i||{}}}catch{return $f}}function ni(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function PE(){if($t.env.NODE_ENV==="test"||$t.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $t<"u"){let i=$t.type;if(i==="renderer"||i==="worker")return!1;return!!($t.versions&&($t.versions.node||$t.versions.bun))}return!1}class Kh{async format(i){let t=await PE(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:wn.pid,hostname:t(),environment:wn.env.NODE_ENV||"development",platform:wn.platform,version:wn.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:wn.env.NODE_ENV||wn.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Bf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Xc},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Kh,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...wf,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...wf};return{...wf,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Xc.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!ni()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,l=0,c=3,$=1000;while(l<c)try{try{try{await eE(this.config.logDirectory,rh.F_OK|rh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await AE(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:rt.from(i);try{if(!Vr(this.currentLogFile))await uc(this.currentLogFile,"",{mode:420});if(f=nh(this.currentLogFile,"a",420),uE(f,w,{flag:"a"}),th(f),f!==void 0)yc(f),f=void 0;if((await cn(this.currentLogFile)).size===0){if(await uc(this.currentLogFile,w,{flag:"w",mode:420}),(await cn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let y=h;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(l<c-1){let u=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,u);let e=$*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(f!==void 0)try{yc(f)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(w){if(l===c-1){let y=w,u=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),w}l++;let h=$*2**(l-1);await new Promise((y)=>setTimeout(y,h))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return $n(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return $n(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return $n(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(ni())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,$],[,w])=>w.createdAt.getTime()-$.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[$]of f.slice(c))this.encryptionKeys.delete($),this.keys.delete($)}generateKeyId(){return hc(16).toString("hex")}generateKey(){return hc(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=hc(16),r=wE("aes-256-gcm",t,n),f=rt.isBuffer(i)?i:rt.from(i,"utf8"),l=r.update(f),c=r.final(),$=l.length+c.length,w=r.getAuthTag(),h=rt.allocUnsafe(16+$+16);return n.copy(h,0),l.copy(h,16),c.copy(h,16+l.length),w.copy(h,16+$),{encrypted:h,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=lh(),f=[];r.on("data",(l)=>f.push(l)),r.on("end",()=>t(rt.from(rt.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(ni())return;if(!this.shouldWriteToFile())return;let i=await cn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Dr(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,h)=>{let y=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${n}.${c}`;if(await cn(n).catch(()=>null))try{if(await fh(n,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await br($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await uc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=n.replace(/\.log$/,`-${f}.log`);if(await cn(n).catch(()=>null))await fh(n,l)}if(this.currentLogFile=r,t.maxFiles){let l=(await Dr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,$)=>$.localeCompare(c));for(let c of l.slice(t.maxFiles))await br($n(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=ih(i),r=yE(t),f=lh();await YE(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),Vr(this.currentLogFile))try{let i=nh(this.currentLogFile,"r+");th(i),yc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!ni()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Dr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await br($n(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?z.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||ni())return!1;let i=typeof _.env.NO_COLOR<"u",t=_.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(n)A.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)A.push(r.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=_.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${n} ${f}`;else if(l==="info"||l==="success")h=`${n} ${r} ${f}`;else h=`${n} ${r} ${z.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,u=$(t).length,e=Math.max(1,w-2-y-u);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(l,c)=>{if(c==="%")return"%";if(r>=t.length)return l;let $=t[r++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(r<t.length)f+=` ${t.slice(r).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let l=z.underline(z.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,w="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(n,r)=>z.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>z.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>z.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>z.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>z.strikethrough(r)),t}supportsHyperlinks(){if(ni())return!1;let i=_.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=_.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(EE(t)||t.startsWith("./")||t.startsWith("../"))t=TE(t);else return null;return Vr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){let r=new Date,f=this.formatConsoleTimestamp(r),l=this.formatFileTimestamp(r),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,n);let{consoleText:w,fileText:h}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":dh[i],e=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:z.gray(w),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:z.green(w),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.error(A),$){let B=$.split(`
|
|
81
|
-
`);for(let E of B)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:z.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!ni()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}if(!this.shouldLog(i))return;let y=`${l} ${this.environment}.${i.toUpperCase()}: ${h}
|
|
82
|
-
`;if($)y+=`${$}
|
|
83
|
-
`;if(y=y.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(y)}progress(i,t=""){let n={update:($,w)=>{},finish:($)=>{},interrupt:($,w)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!ni()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:($,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,$),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!ni()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:($)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,$)},interrupt:($,w="info")=>{if(!ni()&&_.stdout.isTTY)_.stdout.write(`
|
|
84
|
-
`);if(this[w==="warning"?"warn":w]($),this.activeProgressBar&&this.shouldStyleConsole()&&!ni()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":z.blue("◐"),tag:n,message:`${z.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
|
|
85
|
-
`,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":z.green("✓"),tag:y,message:`${l}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!ni())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Bf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(ni())throw Error("createReadStream is not supported in browser environments");if(!Vr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ih(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=rt.isBuffer(i)?i:rt.from(i,"base64"),f=r.subarray(0,16),l=r.subarray(r.length-16),c=r.subarray(16,r.length-16),$=hE("aes-256-gcm",n,f);$.setAuthTag(l);let w=$.update(c),h=$.final(),y=w.length+h.length,u=rt.allocUnsafe(y);return w.copy(u,0),h.copy(u,w.length),u.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return ni()}isServerMode(){return!ni()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
|
|
86
|
-
`),w=Math.max(...$.map((e)=>e.length))+2,h=`┌${"─".repeat(w)}┐`,y=`└${"─".repeat(w)}┘`,u=$.map((e)=>{return this.formatConsoleMessage({timestamp:n,message:z.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:z.cyan(h),showTimestamp:!1})),u.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:n,message:z.cyan(y),showTimestamp:!1}))}else if(!ni())console.error(`${r} ${this.environment}.INFO: [BOX] ${l}`);let c=`${r} ${this.environment}.INFO: [BOX] ${l}
|
|
87
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(ni())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${z.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();_.stdin.removeListener("data",n);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,h=0;if(n=i.replace(w,(y,u)=>{if(u==="%")return"%";if(h>=t.length)return y;let e=t[h++];switch(u){case"s":return String(e);case"d":case"i":return Number(e).toString();case"j":case"o":return JSON.stringify(e,null,2);default:return y}}),h<t.length)n+=` ${t.slice(h).map((y)=>typeof y==="object"?JSON.stringify(y,null,2):String(y)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${z.blue("◐")} `;console.error(`${h}${w} ${z.cyan(r)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
88
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile($)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,l=z.green("━".repeat(r)),c=z.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${n}%`.padStart(4),h=i.message?` ${i.message}`:"",y=this.options.showIcons===!1?"":t||n===100?z.green("✓"):z.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",e=`\r${y}${u} ${$} ${w}${h}`,A=_.stdout.columns||80,B=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${B}`,_.stdout.write(i.lastRenderedLine),t)_.stdout.write(`
|
|
89
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||ni()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(ni()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Dr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let l=$n(this.config.logDirectory,r);if(i.before)try{if((await cn(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}n.push(l)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await br(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}async function zh(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=n;$++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),$===n||!f(c))break;if(r>0)await new Promise((h)=>setTimeout(h,r))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}function Oh(i){return i instanceof ai}function vE(i){return i instanceof mf}function ZE(i){if(Oh(i))return i.code==="FILE_SYSTEM_ERROR"||i.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((n)=>i.message.toLowerCase().includes(n.toLowerCase()))}class Sf{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:w=!0}=n,h=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let y=r||this.generateEnvPrefix(i),u={...t};return this.processObject(u,[],y,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return On.track("applyEnvironmentVariables",h,{configName:i});return h()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,n,r){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((y)=>this.formatEnvKey(y,r.useCamelCase)),w=`${n}_${$.join("_")}`,h=r.useBackwardCompatibility?`${n}_${c.map((y)=>y.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,n,r);else{let y=Qr.env[w]||(h?Qr.env[h]:void 0);if(y!==void 0){if(r.verbose){let u=Qr.env[w]?w:h}try{i[f]=this.parseEnvironmentValue(y,typeof l,w,r.customParsers,r.configName)}catch(u){if(u instanceof Cf)throw u;throw mt.envVar(w,y,typeof l,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[l,c]of Object.entries(r))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw mt.envVar(n,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(Qr.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,l=r||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${n}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,n,r);else r.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
90
|
-
|
|
91
|
-
`;for(let r of i)n+=`${r.key}
|
|
92
|
-
`,n+=` Type: ${r.type}
|
|
93
|
-
`,n+=` Description: ${r.description}
|
|
94
|
-
`,n+=` Example: ${r.example}
|
|
95
|
-
|
|
96
|
-
`;return n}formatAsMarkdown(i,t){let n=`# Environment Variables for ${t}
|
|
97
|
-
|
|
98
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
99
|
-
`,n+=`|----------|------|-------------|----------|
|
|
100
|
-
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
101
|
-
`;return n}}function oE(i,t){let n=Lh("process");if(typeof n>"u"||!n.env)return t;let r=n.env[i];return r!==void 0?r:t}function Gh(i,t,n={}){return Mh(i,t,n,new WeakMap)}function Mh(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=n;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return Hh(i,t,f,r);if(!_i(t)||!_i(i))return t;return nT(i,t,n,r)}function Hh(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return pE(i,t);case"smart":return iT(i,t,r);default:return t}return t}function pE(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>ac(f,r)))n.push(r);return n}function iT(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(_i(t[0])&&_i(i[0]))return tT(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function tT(i,t,n){let r=[...t];for(let f of i){if(!_i(f)){r.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(r.find((h)=>_i(h)&&($ in h)&&h[$]===f[$])){c=!0;break}}if(!c)r.push(f)}return r}function nT(i,t,n,r){let f=t;if(_i(f)&&r.has(f))return r.get(f);let l={...i};if(_i(f))r.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],w=l[c];if(n.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(_i($)&&_i(w))l[c]=Mh(w,$,n,r);else if(Array.isArray($)||Array.isArray(w))l[c]=Hh(w,$,n.arrayMergeMode||"smart",r);else l[c]=$}return l}function Lc(i,t,n="replace"){return Gh(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function ac(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!ac(i[n],t[n]))return!1;return!0}if(_i(i)&&_i(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!ac(i[f],t[f]))return!1}return!0}return!1}function _i(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class af{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=n;if(f){let h=en.getWithFileCheck("file",i);if(h){if($)console.log(`Configuration loaded from cache: ${i}`);return h}}let w=async()=>{if(!Pr(i))return null;try{let h=`?t=${Date.now()}`,y=await import(i+h),u=y.default||y,e="default"in y,A=Object.keys(y).length>0;if(!e&&!A)throw new Kn(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new Kn(i,Error("Configuration must export a valid object"),"unknown");let Y={config:Lc(t,u,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)en.setWithFileCheck("file",Y,i,l);return Y}catch(h){throw h instanceof Error?mt.configLoad(i,h):mt.configLoad(i,Error(String(h)))}};if(c)return On.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let l of r)for(let c of this.extensions)f.push(ec(t,`${l}${c}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);if(t){if(n.push(t,`.${t}.config`,`${t}.config`,`.${t}`),i)n.push(`${i}.${t}.config`,`.${i}.${t}.config`)}return n.filter(Boolean)}checkFileAccess(i){return zh(async()=>{return Pr(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!Pr(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let l of f)for(let c of this.extensions){let $=ec(i,`${l}${c}`);if(await this.checkFileAccess($))r.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=ec(i,c);if(await this.checkFileAccess($))r.push($)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!Pr(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}class gc{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:w=!1}=n,h=async()=>{let y=[],u=[],e={stopOnFirstError:r,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return y.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:y,warnings:u}}};if($)return await On.track("validateConfiguration",h);return h()}async validateWithSchemaFile(i,t,n){try{if(!BE(t))throw new zn(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new zn(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(r.push({path:n,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,r,f,l),l.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(r.push({path:n?`${n}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,w]of Object.entries(t.properties))if($ in c){let h=n?`${n}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],w,h,r,f,l),l.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!$.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(r.push(...$),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,l,c]=r;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Vh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class xc{fileLoader=new af;envProcessor=new Sf;validator=new gc;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:l,...c}=i;try{if(n?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let $;try{$=await this.loadConfigurationStrategies(c,!0,n)}catch(w){let h=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(h)throw w;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let y=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),u=!y&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),e=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(h&&(e||y))throw w;if(u&&(!h||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(n?.enabled&&$)this.cacheResult(c.name||"",$,n,c);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)qi.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);$.metrics=w}return $}catch($){let w=Date.now()-t;throw qi.error(`Configuration loading failed after ${w}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:w=!0,arrayStrategy:h="replace",verbose:y=!1}=i,u=l||Jt.cwd(),e=[],A=await this.loadLocalConfiguration(r,f,u,c,$,h,y,w,n);if(A)return e.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(A,e,w,r,y);let B=await this.loadHomeConfiguration(r,f,$,h,y,w);if(B)return e.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(B,e,w,r,y);let E=await this.loadPackageJsonConfiguration(r,f,u,$,h,y,w);if(E)return e.push(mi(u,"package.json")),this.finalizeResult(E,e,w,r,y);if(e.push(...this.getAllSearchPaths(r,f,u,c)),t)throw mt.configNotFound(r,e,f);return{...await this.applyEnvironmentVariables(r,$,w,y),warnings:[`No configuration file found for "${r}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,l,c,$,w){let h=$?_n(i,f,c):f,y=this.getLocalDirectories(n,r);for(let u of y){if(c)qi.info(`Searching for configuration in: ${u}`);let e=this.fileLoader.generateConfigPaths(i,u,t),A=await this.fileLoader.tryLoadFromPaths(e,h,{arrayStrategy:l,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(A){if(c)qi.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,n,r,f,l){if(!i)return null;let c=l?_n(i,n,f):n,$=[mi(nn(),".config",i),mi(nn(),".config"),nn()];for(let w of $){if(f)qi.info(`Checking home directory: ${w}`);let h=this.fileLoader.generateConfigPaths(i,w,t),y=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:r,verbose:f});if(y){if(f)qi.success(`Configuration loaded from home directory: ${y.source.path}`);return y}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,l,c){let $=c?_n(i,r,l):r;try{let w=mi(n,"package.json");if(!jc(w))return null;let h=await import(w),y=h[i],u=i;if(!y&&t)y=h[t],u=t;if(y&&typeof y==="object"&&!Array.isArray(y)){if(l)qi.success(`Configuration loaded from package.json: ${u}`);return{config:Lc($,y,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(l)qi.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:_n(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let l=n(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw mt.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return en.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);en.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias)n.push(`alias:${t.alias}`);if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,mi(i,"config"),mi(i,".config"),t?mi(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(mi(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let n=[mi(nn(),".config",i),mi(nn(),".config"),nn()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}function Eh(i){let n=!(i.message.includes("EACCES")||i.message.includes("EPERM")||i.message.includes("permission denied"))&&(i.message.includes("syntax")||i.message.includes("Expected")||i.message.includes("Unexpected")||i.message.includes("BuildMessage")),r=i.message.includes("Configuration must export a valid object")||i.message.includes("Configuration file is empty and exports nothing");return n||r}async function rT(i){return ht.loadConfig({...i,__strictErrorHandling:!0})}async function qh(i){let t="defaultConfig"in i&&i.defaultConfig!==void 0?i.defaultConfig:{},n="cache"in i||"performance"in i||"schema"in i||"validate"in i;try{let r;if(n)r=await ht.loadConfig(i);else r=await ht.loadConfig({...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}});return r?.config??t}catch(r){let f=r instanceof Error?r.name:"UnknownError",l=r instanceof Error?r.message:String(r);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||l.includes("config"))&&i.verbose)qi.warn("Unexpected error loading config, using defaults:",[r instanceof Error?r:Error(String(r))]);let $=n?{...i,defaultConfig:t}:{...i,defaultConfig:t,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in i?i.checkEnv!==!1:!0)return(await ht.applyEnvironmentVariables($.name||"",t,!0,$.verbose||!1))?.config??t;return t}}async function fT(i={defaultConfig:{}}){if(typeof i==="string"){let{cwd:t}=await import("process");try{return(await ht.loadConfig({name:i,cwd:t(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(n){if(n instanceof Error&&(n.name==="ConfigNotFoundError"||n.name==="ConfigLoadError"&&Eh(n)))return(await ht.applyEnvironmentVariables(i,{},!0,!1)).config;throw n}}try{return(await ht.loadConfig({...i,cwd:i.cwd||Jt.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(t){if(t instanceof Error&&(t.name==="ConfigNotFoundError"||t.name==="ConfigLoadError"&&Eh(t)))return(await ht.applyEnvironmentVariables(i.name||"",i.defaultConfig||{},i.checkEnv!==!1,i.verbose||!1)).config;throw t}}async function lT(i,t,n="replace"){let r=new af;try{let f=await r.loadFromPath(i,t,{arrayStrategy:n,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function _n(i,t,n=!1){let r=new Sf,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let w={...c};for(let[h,y]of Object.entries(c)){let u=[...$,h],e=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((E)=>E.toUpperCase()).join("")}`,`${f}_${u.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,B;for(let E of e)if(A=Jt.env[E],A!==void 0){B=E;break}if(A!==void 0&&B)if(typeof y==="boolean")w[h]=["true","1","yes"].includes(A.toLowerCase());else if(typeof y==="number"){let E=Number(A);if(!Number.isNaN(E))w[h]=E}else if(Array.isArray(y))try{w[h]=JSON.parse(A)}catch{w[h]=A.split(",").map((E)=>E.trim())}else w[h]=A;else if(y&&typeof y==="object"&&!Array.isArray(y))w[h]=l(y,u)}return w}return l(t)}function cT(i){let t=mi(Jt.cwd(),i.configDir),n=mi(Jt.cwd(),i.generatedDir),r=mi(n,"config-types.ts");if(!jc(Vw(r)))QA(Vw(r),{recursive:!0,mode:511});let f=jc(t)?PA(t).map((c)=>c.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],l=`// Generated by bunfig v${OT}
|
|
102
|
-
export type ConfigNames = ${f.length?`'${f.join("' | '")}'`:"string"}
|
|
103
|
-
`;vA(r,l,{mode:438})}function $T(i){let t=null,n=null,r=()=>{if(!n)n=qh(i).then((l)=>{return t=l,l},(l)=>{let c="defaultConfig"in i?i.defaultConfig:{};if(t=c,"verbose"in i&&i.verbose)qi.warn("Config loading failed, using defaults:",[l instanceof Error?l:Error(String(l))]);return c});return n},f="defaultConfig"in i?i.defaultConfig:{};return t=f,r(),new Proxy({},{get(l,c){if(t)return t[c];let $=f[c];return r(),$},has(l,c){return c in(t||f)},ownKeys(){return Object.keys(t||f)},getOwnPropertyDescriptor(l,c){return Object.getOwnPropertyDescriptor(t||f,c)},set(l,c,$){if(!t)t={...f};return t[c]=$,!0}})}function wT(i){let t=ch(RE.cwd(),i?.configDir||"./config");function n(){if(!mE(t))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),l=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],c=CE(t).filter((w)=>f.has(Ac(w))).map((w)=>({base:w.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:w})),$=new Map;for(let{base:w,file:h}of c){let y=Ac(h).toLowerCase(),u=$.get(w);if(!u){$.set(w,h);continue}let e=Ac(u).toLowerCase();if(l.indexOf(y)<l.indexOf(e))$.set(w,h)}return Array.from($.entries()).map(([w,h])=>({base:w,file:h})).sort((w,h)=>w.base.localeCompare(h.base))}function r(){let f=n(),l=f.map((h)=>h.base),c=l.length?l.map((h)=>`'${h}'`).join(" | "):"string",$=f.length?`{
|
|
104
|
-
${f.map((h)=>{let y=ch(t,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${y}').default`}).join(`,
|
|
105
|
-
`)}
|
|
106
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${c}
|
|
107
|
-
export type ConfigByName = ${$}
|
|
108
|
-
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
109
|
-
export type ConfigOf = Config
|
|
110
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(l)=>{return{path:l.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:r(),loader:"ts"}})}}}var Lh,en,On,gh,hT,yT,Th,lf,Nc,ui,k,uT,Yh,eT,Bh,AT,ET,Bc,TT,mh,Ch,mc,YT,BT,mT,CT,cf,xh,RT,ei,sT,UT,Rh,$f,Xc,ri,z,jT,sh,ST,Uh,aT,NT,Cc,XT,jh,Sh,FT,Rc,WT,JT,_T,IT,KT,wf,dh,zT,OT="0.15.6",ai,mf,Kn,Fc,Wc,Cf,Jc,_c,zn,Ic,Kc,mt,kh,Vh,qi,ht,Dh,bh,GT=GE(async()=>{Lh=import.meta.require,en=new Gc,On=new Mc,gh={createKey:ME,isEquivalent:HE,estimateMemoryUsage:qE},hT=ef(Sc.cwd(),"config"),yT=ef(Sc.cwd(),"src/generated"),Th=uf.env.CLARITY_LOG_DIR||pA(xE(),"logs"),lf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Th,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Nc=await dE(),ui={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,reset:"\x1B[0m"},k=ui,uT=ui.red,Yh=ui.green,eT=ui.yellow,Bh=ui.blue,AT=ui.magenta,ET=ui.cyan,Bc=ui.white,TT=ui.gray,mh=ui.bgRed,Ch=ui.bgYellow,mc=ui.bold,YT=ui.dim,BT=ui.italic,mT=ui.underline,CT=ui.reset,cf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xh={debug:"\uD83D\uDD0D",info:Bh("ℹ"),success:Yh("✓"),warning:Ch(Bc(mc(" WARN "))),error:mh(Bc(mc(" ERROR ")))},RT=new Tf("stacks"),ei=new Tf("bunfig",{showTags:!0}),sT=Bi(In.cwd(),"config"),UT=Bi(In.cwd(),"src/generated"),Rh=yf.env.CLARITY_LOG_DIR||ZA(bE(),"logs"),$f={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Xc=await QE(),ri={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},z=ri,jT=ri.red,sh=ri.green,ST=ri.yellow,Uh=ri.blue,aT=ri.magenta,NT=ri.cyan,Cc=ri.white,XT=ri.gray,jh=ri.bgRed,Sh=ri.bgYellow,FT=ri.bgGray,Rc=ri.bold,WT=ri.dim,JT=ri.italic,_T=ri.underline,IT=ri.strikethrough,KT=ri.reset,wf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},dh={debug:"\uD83D\uDD0D",info:Uh("ℹ"),success:sh("✓"),warning:Sh(Cc(Rc(" WARN "))),error:jh(Cc(Rc(" ERROR ")))},zT=new Bf("stacks"),ai=class extends Error{timestamp;context;constructor(t,n={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=n,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([n,r])=>`${n}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},mf=class extends ai{code="CONFIG_NOT_FOUND";constructor(t,n,r){let f=r?` or alias "${r}"`:"";super(`Configuration "${t}"${f} not found`,{configName:t,alias:r,searchPaths:n,searchPathCount:n.length})}},Kn=class extends ai{code="CONFIG_LOAD_ERROR";constructor(t,n,r){super(`Failed to load configuration from "${t}": ${n.message}`,{configPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Fc=class extends ai{code="CONFIG_VALIDATION_ERROR";constructor(t,n,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Wc=class extends ai{code="CONFIG_MERGE_ERROR";constructor(t,n,r,f){super(`Failed to merge configuration from "${t}" with "${n}": ${r.message}`,{sourcePath:t,targetPath:n,configName:f,originalError:r.name,originalMessage:r.message});this.cause=r}},Cf=class extends ai{code="ENV_VAR_ERROR";constructor(t,n,r,f){super(`Failed to parse environment variable "${t}" with value "${n}" as ${r}`,{envKey:t,envValue:n,expectedType:r,configName:f})}},Jc=class extends ai{code="FILE_SYSTEM_ERROR";constructor(t,n,r){super(`File system ${t} failed for "${n}": ${r.message}`,{operation:t,path:n,originalError:r.name,originalMessage:r.message});this.cause=r}},_c=class extends ai{code="TYPE_GENERATION_ERROR";constructor(t,n,r){super(`Failed to generate types from "${t}" to "${n}": ${r.message}`,{configDir:t,outputPath:n,originalError:r.name,originalMessage:r.message});this.cause=r}},zn=class extends ai{code="SCHEMA_VALIDATION_ERROR";constructor(t,n,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:n,errorCount:n.length})}},Ic=class extends ai{code="BROWSER_CONFIG_ERROR";constructor(t,n,r,f){super(`Failed to fetch configuration from "${t}": ${n} ${r}`,{endpoint:t,status:n,statusText:r,configName:f})}},Kc=class extends ai{code="PLUGIN_ERROR";constructor(t,n,r){super(`Plugin "${t}" failed during ${n}: ${r.message}`,{pluginName:t,operation:n,originalError:r.name,originalMessage:r.message});this.cause=r}},mt={configNotFound(i,t,n){return new mf(i,t,n)},configLoad(i,t,n){return new Kn(i,t,n)},configValidation(i,t,n){return new Fc(i,t,n)},configMerge(i,t,n,r){return new Wc(i,t,n,r)},envVar(i,t,n,r){return new Cf(i,t,n,r)},fileSystem(i,t,n){return new Jc(i,t,n)},typeGeneration(i,t,n){return new _c(i,t,n)},schemaValidation(i,t,n){return new zn(i,t,n)},browserConfig(i,t,n,r){return new Ic(i,t,n,r)},plugin(i,t,n){return new Kc(i,t,n)}},kh={replace:"replace",concat:"concat",smart:"smart"},Vh=/^https?:\/\//,qi=new Bf("bunfig",{showTags:!0}),ht=new xc,Dh=mi(Jt.cwd(),"config"),bh=mi(Jt.cwd(),"src/generated")});function MT(i,t={}){let n=Af.cwd();while(n.includes("storage"))n=$h(n,"..");let r=$h(n,i||"");if(t?.relative)return UE(Af.cwd(),r);return r}var HT=Af.env.CLARITY_LOG_DIR||sE(MT(),"logs"),Qh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:HT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Rf={...Qh},AU=(async()=>{try{let{loadConfig:i}=await GT().then(()=>_h),t=await i({name:"clarity",alias:"logging",defaultConfig:Qh,cwd:Af.cwd()});if(t)Object.assign(Rf,t)}catch{}return Rf})();function fi(){if(wt.env.NODE_ENV==="test"||wt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function qT(){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 i=wt.type;if(i==="renderer"||i==="worker")return!1;return!!(wt.versions&&(wt.versions.node||wt.versions.bun))}return!1}class Ph{async format(i){let t=await qT(),n=await this.getMetadata(t);return JSON.stringify({timestamp:i.timestamp.toISOString(),level:i.level,name:i.name,message:i.message,metadata:n})}async getMetadata(i){if(i){let{hostname:t}=await import("os");return{pid:un.pid,hostname:t(),environment:un.env.NODE_ENV||"development",platform:un.platform,version:un.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:un.env.NODE_ENV||un.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var ci={red:(i)=>`\x1B[31m${i}\x1B[0m`,green:(i)=>`\x1B[32m${i}\x1B[0m`,yellow:(i)=>`\x1B[33m${i}\x1B[0m`,blue:(i)=>`\x1B[34m${i}\x1B[0m`,magenta:(i)=>`\x1B[35m${i}\x1B[0m`,cyan:(i)=>`\x1B[36m${i}\x1B[0m`,white:(i)=>`\x1B[37m${i}\x1B[0m`,gray:(i)=>`\x1B[90m${i}\x1B[0m`,bgRed:(i)=>`\x1B[41m${i}\x1B[0m`,bgYellow:(i)=>`\x1B[43m${i}\x1B[0m`,bgGray:(i)=>`\x1B[100m${i}\x1B[0m`,bold:(i)=>`\x1B[1m${i}\x1B[0m`,dim:(i)=>`\x1B[2m${i}\x1B[0m`,italic:(i)=>`\x1B[3m${i}\x1B[0m`,underline:(i)=>`\x1B[4m${i}\x1B[0m`,strikethrough:(i)=>`\x1B[9m${i}\x1B[0m`,reset:"\x1B[0m"},G=ci,EU=ci.red,LT=ci.green,TU=ci.yellow,gT=ci.blue,YU=ci.magenta,BU=ci.cyan,ah=ci.white,mU=ci.gray,xT=ci.bgRed,dT=ci.bgYellow,CU=ci.bgGray,Nh=ci.bold,RU=ci.dim,sU=ci.italic,UU=ci.underline,jU=ci.strikethrough,SU=ci.reset,sc={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},kT={debug:"\uD83D\uDD0D",info:gT("ℹ"),success:LT("✓"),warning:dT(ah(Nh(" WARN "))),error:xT(ah(Nh(" ERROR ")))};class Nf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(i,t={}){this.name=i,this.config={...Rf},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??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let n={...t},r=t.timestamp!==void 0;if(r)delete n.timestamp;if(this.config={...this.config,...n,timestamp:r||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),l=this.generateKey();this.currentKeyId=f,this.keys.set(f,l),this.encryptionKeys.set(f,{key:l,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(i){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},n=this.fingersCrossedConfig.activationLevel??"error";return t[i]>=t[n]}initializeFingersCrossedConfig(i){if(!i.fingersCrossedEnabled&&i.fingersCrossed)return{...sc,...i.fingersCrossed};if(!i.fingersCrossedEnabled)return null;if(!i.fingersCrossed)return{...sc};return{...sc,...i.fingersCrossed}}normalizeOptions(i){let t={format:"json",level:"info",logDirectory:Rf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},n={...t,...Object.fromEntries(Object.entries(i).filter(([,r])=>r!==void 0))};if(!n.level||!["debug","info","success","warning","error"].includes(n.level))n.level=t.level;return n}shouldWriteToFile(){return!fi()&&this.config.writeToFile===!0}async writeToFile(i){let n=(async()=>{let f,l=0,c=3,$=1000;while(l<c)try{try{try{await XE(this.config.logDirectory,uh.F_OK|uh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await FE(this.config.logDirectory,{recursive:!0,mode:493});else if(h.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw h;else throw h}}catch(h){throw console.error("Debug: [writeToFile] Failed to create log directory:",h),h}let w=this.validateEncryptionConfig()?(await this.encrypt(i)).encrypted:ft.from(i);try{if(!vr(this.currentLogFile))await Yc(this.currentLogFile,"",{mode:420});if(f=yh(this.currentLogFile,"a",420),NE(f,w,{flag:"a"}),hh(f),f!==void 0)Tc(f),f=void 0;if((await hn(this.currentLogFile)).size===0){if(await Yc(this.currentLogFile,w,{flag:"w",mode:420}),(await hn(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let y=h;if(y.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(y.code)){if(l<c-1){let u=typeof y.message==="string"?y.message:"Unknown error";console.error(`Network error during write attempt ${l+1}/${c}:`,u);let e=$*2**l;await new Promise((A)=>setTimeout(A,e)),l++;continue}}if(y?.code&&["ENOSPC","EDQUOT"].includes(y.code))throw Error(`Disk quota exceeded or no space left on device: ${y.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",y),y}finally{if(f!==void 0)try{Tc(f)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(w){if(l===c-1){let y=w,u=typeof y.message==="string"?y.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),w}l++;let h=$*2**(l-1);await new Promise((y)=>setTimeout(y,h))}})();this.pendingOperations.push(n);let r=this.pendingOperations.length-1;try{await n}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return yn(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 yn(this.config.logDirectory,`${this.name}.log`);let i=new Date().toISOString().split("T")[0];return yn(this.config.logDirectory,`${this.name}-${i}.log`)}setupRotation(){if(fi())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let i=this.config.rotation,t;switch(i.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let n=typeof t.interval==="number"?t.interval:60,r=Math.max(n,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,n=this.generateKeyId(),r=this.generateKey();this.currentKeyId=n,this.keys.set(n,r),this.encryptionKeys.set(n,{key:r,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,$],[,w])=>w.createdAt.getTime()-$.createdAt.getTime()),l=typeof t.maxKeys==="number"?t.maxKeys:1,c=Math.max(1,l);if(f.length>c)for(let[$]of f.slice(c))this.encryptionKeys.delete($),this.keys.delete($)}generateKeyId(){return Ec(16).toString("hex")}generateKey(){return Ec(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let i=this.keys.get(this.currentKeyId);if(!i)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:i,id:this.currentKeyId}}encrypt(i){let{key:t}=this.getCurrentKey(),n=Ec(16),r=jE("aes-256-gcm",t,n),f=ft.isBuffer(i)?i:ft.from(i,"utf8"),l=r.update(f),c=r.final(),$=l.length+c.length,w=r.getAuthTag(),h=ft.allocUnsafe(16+$+16);return n.copy(h,0),l.copy(h,16),c.copy(h,16+l.length),w.copy(h,16+$),{encrypted:h,iv:n}}async compressData(i){return new Promise((t,n)=>{let r=Ah(),f=[];r.on("data",(l)=>f.push(l)),r.on("end",()=>t(ft.from(ft.concat(f)))),r.on("error",n),r.write(i),r.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let i={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...i,...t}}return i}async rotateLog(){if(fi())return;if(!this.shouldWriteToFile())return;let i=await hn(this.currentLogFile).catch(()=>null);if(!i)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&i.size>=t.maxSize){let n=this.currentLogFile,r=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Zr(this.config.logDirectory),l=f.filter((w)=>w.startsWith(this.name)&&/\.log\.\d+$/.test(w)).sort((w,h)=>{let y=Number.parseInt(w.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-y}),c=l.length>0?Number.parseInt(l[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,$=`${n}.${c}`;if(await hn(n).catch(()=>null))try{if(await eh(n,$),t.compress)try{let w=`${$}.gz`;await this.compressLogFile($,w),await or($)}catch(w){console.error("Error compressing rotated file:",w)}if(l.length===0&&!f.some((w)=>w.endsWith(".log.1")))try{let w=`${n}.1`;await Yc(w,"")}catch(w){console.error("Error creating backup file:",w)}}catch(w){console.error(`Error during rotation: ${w instanceof Error?w.message:String(w)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),l=n.replace(/\.log$/,`-${f}.log`);if(await hn(n).catch(()=>null))await eh(n,l)}if(this.currentLogFile=r,t.maxFiles){let l=(await Zr(this.config.logDirectory)).filter((c)=>c.startsWith(this.name)).sort((c,$)=>$.localeCompare(c));for(let c of l.slice(t.maxFiles))await or(yn(this.config.logDirectory,c))}}}async compressLogFile(i,t){let n=wh(i),r=aE(t),f=Ah();await _E(n,f,r)}async handleFingersCrossedBuffer(i,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(i)&&!this.isActivated){this.isActivated=!0;for(let n of this.logBuffer){let r=await this.formatter.format(n);if(this.shouldWriteToFile())await this.writeToFile(r);console.log(r)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(i){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[i]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((i)=>{if(i instanceof Promise)return i.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),vr(this.currentLogFile))try{let i=yh(this.currentLogFile,"r+");hh(i),Tc(i)}catch(i){console.error(`Error flushing file: ${i}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let i of this.pendingOperations)if(typeof i.cancel==="function")i.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(i){console.error("Error waiting for pending operations:",i)}if(!fi()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Zr(this.config.logDirectory)).filter((n)=>(n.includes("temp")||n.includes(".tmp"))&&n.includes(this.name));for(let n of t)try{await or(yn(this.config.logDirectory,n))}catch(r){console.error(`Failed to delete temp file ${n}:`,r)}}catch(i){console.error("Error cleaning up temporary files:",i)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(i){if(!i)return"";return`${this.tagFormat.prefix}${i}${this.tagFormat.suffix}`}formatFileTimestamp(i){return`[${i.toISOString()}]`}formatConsoleTimestamp(i){return this.shouldStyleConsole()?G.gray(i.toLocaleTimeString()):i.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||fi())return!1;let i=typeof I.env.NO_COLOR<"u",t=I.env.FORCE_COLOR==="0";if(i||t)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(i){let{timestamp:t,icon:n="",tag:r="",message:f,level:l,showTimestamp:c=!0}=i,$=(A)=>A.replace(this.ANSI_PATTERN,"");if(!this.fancy){let A=[];if(c)A.push(t);if(l==="warning")A.push("WARN");else if(l==="error")A.push("ERROR");else if(n)A.push(n.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(r)A.push(r.replace(/[[\]]/g,""));return A.push(f),A.join(" ")}let w=I.stdout.columns||120,h="";if(l==="warning"||l==="error")h=`${n} ${f}`;else if(l==="info"||l==="success")h=`${n} ${r} ${f}`;else h=`${n} ${r} ${G.cyan(f)}`;if(!c)return h.trim();let y=$(h).trim().length,u=$(t).length,e=Math.max(1,w-2-y-u);return`${h.trim()}${" ".repeat(e)}${t}`}formatMessage(i,t){if(t.length===1&&Array.isArray(t[0]))return i.replace(/\{(\d+)\}/g,(l,c)=>{let $=Number.parseInt(c,10);return $<t[0].length?String(t[0][$]):l});let n=/%([sdijfo%])/g,r=0,f=i.replace(n,(l,c)=>{if(c==="%")return"%";if(r>=t.length)return l;let $=t[r++];switch(c){case"s":return String($);case"d":case"i":return Number($).toString();case"j":case"o":return JSON.stringify($,null,2);default:return l}});if(r<t.length)f+=` ${t.slice(r).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`;return f}formatMarkdown(i){if(!i)return i;let t=i;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(n,r,f)=>{let l=G.underline(G.blue(r)),c=this.toAbsoluteFilePath(f);if(c&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let $=`file://${encodeURI(c)}`,w="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${$}\x1B\\${l}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${l}\x1B]8;;\x1B\\`;return l}),t=t.replace(/`([^`]+)`/g,(n,r)=>G.bgGray(r)),t=t.replace(/\*\*([^*]+)\*\*/g,(n,r)=>G.bold(r)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(n,r)=>G.italic(r)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(n,r)=>G.italic(r)),t=t.replace(/~([^~]+)~/g,(n,r)=>G.strikethrough(r)),t}supportsHyperlinks(){if(fi())return!1;let i=I.env;if(!i)return!1;if(i.TERM_PROGRAM==="iTerm.app"||i.TERM_PROGRAM==="vscode"||i.TERM_PROGRAM==="WezTerm")return!0;if(i.WT_SESSION)return!0;if(i.TERM==="xterm-kitty")return!0;let t=i.VTE_VERSION?Number.parseInt(i.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(i){try{let t=i;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let n=I.env.HOME||"";if(n)t=t.replace(/^~(?=$|\/)/,n)}if(WE(t)||t.startsWith("./")||t.startsWith("../"))t=JE(t);else return null;return vr(t)?t:null}catch{return null}}buildOutputTexts(i){let t=this.shouldStyleConsole()?this.formatMarkdown(i):i,n=i.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:n}}async log(i,t,...n){if(!this.shouldLog(i))return;let r=new Date,f=this.formatConsoleTimestamp(r),l=this.formatFileTimestamp(r),c,$;if(t instanceof Error)c=t.message,$=t.stack;else c=this.formatMessage(t,n);let{consoleText:w,fileText:h}=this.buildOutputTexts(c);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":kT[i],e=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",A;switch(i){case"debug":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:G.gray(w),level:i}),console.error(A);break;case"info":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"success":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:G.green(w),level:i}),console.error(A);break;case"warning":A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.warn(A);break;case"error":if(A=this.formatConsoleMessage({timestamp:f,icon:u,tag:e,message:w,level:i}),console.error(A),$){let B=$.split(`
|
|
111
|
-
`);for(let E of B)if(E.trim()&&!E.includes(c))console.error(this.formatConsoleMessage({timestamp:f,message:G.gray(` ${E}`),level:i,showTimestamp:!1}))}break}}else if(!fi()){if(console.error(`${l} ${this.environment}.${i.toUpperCase()}: ${c}`),$)console.error($)}let y=`${l} ${this.environment}.${i.toUpperCase()}: ${h}
|
|
112
|
-
`;if($)y+=`${$}
|
|
113
|
-
`;if(y=y.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(y)}progress(i,t=""){let n={update:($,w)=>{},finish:($)=>{},interrupt:($,w)=>{}};if(!this.enabled)return n;let r=30;if(this.activeProgressBar={total:Math.max(1,i||1),current:0,message:t||"",barLength:r,lastRenderedLine:""},this.shouldStyleConsole()&&!fi()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:($,w)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,$),this.activeProgressBar.total),w!==void 0)this.activeProgressBar.message=w;if(this.shouldStyleConsole()&&!fi()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:($)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,$)},interrupt:($,w="info")=>{if(!fi()&&I.stdout.isTTY)I.stdout.write(`
|
|
114
|
-
`);if(this[w==="warning"?"warn":w]($),this.activeProgressBar&&this.shouldStyleConsole()&&!fi()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(i){let t=performance.now();if(this.shouldStyleConsole()){let n=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",r=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:r,icon:this.options.showIcons===!1?"":G.blue("◐"),tag:n,message:`${G.cyan(i)}...`}))}return async(n)=>{if(!this.enabled)return;let r=performance.now(),f=Math.round(r-t),l=`${i} completed in ${f}ms`,c=new Date,$=this.formatConsoleTimestamp(c),h=`${this.formatFileTimestamp(c)} ${this.environment}.INFO: ${l}`;if(n)h+=` ${JSON.stringify(n)}`;if(h+=`
|
|
115
|
-
`,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let y=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:$,icon:this.options.showIcons===!1?"":G.green("✓"),tag:y,message:`${l}${n?` ${JSON.stringify(n)}`:""}`}))}else if(!fi())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(i,...t){await this.log("debug",i,...t)}async info(i,...t){await this.log("info",i,...t)}async success(i,...t){await this.log("success",i,...t)}async warn(i,...t){await this.log("warning",i,...t)}async error(i,...t){await this.log("error",i,...t)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let i=this.config.rotation,{encrypt:t}=i;return!!t}async only(i){if(!this.enabled)return;return await i()}isEnabled(){return this.enabled}setEnabled(i){this.enabled=i}extend(i){let t=`${this.name}:${i}`,n=new Nf(t,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(n),n}createReadStream(){if(fi())throw Error("createReadStream is not supported in browser environments");if(!vr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wh(this.currentLogFile,{encoding:"utf8"})}async decrypt(i){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let t=this.config.rotation;if(!t.encrypt||typeof t.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let n=this.keys.get(this.currentKeyId);try{let r=ft.isBuffer(i)?i:ft.from(i,"base64"),f=r.subarray(0,16),l=r.subarray(r.length-16),c=r.subarray(16,r.length-16),$=SE("aes-256-gcm",n,f);$.setAuthTag(l);let w=$.update(c),h=$.final(),y=w.length+h.length,u=ft.allocUnsafe(y);return w.copy(u,0),h.copy(u,w.length),u.toString("utf8")}catch(r){throw Error(`Decryption failed: ${r instanceof Error?r.message:String(r)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return fi()}isServerMode(){return!fi()}setTestEncryptionKey(i,t){this.currentKeyId=i,this.keys.set(i,t)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(i){if(!this.enabled)return;let t=new Date,n=this.formatConsoleTimestamp(t),r=this.formatFileTimestamp(t),{consoleText:f,fileText:l}=this.buildOutputTexts(i);if(this.shouldStyleConsole()){let $=f.split(`
|
|
116
|
-
`),w=Math.max(...$.map((e)=>e.length))+2,h=`┌${"─".repeat(w)}┐`,y=`└${"─".repeat(w)}┘`,u=$.map((e)=>{return this.formatConsoleMessage({timestamp:n,message:G.cyan(e),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:n,message:G.cyan(h),showTimestamp:!1})),u.forEach((e)=>console.error(e)),console.error(this.formatConsoleMessage({timestamp:n,message:G.cyan(y),showTimestamp:!1}))}else if(!fi())console.error(`${r} ${this.environment}.INFO: [BOX] ${l}`);let c=`${r} ${this.environment}.INFO: [BOX] ${l}
|
|
117
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}async prompt(i){if(fi())return Promise.resolve(!0);return new Promise((t)=>{console.error(`${G.cyan("?")} ${i} (y/n) `);let n=(r)=>{let f=r.toString().trim().toLowerCase();I.stdin.removeListener("data",n);try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!1)}catch{}I.stdin.pause(),console.error(""),t(f==="y"||f==="yes")};try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!0)}catch{}I.stdin.resume(),I.stdin.once("data",n)})}setFancy(i){this.fancy=i}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(i,...t){if(!this.enabled)return;let n=i;if(t&&t.length>0){let w=/%([sdijfo%])/g,h=0;if(n=i.replace(w,(y,u)=>{if(u==="%")return"%";if(h>=t.length)return y;let e=t[h++];switch(u){case"s":return String(e);case"d":case"i":return Number(e).toString();case"j":case"o":return JSON.stringify(e,null,2);default:return y}}),h<t.length)n+=` ${t.slice(h).map((y)=>typeof y==="object"?JSON.stringify(y,null,2):String(y)).join(" ")}`}let{consoleText:r,fileText:f}=this.buildOutputTexts(n);if(this.shouldStyleConsole()){let w=this.options.showTags!==!1&&this.name?G.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${G.blue("◐")} `;console.error(`${h}${w} ${G.cyan(r)}`)}let $=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${f}
|
|
118
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile($)}renderProgressBar(i,t=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let n=Math.min(100,Math.max(0,Math.round(i.current/i.total*100))),r=Math.round(i.barLength*n/100),f=i.barLength-r,l=G.green("━".repeat(r)),c=G.gray("━".repeat(f)),$=`[${l}${c}]`,w=`${n}%`.padStart(4),h=i.message?` ${i.message}`:"",y=this.options.showIcons===!1?"":t||n===100?G.green("✓"):G.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${G.gray(this.formatTag(this.name))}`:"",e=`\r${y}${u} ${$} ${w}${h}`,A=I.stdout.columns||80,B=" ".repeat(Math.max(0,A-e.replace(this.ANSI_PATTERN,"").length));if(i.lastRenderedLine=`${e}${B}`,I.stdout.write(i.lastRenderedLine),t)I.stdout.write(`
|
|
119
|
-
`)}finishProgressBar(i,t){if(!this.enabled||!this.fancy||fi()||!I.stdout.isTTY){this.activeProgressBar=null;return}if(i.current<i.total)i.current=i.total;if(t)i.message=t;this.renderProgressBar(i,!0),this.activeProgressBar=null}async clear(i={}){if(fi()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let t=await Zr(this.config.logDirectory),n=[];for(let r of t){if(!(i.name?new RegExp(i.name.replace("*",".*")).test(r):r.startsWith(this.name))||!r.endsWith(".log"))continue;let l=yn(this.config.logDirectory,r);if(i.before)try{if((await hn(l)).mtime>=i.before)continue}catch(c){console.error(`Failed to get stats for file ${l}:`,c);continue}n.push(l)}if(n.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${n.length} log file(s)...`);for(let r of n)try{await or(r),console.warn(`Deleted log file: ${r}`)}catch(f){console.error(`Failed to delete log file ${r}:`,f)}console.warn("Log clearing process finished.")}catch(t){console.error("Error during log clearing process:",t)}}}var aU=new Nf("stacks");class Li extends Error{timestamp;context;constructor(i,t={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=t,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([t,n])=>`${t}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}}class vh extends Li{code="CONFIG_NOT_FOUND";constructor(i,t,n){let r=n===void 0?[]:Array.isArray(n)?n.filter(Boolean):[n],f="";if(r.length===1)f=` or alias "${r[0]}"`;else if(r.length>1)f=` or aliases ${r.map((l)=>`"${l}"`).join(", ")}`;super(`Configuration "${i}"${f} not found`,{configName:i,alias:n,searchPaths:t,searchPathCount:t.length})}}class sf extends Li{code="CONFIG_LOAD_ERROR";constructor(i,t,n){super(`Failed to load configuration from "${i}": ${t.message}`,{configPath:i,configName:n,originalError:t.name,originalMessage:t.message});this.cause=t}}class Zh extends Li{code="CONFIG_VALIDATION_ERROR";constructor(i,t,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class oh extends Li{code="CONFIG_MERGE_ERROR";constructor(i,t,n,r){super(`Failed to merge configuration from "${i}" with "${t}": ${n.message}`,{sourcePath:i,targetPath:t,configName:r,originalError:n.name,originalMessage:n.message});this.cause=n}}class dc extends Li{code="ENV_VAR_ERROR";constructor(i,t,n,r){super(`Failed to parse environment variable "${i}" with value "${t}" as ${n}`,{envKey:i,envValue:t,expectedType:n,configName:r})}}class ph extends Li{code="FILE_SYSTEM_ERROR";constructor(i,t,n){super(`File system ${i} failed for "${t}": ${n.message}`,{operation:i,path:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class iy extends Li{code="TYPE_GENERATION_ERROR";constructor(i,t,n){super(`Failed to generate types from "${i}" to "${t}": ${n.message}`,{configDir:i,outputPath:t,originalError:n.name,originalMessage:n.message});this.cause=n}}class Uf extends Li{code="SCHEMA_VALIDATION_ERROR";constructor(i,t,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:t,errorCount:t.length})}}class ty extends Li{code="BROWSER_CONFIG_ERROR";constructor(i,t,n,r){super(`Failed to fetch configuration from "${i}": ${t} ${n}`,{endpoint:i,status:t,statusText:n,configName:r})}}class ny extends Li{code="PLUGIN_ERROR";constructor(i,t,n){super(`Plugin "${i}" failed during ${t}: ${n.message}`,{pluginName:i,operation:t,originalError:n.name,originalMessage:n.message});this.cause=n}}var An={configNotFound(i,t,n){return new vh(i,t,n)},configLoad(i,t,n){return new sf(i,t,n)},configValidation(i,t,n){return new Zh(i,t,n)},configMerge(i,t,n,r){return new oh(i,t,n,r)},envVar(i,t,n,r){return new dc(i,t,n,r)},fileSystem(i,t,n){return new ph(i,t,n)},typeGeneration(i,t,n){return new iy(i,t,n)},schemaValidation(i,t,n){return new Uf(i,t,n)},browserConfig(i,t,n,r){return new ty(i,t,n,r)},plugin(i,t,n){return new ny(i,t,n)}};async function VT(i,t={}){let{maxRetries:n=3,retryDelay:r=1000,isRetryable:f=()=>!0,fallback:l}=t,c=Error("Unknown error occurred");for(let $=0;$<=n;$++)try{return await i()}catch(w){if(c=w instanceof Error?w:Error(String(w)),$===n||!f(c))break;if(r>0)await new Promise((h)=>setTimeout(h,r))}if(l!==void 0)return l;throw c instanceof Error?c:Error(`Unknown error: ${String(c)}`)}class kc{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(i,t)=>t==="boolean"||["true","false","1","0","yes","no"].includes(i.toLowerCase()),parse:(i)=>{let t=i.toLowerCase();return["true","1","yes"].includes(t)}},{name:"number",canParse:(i,t)=>t==="number"||!Number.isNaN(Number(i))&&!Number.isNaN(Number.parseFloat(i)),parse:(i)=>{let t=Number(i);if(Number.isNaN(t))throw TypeError(`Cannot parse "${i}" as number`);return t}},{name:"array",canParse:(i,t)=>t==="array"||i.startsWith("[")||i.includes(","),parse:(i)=>{try{let t=JSON.parse(i);if(Array.isArray(t))return t}catch{}return i.split(",").map((t)=>t.trim())}},{name:"json",canParse:(i,t)=>t==="object"||(i.startsWith("{")&&i.endsWith("}")||i.startsWith("[")&&i.endsWith("]")),parse:(i)=>{try{return JSON.parse(i)}catch(t){throw Error(`Cannot parse "${i}" as JSON: ${t}`)}}}]}async applyEnvironmentVariables(i,t,n={}){let{prefix:r,useCamelCase:f=!0,useBackwardCompatibility:l=!0,customParsers:c={},verbose:$=!1,trackPerformance:w=!0}=n,h=async()=>{if(!i)return{config:t,source:{type:"environment",priority:50,timestamp:new Date}};let y=r||this.generateEnvPrefix(i),u={...t};return this.processObject(u,[],y,{useCamelCase:f,useBackwardCompatibility:l,customParsers:c,verbose:$,configName:i}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(w)return Oc.track("applyEnvironmentVariables",h,{configName:i});return h()}generateEnvPrefix(i){return i.toUpperCase().replace(/-/g,"_")}formatEnvKey(i,t){if(!t)return i.toUpperCase();return i.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(i,t,n,r){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=c.map((y)=>this.formatEnvKey(y,r.useCamelCase)),w=`${n}_${$.join("_")}`,h=r.useBackwardCompatibility?`${n}_${c.map((y)=>y.toUpperCase()).join("_")}`:null;if(r.verbose);if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.processObject(l,c,n,r);else{let y=tf.env[w]||(h?tf.env[h]:void 0);if(y!==void 0){if(r.verbose){let u=tf.env[w]?w:h}try{i[f]=this.parseEnvironmentValue(y,typeof l,w,r.customParsers,r.configName)}catch(u){if(u instanceof dc)throw u;throw An.envVar(w,y,typeof l,r.configName)}}}}}parseEnvironmentValue(i,t,n,r,f){for(let[l,c]of Object.entries(r))try{return c(i)}catch{continue}for(let l of this.defaultParsers)if(l.canParse(i,t))try{return l.parse(i)}catch{throw An.envVar(n,i,`${t} (via ${l.name} parser)`,f)}return i}getEnvironmentVariables(i){let t={},n=i.toUpperCase();for(let[r,f]of Object.entries(tf.env))if(r.startsWith(n)&&f!==void 0)t[r]=f;return t}validateEnvironmentVariable(i,t,n){let r=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(i))r.push(`Environment variable key "${i}" should only contain uppercase letters, numbers, and underscores`);if(n)try{this.parseEnvironmentValue(i,t,n,{})}catch(f){r.push(`Cannot parse value "${t}" as ${n}: ${f}`)}return{isValid:r.length===0,errors:r}}generateEnvVarDocs(i,t,n={}){let{prefix:r,format:f="text"}=n,l=r||this.generateEnvPrefix(i),c=[];switch(this.extractEnvVarInfo(t,[],l,c),f){case"markdown":return this.formatAsMarkdown(c,i);case"json":return JSON.stringify(c,null,2);default:return this.formatAsText(c,i)}}extractEnvVarInfo(i,t,n,r){for(let[f,l]of Object.entries(i)){let c=[...t,f],$=`${n}_${c.map((w)=>this.formatEnvKey(w,!0)).join("_")}`;if(typeof l==="object"&&l!==null&&!Array.isArray(l))this.extractEnvVarInfo(l,c,n,r);else r.push({key:$,type:Array.isArray(l)?"array":typeof l,description:`Configuration for ${c.join(".")}`,example:this.generateExample(l)})}}generateExample(i){if(Array.isArray(i))return JSON.stringify(i);if(typeof i==="object"&&i!==null)return JSON.stringify(i);return String(i)}formatAsText(i,t){let n=`Environment Variables for ${t}:
|
|
120
|
-
|
|
121
|
-
`;for(let r of i)n+=`${r.key}
|
|
122
|
-
`,n+=` Type: ${r.type}
|
|
123
|
-
`,n+=` Description: ${r.description}
|
|
124
|
-
`,n+=` Example: ${r.example}
|
|
125
|
-
|
|
126
|
-
`;return n}formatAsMarkdown(i,t){let n=`# Environment Variables for ${t}
|
|
127
|
-
|
|
128
|
-
`;n+=`| Variable | Type | Description | Example |
|
|
129
|
-
`,n+=`|----------|------|-------------|----------|
|
|
130
|
-
`;for(let r of i)n+=`| \`${r.key}\` | ${r.type} | ${r.description} | \`${r.example}\` |
|
|
131
|
-
`;return n}}function DT(i,t,n={}){return ry(i,t,n,new WeakMap)}function ry(i,t,n,r){let{arrayMergeMode:f="replace",skipNullish:l=!1,customMerger:c}=n;if(t===null||t===void 0)return l?i:t;if(c){let $=c(i,t);if($!==void 0)return $}if(Array.isArray(t)||Array.isArray(i))return fy(i,t,f,r);if(!Ii(t)||!Ii(i))return t;return vT(i,t,n,r)}function fy(i,t,n,r){if(Array.isArray(t)&&!Array.isArray(i))return t;if(Array.isArray(i)&&!Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(i))switch(n){case"replace":return t;case"concat":return bT(i,t);case"smart":return QT(i,t,r);default:return t}return t}function bT(i,t){let n=[...t];for(let r of i)if(!n.some((f)=>zc(f,r)))n.push(r);return n}function QT(i,t,n){if(t.length===0)return i;if(i.length===0)return t;if(Ii(t[0])&&Ii(i[0]))return PT(i,t,n);if(t.every((r)=>typeof r==="string")&&i.every((r)=>typeof r==="string")){let r=[...t];for(let f of i)if(!r.includes(f))r.push(f);return r}return t}function PT(i,t,n){let r=[...t];for(let f of i){if(!Ii(f)){r.push(f);continue}let l=["id","name","key","path","type"],c=!1;for(let $ of l)if($ in f){if(r.find((h)=>Ii(h)&&($ in h)&&h[$]===f[$])){c=!0;break}}if(!c)r.push(f)}return r}function vT(i,t,n,r){let f=t;if(Ii(f)&&r.has(f))return r.get(f);let l={...i};if(Ii(f))r.set(f,l);for(let c in f){if(!Object.prototype.hasOwnProperty.call(f,c))continue;let $=f[c],w=l[c];if(n.skipNullish&&($===null||$===void 0))continue;if($===null||$===void 0){l[c]=$;continue}if(Ii($)&&Ii(w))l[c]=ry(w,$,n,r);else if(Array.isArray($)||Array.isArray(w))l[c]=fy(w,$,n.arrayMergeMode||"smart",r);else l[c]=$}return l}function ly(i,t,n="replace"){return DT(i,t,{arrayMergeMode:n==="replace"?"replace":"smart",skipNullish:!0})}function zc(i,t){if(i===t)return!0;if(Array.isArray(i)&&Array.isArray(t)){if(i.length!==t.length)return!1;for(let n=0;n<i.length;n++)if(!zc(i[n],t[n]))return!1;return!0}if(Ii(i)&&Ii(t)){let n=Object.keys(i),r=Object.keys(t);if(n.length!==r.length)return!1;for(let f of n){if(!Object.prototype.hasOwnProperty.call(t,f))return!1;if(!zc(i[f],t[f]))return!1}return!0}return!1}function Ii(i){return Boolean(i&&typeof i==="object"&&!Array.isArray(i))}class cy{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(i,t,n={}){let{arrayStrategy:r="replace",useCache:f=!0,cacheTtl:l,trackPerformance:c=!0,verbose:$=!1}=n;if(f){let h=hf.getWithFileCheck("file",i);if(h){if($)console.log(`Configuration loaded from cache: ${i}`);return h}}let w=async()=>{if(!nf(i))return null;try{let h=`?t=${Date.now()}`,y=await import(i+h),u=y.default||y,e="default"in y,A=Object.keys(y).length>0;if(!e&&!A)throw new sf(i,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new sf(i,Error("Configuration must export a valid object"),"unknown");let Y={config:ly(t,u,r),source:{type:"file",path:i,priority:100,timestamp:new Date}};if(f)hf.setWithFileCheck("file",Y,i,l);return Y}catch(h){throw h instanceof Error?An.configLoad(i,h):An.configLoad(i,Error(String(h)))}};if(c)return Oc.track("loadFromPath",w,{path:i});return w()}async tryLoadFromPaths(i,t,n={}){for(let r of i)try{let f=await this.loadFromPath(r,t,n);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(n.verbose)console.warn(`Failed to load config from ${r}:`,f)}return null}generateConfigPaths(i,t,n){let r=this.generateNamePatterns(i,n),f=[];for(let l of r)for(let c of this.extensions)f.push(Uc(t,`${l}${c}`));return f}generateNamePatterns(i,t){let n=[];if(n.push("config",".config"),i)n.push(i,`.${i}.config`,`${i}.config`,`.${i}`);let r=t===void 0?[]:Array.isArray(t)?t:[t];for(let l of r){if(!l)continue;if(n.push(l,`.${l}.config`,`${l}.config`,`.${l}`),i)n.push(`${i}.${l}.config`,`.${i}.${l}.config`)}let f=new Set;return n.filter((l)=>{if(!l||f.has(l))return!1;return f.add(l),!0})}checkFileAccess(i){return VT(async()=>{return nf(i)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(i,t,n){let r=[];if(!nf(i))return r;if(t||n){let f=this.generateNamePatterns(t||"",n);for(let l of f)for(let c of this.extensions){let $=Uc(i,`${l}${c}`);if(await this.checkFileAccess($))r.push($)}}else try{let{readdirSync:f}=await import("fs"),l=f(i);for(let c of l)if(this.looksLikeConfigFile(c)){let $=Uc(i,c);if(await this.checkFileAccess($))r.push($)}}catch{return[]}return r}looksLikeConfigFile(i){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((n)=>n.test(i))}async validateConfigFile(i){let t=[];try{if(!nf(i))return t.push("Configuration file does not exist"),t;let n=await import(i),r=n.default||n;if(r===void 0)t.push("Configuration file must export a default value or named exports");else if(typeof r!=="object"||r===null)t.push("Configuration must be an object");else if(Array.isArray(r))t.push("Configuration cannot be an array at the root level");if(i.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),l=f(i,"utf8");JSON.parse(l)}catch(f){t.push(`Invalid JSON syntax: ${f}`)}}catch(n){t.push(`Failed to load configuration file: ${n}`)}return t}async getFileModificationTime(i){try{let{statSync:t}=await import("fs");return t(i).mtime}catch{return null}}async preloadConfigurations(i,t={}){let n=new Map;return await Promise.allSettled(i.map(async(r)=>{try{let f=await this.loadFromPath(r,{},t);if(f)n.set(r,f.config)}catch(f){if(t.verbose)console.warn(`Failed to preload ${r}:`,f)}})),n}}var oT=/^https?:\/\//;class $y{async validateConfiguration(i,t,n={}){let{stopOnFirstError:r=!1,validateRequired:f=!0,validateTypes:l=!0,customRules:c=[],trackPerformance:$=!0,verbose:w=!1}=n,h=async()=>{let y=[],u=[],e={stopOnFirstError:r,validateRequired:f,validateTypes:l,customRules:c,trackPerformance:$,verbose:w};try{if(typeof t==="string")return await this.validateWithSchemaFile(i,t,e);else if(Array.isArray(t))return this.validateWithRules(i,[...t,...c],e);else return this.validateWithJSONSchema(i,t,e)}catch(A){return y.push({path:"",message:`Validation failed: ${A}`,rule:"system"}),{isValid:!1,errors:y,warnings:u}}};if($)return await Oc.track("validateConfiguration",h);return h()}async validateWithSchemaFile(i,t,n){try{if(!ZT(t))throw new Uf(t,[{path:"",message:"Schema file does not exist"}]);let r=await import(t),f=r.default||r;if(Array.isArray(f))return this.validateWithRules(i,f,n);else return this.validateWithJSONSchema(i,f,n)}catch(r){throw new Uf(t,[{path:"",message:`Failed to load schema: ${r}`}])}}validateWithJSONSchema(i,t,n){let r=[],f=[];return this.validateObjectAgainstSchema(i,t,"",r,f,n),{isValid:r.length===0,errors:r,warnings:f}}validateObjectAgainstSchema(i,t,n,r,f,l){if(l.validateTypes&&t.type){let c=Array.isArray(i)?"array":typeof i,$=Array.isArray(t.type)?t.type:[t.type];if(!$.includes(c)){if(r.push({path:n,message:`Expected type ${$.join(" or ")}, got ${c}`,expected:$.join(" or "),actual:c,rule:"type"}),l.stopOnFirstError)return}}if(t.enum&&!t.enum.includes(i)){if(r.push({path:n,message:`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"}),l.stopOnFirstError)return}if(typeof i==="string"){if(t.minLength!==void 0&&i.length<t.minLength)r.push({path:n,message:`String length must be at least ${t.minLength}`,expected:`>= ${t.minLength}`,actual:i.length,rule:"minLength"});if(t.maxLength!==void 0&&i.length>t.maxLength)r.push({path:n,message:`String length must not exceed ${t.maxLength}`,expected:`<= ${t.maxLength}`,actual:i.length,rule:"maxLength"});if(t.pattern){if(!new RegExp(t.pattern).test(i))r.push({path:n,message:`String does not match pattern ${t.pattern}`,expected:t.pattern,actual:i,rule:"pattern"})}}if(typeof i==="number"){if(t.minimum!==void 0&&i<t.minimum)r.push({path:n,message:`Value must be at least ${t.minimum}`,expected:`>= ${t.minimum}`,actual:i,rule:"minimum"});if(t.maximum!==void 0&&i>t.maximum)r.push({path:n,message:`Value must not exceed ${t.maximum}`,expected:`<= ${t.maximum}`,actual:i,rule:"maximum"})}if(Array.isArray(i)&&t.items)for(let c=0;c<i.length;c++){let $=n?`${n}[${c}]`:`[${c}]`;if(this.validateObjectAgainstSchema(i[c],t.items,$,r,f,l),l.stopOnFirstError&&r.length>0)return}if(i&&typeof i==="object"&&!Array.isArray(i)){let c=i;if(l.validateRequired&&t.required){for(let $ of t.required)if(!($ in c)){if(r.push({path:n?`${n}.${$}`:$,message:`Missing required property '${$}'`,expected:"required",rule:"required"}),l.stopOnFirstError)return}}if(t.properties){for(let[$,w]of Object.entries(t.properties))if($ in c){let h=n?`${n}.${$}`:$;if(this.validateObjectAgainstSchema(c[$],w,h,r,f,l),l.stopOnFirstError&&r.length>0)return}}if(t.additionalProperties===!1){let $=new Set(Object.keys(t.properties||{}));for(let w of Object.keys(c))if(!$.has(w))f.push({path:n?`${n}.${w}`:w,message:`Additional property '${w}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(i,t,n){let r=[],f=[];for(let l of t)try{let c=this.getValueByPath(i,l.path),$=this.validateWithRule(c,l,l.path);if(r.push(...$),n.stopOnFirstError&&r.length>0)break}catch(c){r.push({path:l.path,message:`Rule validation failed: ${c}`,rule:"system"})}return{isValid:r.length===0,errors:r,warnings:f}}validateWithRule(i,t,n){let r=[];if(t.required&&(i===void 0||i===null))return r.push({path:n,message:t.message||`Property '${n}' is required`,expected:"required",rule:"required"}),r;if(i===void 0||i===null)return r;if(t.type){let f=Array.isArray(i)?"array":typeof i;if(f!==t.type)r.push({path:n,message:t.message||`Expected type ${t.type}, got ${f}`,expected:t.type,actual:f,rule:"type"})}if(t.min!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f<t.min)r.push({path:n,message:t.message||`Value must be at least ${t.min}`,expected:`>= ${t.min}`,actual:f,rule:"min"})}if(t.max!==void 0){let f=Array.isArray(i)?i.length:typeof i==="string"?i.length:typeof i==="number"?i:0;if(f>t.max)r.push({path:n,message:t.message||`Value must not exceed ${t.max}`,expected:`<= ${t.max}`,actual:f,rule:"max"})}if(t.pattern&&typeof i==="string"){if(!t.pattern.test(i))r.push({path:n,message:t.message||`Value does not match pattern ${t.pattern}`,expected:t.pattern.toString(),actual:i,rule:"pattern"})}if(t.enum&&!t.enum.includes(i))r.push({path:n,message:t.message||`Value must be one of: ${t.enum.join(", ")}`,expected:t.enum.join(", "),actual:i,rule:"enum"});if(t.validator){let f=t.validator(i);if(f)r.push({path:n,message:t.message||f,rule:"custom"})}return r}getValueByPath(i,t){if(!t)return i;let n=t.split("."),r=i;for(let f of n)if(r&&typeof r==="object"&&f in r)r=r[f];else return;return r}generateRulesFromInterface(i){let t=[],n=i.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let r of n){let[,f,l,c]=r;t.push({path:f,required:!l,type:this.mapTypeScriptType(c)})}return t}mapTypeScriptType(i){switch(i.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:oT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var lt=new Nf("bunfig",{showTags:!0});function pT(i){if(!i)return"";let t=Array.isArray(i)?i.filter(Boolean):[i];if(t.length===0)return"";if(t.length===1)return` or alias "${t[0]}"`;return` or aliases ${t.map((n)=>`"${n}"`).join(", ")}`}class wy{fileLoader=new cy;envProcessor=new kc;validator=new $y;async loadConfig(i){let t=Date.now(),{cache:n,performance:r,schema:f,validate:l,...c}=i;try{if(n?.enabled){let w=this.checkCache(c.name||"",c);if(w)return w}let $;try{$=await this.loadConfigurationStrategies(c,!0,n)}catch(w){let h=c.__strictErrorHandling;if(w instanceof Error&&w.name==="ConfigNotFoundError"){if(h)throw w;$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`No configuration file found for "${c.name||"config"}", using defaults with environment variables`]}}else if(w instanceof Error&&w.name==="ConfigLoadError"){let y=w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"),u=!y&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")||w.message.includes("errors building")),e=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");if(h&&(e||y))throw w;if(u&&(!h||!e))$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)$={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading error, using defaults: ${w.message}`]};else throw w}else $={...await this.applyEnvironmentVariables(c.name||"",c.defaultConfig,c.checkEnv!==!1,c.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${w instanceof Error?w.message:String(w)}`]}}if(f||l)await this.validateConfiguration($.config,f,l,c.name);if(n?.enabled&&$)this.cacheResult(c.name||"",$,n,c);if(r?.enabled){let w={operation:"loadConfig",duration:Date.now()-t,configName:c.name,timestamp:new Date};if(r.onMetrics)r.onMetrics(w);if(r.slowThreshold&&w.duration>r.slowThreshold)lt.warn(`Slow configuration loading detected: ${w.duration}ms for ${c.name}`);$.metrics=w}return $}catch($){if($ instanceof Error&&$.name==="ConfigNotFoundError")throw $;let w=Date.now()-t;throw lt.error(`Configuration loading failed after ${w}ms:`,[$ instanceof Error?$:Error(String($))]),$}}async loadConfigurationStrategies(i,t=!1,n){let{name:r="",alias:f,cwd:l,configDir:c,defaultConfig:$,checkEnv:w=!0,arrayStrategy:h="replace",verbose:y=!1}=i,u=l||jf.cwd(),e=[],A=await this.loadLocalConfiguration(r,f,u,c,$,h,y,w,n);if(A)return e.push(...this.getLocalSearchPaths(r,f,u,c)),this.finalizeResult(A,e,w,r,y);let B=await this.loadHomeConfiguration(r,f,$,h,y,w);if(B)return e.push(...this.getHomeSearchPaths(r,f)),this.finalizeResult(B,e,w,r,y);let E=await this.loadPackageJsonConfiguration(r,f,u,$,h,y,w);if(E)return e.push(Ji(u,"package.json")),this.finalizeResult(E,e,w,r,y);if(e.push(...this.getAllSearchPaths(r,f,u,c)),t)throw An.configNotFound(r,e,f);return{...await this.applyEnvironmentVariables(r,$,w,y),warnings:[`No configuration file found for "${r}"${pT(f)}, using defaults with environment variables`]}}async loadLocalConfiguration(i,t,n,r,f,l,c,$,w){let h=$?rf(i,f,c):f,y=this.getLocalDirectories(n,r);for(let u of y){if(c)lt.info(`Searching for configuration in: ${u}`);let e=this.fileLoader.generateConfigPaths(i,u,t),A=await this.fileLoader.tryLoadFromPaths(e,h,{arrayStrategy:l,verbose:c,cacheTtl:w?.ttl,useCache:!w?.ttl||w.ttl>100});if(A){if(c)lt.success(`Configuration loaded from: ${A.source.path}`);return A}}return null}async loadHomeConfiguration(i,t,n,r,f,l){if(!i)return null;let c=l?rf(i,n,f):n,$=[Ji(tn(),".config",i),Ji(tn(),".config"),tn()];for(let w of $){if(f)lt.info(`Checking home directory: ${w}`);let h=this.fileLoader.generateConfigPaths(i,w,t),y=await this.fileLoader.tryLoadFromPaths(h,c,{arrayStrategy:r,verbose:f});if(y){if(f)lt.success(`Configuration loaded from home directory: ${y.source.path}`);return y}}return null}async loadPackageJsonConfiguration(i,t,n,r,f,l,c){let $=c?rf(i,r,l):r;try{let w=Ji(n,"package.json");if(!DA(w))return null;let h={};try{h=JSON.parse(bA(w,"utf8"))}catch(e){if(l)lt.warn("Failed to parse package.json:",[e instanceof Error?e:Error(String(e))]);return null}let y=h[i],u=i;if(!y&&t){let e=Array.isArray(t)?t:[t];for(let A of e){if(!A)continue;if(h[A]){y=h[A],u=A;break}}}if(y&&typeof y==="object"&&!Array.isArray(y)){if(l)lt.success(`Configuration loaded from package.json: ${u}`);return{config:ly($,y,f),source:{type:"package.json",path:w,priority:30,timestamp:new Date}}}}catch(w){if(l)lt.warn("Failed to load package.json:",[w instanceof Error?w:Error(String(w))])}return null}async applyEnvironmentVariables(i,t,n,r){if(!n||!i||typeof t!=="object"||t===null||Array.isArray(t))return{config:t,source:{type:"default",priority:10,timestamp:new Date}};return{config:rf(i,t,r),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(i,t,n,r,f){return{config:i.config,source:i.source,path:i.source.path}}async validateConfiguration(i,t,n,r){let f=[];if(n){let l=n(i);if(l)f.push(...l)}if(t){let l=await this.validator.validateConfiguration(i,t);if(!l.isValid)f.push(...l.errors.map((c)=>c.path?`${c.path}: ${c.message}`:c.message))}if(f.length>0)throw An.configValidation(r||"unknown",f,r)}checkCache(i,t){let n=this.generateCacheKey(i,t);return hf.get(n)||null}cacheResult(i,t,n,r){let f=this.generateCacheKey(i,r);hf.set(f,t,void 0,n.ttl)}generateCacheKey(i,t){let n=[i];if(t.alias){let r=Array.isArray(t.alias)?t.alias.join(","):t.alias;n.push(`alias:${r}`)}if(t.cwd)n.push(`cwd:${t.cwd}`);if(t.configDir)n.push(`configDir:${t.configDir}`);if("checkEnv"in t)n.push(`checkEnv:${t.checkEnv}`);return n.join("|")}getLocalDirectories(i,t){return Array.from(new Set([i,Ji(i,"config"),Ji(i,".config"),t?Ji(i,t):void 0].filter(Boolean)))}getAllSearchPaths(i,t,n,r){let f=[];return f.push(...this.getLocalSearchPaths(i,t,n,r)),f.push(...this.getHomeSearchPaths(i,t)),f.push(Ji(n,"package.json")),f}getLocalSearchPaths(i,t,n,r){let f=this.getLocalDirectories(n,r),l=[];for(let c of f)l.push(...this.fileLoader.generateConfigPaths(i,c,t));return l}getHomeSearchPaths(i,t){if(!i)return[];let n=[Ji(tn(),".config",i),Ji(tn(),".config"),tn()],r=[];for(let f of n)r.push(...this.fileLoader.generateConfigPaths(i,f,t));return r}async loadConfigWithResult(i){return this.loadConfig(i)}}var JU=new wy;function rf(i,t,n=!1){let r=new kc,f=i.toUpperCase().replace(/[^A-Z0-9]/g,"_");function l(c,$=[]){let w={...c};for(let[h,y]of Object.entries(c)){let u=[...$,h],e=[`${f}_${u.join("_").toUpperCase()}`,`${f}_${u.map((E)=>E.toUpperCase()).join("")}`,`${f}_${u.map((E)=>E.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],A,B;for(let E of e)if(A=jf.env[E],A!==void 0){B=E;break}if(A!==void 0&&B)if(typeof y==="boolean")w[h]=["true","1","yes"].includes(A.toLowerCase());else if(typeof y==="number"){let E=Number(A);if(!Number.isNaN(E))w[h]=E}else if(Array.isArray(y))try{w[h]=JSON.parse(A)}catch{w[h]=A.split(",").map((E)=>E.trim())}else w[h]=A;else if(y&&typeof y==="object"&&!Array.isArray(y))w[h]=l(y,u)}return w}return l(t)}var _U=Ji(jf.cwd(),"config"),IU=Ji(jf.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",iY={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Dc(Vc(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Dc(Vc(),".stacks","ssl","stacks.localhost.crt"),keyPath:Dc(Vc(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var hy=iY;import{execSync as Mn}from"node:child_process";import{homedir as fY}from"node:os";import{join as lY}from"node:path";function tY(i){return(i.includes("=")?i.split("=").pop():i).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function _t(i){try{return xr(i)}catch{return null}}function bc(i){try{return ic(i)||null}catch{return null}}function Qc(i,t){try{return t.every((n)=>nc(i,n))}catch{return!1}}function nY(i,t,n=443){return tc(i,t,n)}function rY(i){let t=[];for(let n of i.split(`
|
|
132
|
-
`)){let r=n.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(r)t.push(r[1].toUpperCase())}return t}var Ct="-d -r trustRoot -p ssl -p basic",It="/Library/Keychains/System.keychain",Pc="rpx.localhost";function Hn(){return lY(fY(),"Library/Keychains/login.keychain-db")}function vc(){return[It,Hn()]}function yy(i,t=Pc){let n=Mn(`security find-certificate -a -c "${t}" -Z "${i}" 2>/dev/null || true`,{encoding:"utf8"}),r=[];for(let f of n.split(`
|
|
133
|
-
`)){let l=f.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(l)r.push(l[1].toUpperCase())}return r}function Xf(i){if(process.platform!=="darwin")return;let t=_t(i.caPath);if(!t)return;let n=i.commonName??Pc,r=i.keychains??vc();for(let f of r)for(let l of yy(f,n)){if(l===t)continue;try{if(f.startsWith("/Library"))Gn(`security delete-certificate -Z ${l} "${f}"`);else Mn(`security delete-certificate -Z ${l} "${f}"`,{stdio:"ignore"});T("ssl",`Removed stale Root CA ${l} from ${f}`,i.verbose)}catch{}}}function qn(i,t,n){if(process.platform!=="darwin")return Ln(i,n);try{let f=Mn(`security verify-cert -c "${i}" -s "${t}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return T("ssl",`verify-cert ${t}: ${f?"trusted":"not trusted"}`,n?.verbose),f}catch{return!1}}function Ln(i,t){let n=_t(i);if(!n)return!1;for(let r of vc())try{let f=Mn(`security find-certificate -a -Z "${r}" 2>/dev/null || true`,{encoding:"utf8"});for(let l of f.split(`
|
|
134
|
-
`))if(l.toUpperCase().includes("SHA-256")){if(l.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===n)return T("ssl",`Root CA fingerprint found in ${r}`,t?.verbose),!0}}catch{}return!1}function Zc(i,t){if(process.platform!=="darwin")return!1;let n=t.serverName;Xf({caPath:i,commonName:t.commonName,verbose:t.verbose});let r=Hn();try{Mn(`security add-trusted-cert ${Ct} -k "${r}" "${i}"`,{stdio:"ignore"})}catch{}try{Gn(`security add-trusted-cert ${Ct} -k ${It} "${i}"`)}catch{return!1}return qn(i,n,{verbose:t.verbose})||Ln(i,{verbose:t.verbose})}var Rt=null,t0=b(En(),".stacks","ssl","rpx.localhost.crt");function By(i,t){return[...new Set(i.filter(Boolean))].map((n)=>({serverName:n,cert:t.cert,key:t.key}))}function my(i,t,n){let r=b(En(),".stacks","ssl"),f=[...new Set([t,...i,"rpx.localhost"])];return{https:{certPath:t0,keyPath:b(r,"rpx.localhost.key"),caCertPath:b(r,"rpx.localhost.ca.crt"),commonName:t},verbose:n,regenerateUntrustedCerts:!0,proxies:f.map((l)=>({from:"localhost:1",to:l,cleanUrls:!1}))}}var cY="rpx-root-ca.crt",$Y="rpx-root-ca.key";function n0(i){return{caCertPath:b(i,cY),caKeyPath:b(i,$Y)}}function lj(i){return{certPath:b(i,"rpx.localhost.crt"),keyPath:b(i,"rpx.localhost.key"),caCertPath:b(i,"rpx.localhost.ca.crt"),rootCA:n0(i)}}async function wY(i,t){try{let[n,r]=await Promise.all([v.readFile(i.caCertPath,"utf8"),v.readFile(i.caKeyPath,"utf8")]);if(!n.includes("-----BEGIN CERTIFICATE-----")||!r.includes("PRIVATE KEY-----"))return T("ssl",`Root CA files at ${i.caCertPath} look malformed, will regenerate`,t),null;return{certificate:n,privateKey:r}}catch(n){return T("ssl",`No existing Root CA at ${i.caCertPath} (${n.code||n}), will create one`,t),null}}function uy(i){let t=new Set;t.add(i);let n=i.split(".");if(n.length>=2)t.add(`*.${n.slice(1).join(".")}`);return Array.from(t)}function Cy(i){let n=i0(i).replace(/\*/g,"wildcard"),r=b(En(),".stacks","ssl"),f=r;if(typeof i?.https==="object")return f=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:r,{caCertPath:i.https.caCertPath||b(f,`${n}.ca.crt`),certPath:i.https.certPath||b(f,`${n}.crt`),keyPath:i.https.keyPath||b(f,`${n}.key`)};return{caCertPath:b(f,`${n}.ca.crt`),certPath:b(f,`${n}.crt`),keyPath:b(f,`${n}.key`)}}function ey(i){let t=new Set;if(Ff(i))i.proxies.forEach((n)=>{let r=n.to||"rpx.localhost";uy(r).forEach((f)=>t.add(f))});else if(Ey(i)){let n=i.to||"rpx.localhost";uy(n).forEach((r)=>t.add(r))}else t.add("rpx.localhost");return t.add("localhost"),t.add("*.localhost"),t}async function cj(i){T("ssl","Loading SSL configuration",i.verbose);let t={...hy,...i};if(i.https=l0(t),!i.https?.keyPath&&!i.https?.certPath)return T("ssl","No SSL configuration provided",i.verbose),null;if(i.https?.keyPath&&!i.https?.certPath||!i.https?.keyPath&&i.https?.certPath){let n=!i.https?.keyPath?"keyPath":"certPath";throw T("ssl",`Invalid SSL configuration - missing ${n}`,i.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${n}`)}try{if(!i.https?.keyPath||!i.https?.certPath)return null;try{T("ssl","Reading SSL certificate files",i.verbose);let n=await v.readFile(i.https?.keyPath,"utf8"),r=await v.readFile(i.https?.certPath,"utf8");return T("ssl","SSL configuration loaded successfully",i.verbose),{key:n,cert:r}}catch(n){return T("ssl",`Failed to read certificates: ${n}`,i.verbose),null}}catch(n){throw T("ssl",`SSL configuration error: ${n}`,i.verbose),n}}async function $j(i,t){if(gi.platform==="darwin")return hY(i,t);if(gi.platform==="linux")try{let{exec:n}=await import("node:child_process");return await new Promise((r)=>{n(`sudo cp "${i}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(f)=>{if(!f)r(!0);else n(`sudo cp "${i}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(l)=>{r(!l)})})})}catch{return!1}return!1}async function hY(i,t){if(gi.platform!=="darwin")return!1;let n=t?.serverName??"rpx.localhost",r=t?.verbose??!1;try{if(qn(i,n,{verbose:r}))return T("ssl","Root CA already trusted for SSL, skipping trust operation",r),!0;return T("ssl","Trusting Root CA for browsers (login + system keychains)",r),Zc(i,{serverName:n,verbose:r})}catch{return!1}}async function Ry(i){if(Rt&&!i.forceRegenerate){T("ssl","Using cached SSL configuration",i.verbose);return}r0();let t=Ff(i)?i.proxies.map((y)=>y.to):[i.to];T("ssl",`Generating certificate for domains: ${t.join(", ")}`,i.verbose);let n=l0(i,i.verbose),r=n.basePath||b(En(),".stacks","ssl");await v.mkdir(r,{recursive:!0});let f=n0(r),l=await wY(f,i.verbose),c=!1;if(!l){if(i.verbose)F.info("Generating Root CA certificate (one-time)...");l=await ol(n);try{await Promise.all([v.writeFile(f.caCertPath,l.certificate),v.writeFile(f.caKeyPath,l.privateKey,{mode:384})]),c=!0,T("ssl",`Persisted Root CA at ${f.caCertPath}`,i.verbose)}catch(y){throw T("ssl",`Error saving Root CA files: ${y}`,i.verbose),Error(`Failed to save Root CA files: ${y}`)}}else T("ssl",`Reusing existing Root CA from ${f.caCertPath}`,i.verbose);if(i.verbose)F.info(`Generating host certificate for: ${t.join(", ")}`);let $=await pl({...n,rootCA:{certificate:l.certificate,privateKey:l.privateKey}});try{await Promise.all([v.writeFile(n.certPath,$.certificate),v.writeFile(n.keyPath,$.privateKey),v.writeFile(n.caCertPath,l.certificate)]),T("ssl","Certificate files saved successfully",i.verbose)}catch(y){throw T("ssl",`Error saving certificate files: ${y}`,i.verbose),Error(`Failed to save certificate files: ${y}`)}if(c?!1:await sy(f.caCertPath,{verbose:i.verbose,regenerateUntrustedCerts:!0})){if(T("ssl","Root CA already trusted, skipping trust store update",i.verbose),i.verbose)F.success("Root CA is already trusted in system trust store");if(Rt={key:$.privateKey,cert:$.certificate,ca:l.certificate},i.verbose)F.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);return}if(i.verbose)F.info("Adding certificate to system trust store (may require sudo permission)...");let h=!1;if(gi.platform==="darwin")try{Xf({caPath:f.caCertPath,verbose:i.verbose});let y=Hn();try{oc(`security add-trusted-cert ${Ct} -k "${y}" "${f.caCertPath}"`,{stdio:"ignore"})}catch{}if(Gn(`security add-trusted-cert ${Ct} -k ${It} "${f.caCertPath}"`),i.verbose)F.success("Successfully added Root CA to system trust store");h=!0;let u=b(r,"trust-rpx-cert.sh"),e=`#!/bin/bash
|
|
135
|
-
echo "Trusting RPX Root CA"
|
|
136
|
-
sudo security add-trusted-cert ${Ct} -k ${It} "${f.caCertPath}"
|
|
137
|
-
echo "Root CA trusted! Please restart your browser."
|
|
138
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
139
|
-
`;await v.writeFile(u,e,{mode:493})}catch(y){if(i.verbose)F.warn(`Could not add Root CA to trust store automatically: ${y}`);let u=b(r,"trust-rpx-cert.sh"),e=`#!/bin/bash
|
|
140
|
-
echo "Trusting RPX Root CA"
|
|
141
|
-
sudo security add-trusted-cert ${Ct} -k ${It} "${f.caCertPath}"
|
|
142
|
-
echo "Root CA trusted! Please restart your browser."
|
|
143
|
-
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
144
|
-
`;if(await v.writeFile(u,e,{mode:493}),i.verbose)F.info(`Created a trust helper script at: ${u}`),F.info(`If you're still having certificate issues, run: sh ${u}`)}else if(gi.platform==="linux")try{let{exec:y}=await import("node:child_process"),u="/usr/local/share/ca-certificates/rpx",e=`
|
|
145
|
-
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
146
|
-
cp "${f.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
147
|
-
update-ca-certificates
|
|
148
|
-
echo "RPX Root CA installed. Please restart your browser."
|
|
149
|
-
`,A=b(pc.tmpdir(),`rpx-trust-${Date.now()}.sh`);await v.writeFile(A,e,{mode:493}),await new Promise((B)=>{y(`sudo bash "${A}"`,(E)=>{if(E){if(i.verbose)F.warn(`Could not trust certificates: ${E}`);B(!1)}else{if(i.verbose)F.success("Successfully added certificates to system trust store");B(!0)}})}),await v.unlink(A).catch(()=>{}),h=!0}catch(y){if(i.verbose)F.warn(`Failed to trust certificates: ${y}`)}else if(gi.platform==="win32")try{let y=`
|
|
150
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${f.caCertPath.replace(/\//g,"\\")}")
|
|
151
|
-
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
152
|
-
$store.Open("ReadWrite")
|
|
153
|
-
$store.Add($cert)
|
|
154
|
-
$store.Close()
|
|
155
|
-
Write-Host "Root CA trusted successfully!"
|
|
156
|
-
`,u=b(pc.tmpdir(),"rpx-trust.ps1");if(await v.writeFile(u,y),oc(`powershell -ExecutionPolicy Bypass -File "${u}"`),i.verbose)F.success("Successfully added certificate to Windows trust store");h=!0}catch(y){if(i.verbose)F.warn(`Could not trust certificate: ${y}`)}else try{await rc($,l.certificate,n),h=!0}catch(y){if(i.verbose)F.warn(`Could not add certificate to trust store: ${y}`)}if(Rt={key:$.privateKey,cert:$.certificate,ca:l.certificate},i.verbose)F.success(`Certificate generated successfully for ${t.length} domain${t.length>1?"s":""}`);if(!h&&i.verbose)F.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),F.warn("This will bypass the warning and you should only need to do it once")}function r0(){Rt=null}async function f0(i){if(!i)return null;if(Rt)return Rt;let t=l0(i);try{let[n,r,f]=await Promise.all([v.access(t.keyPath).then(()=>!0).catch(()=>!1),v.access(t.certPath).then(()=>!0).catch(()=>!1),t.caCertPath?v.access(t.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!n||!r)return T("ssl",`Certificate files don't exist: key=${n}, cert=${r}, paths: ${t.keyPath}, ${t.certPath}`,i.verbose),null;let l="regenerateUntrustedCerts"in i,c=i.regenerateUntrustedCerts,$=l?c!==!1:!0;T("ssl",`Trust check: hasFlag=${l}, flagValue=${c}, shouldCheckTrust=${$}`,i.verbose);let w=t.basePath||b(En(),".stacks","ssl"),h=n0(w);if(!($?await sy(h.caCertPath,i):!0))return T("ssl","Root CA exists but is not trusted, will regenerate",i.verbose),null;let[u,e,A]=await Promise.all([v.readFile(t.keyPath,"utf8"),v.readFile(t.certPath,"utf8"),f&&t.caCertPath?v.readFile(t.caCertPath,"utf8"):Promise.resolve(void 0)]);if(A&&!A.includes("-----BEGIN CERTIFICATE-----"))return T("ssl","Invalid root CA certificate content, will regenerate",i.verbose),null;if(Ff(i))try{let{X509Certificate:B}=await import("node:crypto"),Y=new B(e).subjectAltName||"",C=i.proxies.map((a)=>a.to).filter((a)=>!Y.includes(`DNS:${a}`));if(C.length>0)return T("ssl",`Certificate missing SANs for: ${C.join(", ")}, will regenerate`,i.verbose),null}catch(B){T("ssl",`Could not verify cert SANs: ${B}`,i.verbose)}return T("ssl","Successfully loaded existing certificates",i.verbose),Rt={key:u,cert:e,ca:A},Rt}catch(n){return T("ssl",`Error checking existing certificates: ${n}`,i.verbose),null}}function l0(i,t){let n=i0(i);T("ssl",`Primary domain: ${n}`,t);let r=Cy(i),f=b(En(),".stacks","ssl");if(typeof i.https==="object"){let l=i.https.basePath&&i.https.basePath.trim()!==""?i.https.basePath:f,c={domain:n,hostCertCN:n,basePath:l,caCertPath:i.https.caCertPath||r.caCertPath,certPath:i.https.certPath||r.certPath,keyPath:i.https.keyPath||r.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:i.https.commonName||n,organizationName:i.https.organizationName||"Local Development",countryName:i.https.countryName||"US",stateName:i.https.stateName||"California",localityName:i.https.localityName||"Playa Vista",validityDays:i.https.validityDays||825,verbose:t||!1,subjectAltNames:Array.from(ey(i)).map(($)=>({type:2,value:$}))};if(Ay(i.https.rootCA))c.rootCA=i.https.rootCA;return c}return{domain:n,hostCertCN:n,basePath:f,...r,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:n,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:t||!1,subjectAltNames:Array.from(ey(i)).map((l)=>({type:2,value:l}))}}async function wj(i,t){let n=Cy({to:i,verbose:t}),r=[n.caCertPath,n.certPath,n.keyPath];T("certificates","Attempting to clean up relating certificates",t),await Promise.all(r.map((f)=>Ty(f,t)))}async function sy(i,t){try{if(T("ssl",`Checking if certificate is trusted: ${i}`,t?.verbose),gi.platform==="darwin"){if(t?.serverName)return qn(i,t.serverName,{verbose:t?.verbose});return Ln(i,{verbose:t?.verbose})}else if(gi.platform==="win32")try{let n=bc(i)||"";if(!n)return T("ssl","Could not extract certificate subject",t?.verbose),!1;let r=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(oc(r).toString().includes(n))return T("ssl","Certificate found in trusted root store",t?.verbose),!0;return T("ssl","Certificate not found in trusted root store",t?.verbose),!1}catch(n){return T("ssl",`Error checking certificate trust on Windows: ${n}`,t?.verbose),!1}else if(gi.platform==="linux")try{let n=_t(i);if(!n)return T("ssl","Could not extract certificate fingerprint",t?.verbose),!1;let r=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of r){let l;try{l=await v.readdir(f)}catch{continue}for(let c of l){let $=_t(Yy.join(f,c));if($&&$===n)return T("ssl",`Certificate fingerprint found in ${f}`,t?.verbose),!0}}return T("ssl","Certificate not found in system trust stores",t?.verbose),!1}catch(n){return T("ssl",`Error checking certificate trust on Linux: ${n}`,t?.verbose),!1}return T("ssl",`Platform ${gi.platform} not supported for certificate trust check`,t?.verbose),!1}catch(n){return T("ssl",`Error checking if certificate is trusted: ${n}`,t?.verbose),!1}}function yY(i){return{enabled:i?.enabled??!1,path:i?.path??"/",interval:i?.interval??1e4,timeout:i?.timeout??2000,healthyThreshold:i?.healthyThreshold??2,unhealthyThreshold:i?.unhealthyThreshold??3}}function uY(i){return(Array.isArray(i)?i:[i]).map((n)=>{let r=typeof n==="string"?{url:n}:n;return{url:r.url,weight:r.weight&&r.weight>0?r.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function Uy(i){return(Array.isArray(i)?i:[i]).map((n)=>typeof n==="string"?n:n.url)}function jy(i){if(!i)return"localhost:5173";let t=Array.isArray(i)?i[0]:i;if(!t)return"localhost:5173";return typeof t==="string"?t:t.url}function Sy(i,t){return{upstreams:uY(i),strategy:t?.strategy??"round-robin",healthCheck:yY(t?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function eY(i){let t=i.upstreams.filter((n)=>n.healthy);if(t.length===0&&i.upstreams.length===1)return i.upstreams;return t}function AY(i,t){let n=i.cursor%t.length;return i.cursor=(i.cursor+1)%t.length,t[n]}function EY(i,t){if(i.wrrCurrentWeights.length!==t.length)i.wrrCurrentWeights=t.map(()=>0);let n=t.reduce((f,l)=>f+l.weight,0),r=0;for(let f=0;f<t.length;f++)if(i.wrrCurrentWeights[f]+=t[f].weight,i.wrrCurrentWeights[f]>i.wrrCurrentWeights[r])r=f;return i.wrrCurrentWeights[r]-=n,t[r]}function TY(i){let t=i[0];for(let n=1;n<i.length;n++)if(i[n].activeConnections<t.activeConnections)t=i[n];return t}function ay(i){let t=eY(i);if(t.length===0)return;if(t.length===1)return t[0];switch(i.strategy){case"weighted-round-robin":return EY(i,t);case"least-connections":return TY(t);case"round-robin":default:return AY(i,t)}}function Wf(i,t){if(t.consecutiveFailures=0,t.consecutiveSuccesses+=1,!t.healthy&&t.consecutiveSuccesses>=i.healthCheck.healthyThreshold)t.healthy=!0}function gn(i,t){if(t.consecutiveSuccesses=0,t.consecutiveFailures+=1,t.healthy&&t.consecutiveFailures>=i.healthCheck.unhealthyThreshold)t.healthy=!1}function YY(i){let t=i.lastIndexOf(":");if(t===-1)return{hostname:i,port:80};let n=Number(i.slice(t+1));return{hostname:i.slice(0,t),port:Number.isFinite(n)?n:80}}async function BY(i,t){let{hostname:n,port:r}=YY(t.url),f=new AbortController,l=setTimeout(()=>f.abort(),i.healthCheck.timeout);try{(await fetch(`http://${n}:${r}${i.healthCheck.path}`,{signal:f.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),Wf(i,t)}catch{gn(i,t)}finally{clearTimeout(l)}}function Ny(i){if(!i.healthCheck.enabled||i.healthCheckTimer||i.upstreams.length<2)return;let t=setInterval(()=>{for(let n of i.upstreams)BY(i,n)},i.healthCheck.interval);t.unref?.(),i.healthCheckTimer=t}function c0(i){if(i.healthCheckTimer)clearInterval(i.healthCheckTimer),i.healthCheckTimer=null}import{createHash as Fy,timingSafeEqual as Xy}from"node:crypto";import{readFileSync as mY}from"node:fs";var CY="/.well-known/acme-challenge/";function xn(i,t){let n=Buffer.from(i,"utf8"),r=Buffer.from(t,"utf8");if(n.length!==r.length)return Xy(n,n),!1;return Xy(n,r)}function RY(i,t){let n=(e)=>Fy("md5").update(e).digest(),r=Buffer.from(i,"utf8"),f=Buffer.from(t,"utf8"),l=n(Buffer.concat([r,f,r])),c=[r,Buffer.from("$apr1$","utf8"),f];for(let e=r.length;e>0;e-=16)c.push(l.subarray(0,Math.min(e,16)));for(let e=r.length;e>0;e>>=1)c.push(e&1?Buffer.from([0]):r.subarray(0,1));let $=n(Buffer.concat(c));for(let e=0;e<1000;e++){let A=[];if(A.push(e&1?r:$.subarray(0,16)),e%3)A.push(f);if(e%7)A.push(r);A.push(e&1?$.subarray(0,16):r),$=n(Buffer.concat(A))}let w="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",h=(e,A)=>{let B="",E=e;for(let Y=0;Y<A;Y++)B+=w[E&63],E>>=6;return B},y=$,u="";return u+=h(y[0]<<16|y[6]<<8|y[12],4),u+=h(y[1]<<16|y[7]<<8|y[13],4),u+=h(y[2]<<16|y[8]<<8|y[14],4),u+=h(y[3]<<16|y[9]<<8|y[15],4),u+=h(y[4]<<16|y[10]<<8|y[5],4),u+=h(y[11],2),`$apr1$${t}$${u}`}function sY(i,t){if(/^\$2[aby]?\$/.test(t))try{return Bun.password.verifySync(i,t)}catch{return!1}if(t.startsWith("$apr1$")){let r=t.split("$")[2]??"";return xn(RY(i,r),t)}if(t.startsWith("{SHA}")){let n=Fy("sha1").update(i,"utf8").digest("base64");return xn(`{SHA}${n}`,t)}return xn(i,t)}function UY(i){let t=new Map;for(let n of i.split(`
|
|
157
|
-
`)){let r=n.trim();if(!r||r.startsWith("#"))continue;let f=r.indexOf(":");if(f<=0)continue;t.set(r.slice(0,f),r.slice(f+1))}return t}function Wy(i){if(!i)return;let t=(i.realm??"").trim()||"Restricted",n=[];if(i.username)n.push({username:i.username,password:i.password??""});for(let l of i.users??[])if(l?.username)n.push({username:l.username,password:l.password??""});let r;if(i.htpasswdFile)try{r=UY(mY(i.htpasswdFile,"utf8"))}catch{r=void 0}if(n.length===0&&(!r||r.size===0))return;return{realm:t,verify:(l,c)=>{let $=!1;for(let w of n)if(xn(l,w.username)&&xn(c,w.password))$=!0;if(r){let w=r.get(l);if(w&&sY(c,w))$=!0}return $}}}function Jy(i,t,n){if(t.startsWith(CY))return;let r=i.headers.get("authorization")??"",f=r.indexOf(" "),l=f===-1?r:r.slice(0,f),c=f===-1?"":r.slice(f+1).trim();if(l.toLowerCase()==="basic"&&c){let w="";try{w=Buffer.from(c,"base64").toString("utf8")}catch{w=""}let h=w.indexOf(":");if(h>=0&&n.verify(w.slice(0,h),w.slice(h+1)))return}let $=n.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${$}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var{connect:jY}=Bun,dn=Symbol("rpx.pool.fallback"),Jf=Symbol("rpx.pool.stale");var SY=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function aY(i){return SY.has(i.toUpperCase())}var w0=Symbol("rpx.pool.timeout"),Kt=Symbol("rpx.pool.busy");function NY(){let i=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(i)&&i>0?i:30000}function XY(i){let t=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(t)&&t>0?t:i*8}function FY(){let i=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(i)&&i>0?i:0}function WY(){let i=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(i)&&i>0?i:0}var Iy=1048576;function JY(){let i=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(i)&&i>0?i:256}var $0=30000,_Y=16384,Ky=262144,IY=2097152,KY=524288,zY=8192,OY=4096,GY=new TextEncoder,zy=new TextDecoder,MY=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);class Oy{socket=null;buf=new Uint8Array(_Y);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(i){let t=this.socket,n=t.write(i);while(n<i.length){if(this.closed)throw Jf;await new Promise((r)=>{this.drainWaiter=r}),n+=t.write(i.subarray(n))}}wakeDrain(){let i=this.drainWaiter;if(i)this.drainWaiter=null,i()}push(i){if(this.bodyQueue){let t=i.length<=this.bodyRemaining?i.length:this.bodyRemaining;if(t>0)this.bodyQueue.push(i.slice(0,t)),this.queuedBytes+=t;if(this.bodyRemaining-=t,t<i.length)this.appendToBuf(i.subarray(t));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(i),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>IY)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=KY)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(i){let t=this.len+i.length;if(t>this.buf.length){let n=new Uint8Array(Math.max(this.buf.length*2,t));n.set(this.buf.subarray(0,this.len)),this.buf=n}this.buf.set(i,this.len),this.len=t}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let i=this.waiter;if(i)this.waiter=null,i()}waitForData(i){if(this.len>i||this.closed)return Promise.resolve();return new Promise((t)=>{this.waiter=t})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((i)=>{this.waiter=i})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class Gy{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=NY();maxWaiters;checkoutIdleMs=FY();inUse=new Set;constructor(i,t,n,r=""){this.host=i;this.port=t;this.maxTotal=n;this.key=r;this.maxWaiters=XY(n)}trackCheckout(i){if(i.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(i),this.ensureSweeper()}dial(){let i=new Oy;return jY({hostname:this.host,port:this.port,socket:{data:(t,n)=>i.push(n),drain:()=>i.wakeDrain(),close:()=>i.markClosed(),end:()=>i.markClosed(),error:()=>i.markClosed(),connectError:()=>i.markClosed(),timeout:()=>i.markTimedOut()}}).then((t)=>{let n=t;n.setNoDelay?.(!0);let r=WY();if(r>0)n.timeout?.(r);return i.socket=t,i})}acquireIdleSync(){while(this.idle.length){let i=this.idle.pop();if(!i.closed)return i.socket?.ref(),i.pos=0,i.len=0,this.trackCheckout(i),i;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw Kt;let i=await this.waitForSlot();if(i===Kt)throw Kt;if(i)return i.pos=0,i.len=0,this.trackCheckout(i),i}this.open++;try{let i=await this.dial();return this.trackCheckout(i),i}catch(i){throw this.open--,this.wakeWaiter(),i}}waitForSlot(){return new Promise((i)=>{let t=!1,n=(l)=>{if(t)return;t=!0,clearTimeout(f),i(l)},r=(l)=>n(l),f=setTimeout(()=>{let l=this.waiters.indexOf(r);if(l!==-1)this.waiters.splice(l,1);n(Kt)},this.queueWaitMs);f.unref?.(),this.waiters.push(r)})}release(i){if(this.inUse.delete(i),i.closed){this.open--,this.wakeWaiter();return}i.clearStreaming(),i.compact(),i.fresh=!1;let t=this.waiters.shift();if(t){i.socket?.ref(),this.trackCheckout(i),t(i);return}i.idleSince=Date.now(),i.socket?.unref(),this.idle.push(i),this.ensureSweeper()}destroy(i){this.inUse.delete(i),i.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let i=this.waiters.shift();if(i)i(null)}ensureSweeper(){if(this.sweeper)return;let i=this.checkoutIdleMs>0?Math.min($0,this.checkoutIdleMs):$0;this.sweeper=setInterval(()=>this.sweep(),i),this.sweeper.unref?.()}sweep(){let i=Date.now(),t=i-$0;if(this.idle.length){let n=[];for(let r of this.idle)if(r.closed||r.idleSince<=t)r.destroy(),this.open--;else n.push(r);this.idle=n}if(this.checkoutIdleMs>0&&this.inUse.size){let n=i-this.checkoutIdleMs;for(let r of this.inUse)if(!r.closed&&r.lastActivityAt>0&&r.lastActivityAt<=n)r.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&_f.get(this.key)===this)_f.delete(this.key)}}}var _f=new Map;function HY(i,t){let n=_f.get(i);if(!n){let r=i.lastIndexOf(":"),f=r===-1?i:i.slice(0,r),l=r===-1?80:Number(i.slice(r+1));n=new Gy(f,l,t,i),_f.set(i,n)}return n}function _y(i,t,n){for(let r=n+3;r<t;r++)if(i[r]===10&&i[r-1]===13&&i[r-2]===10&&i[r-3]===13)return r-3;return-1}function qY(i,t,n){let r=zy.decode(i.subarray(t,n)),f=r.indexOf(`\r
|
|
158
|
-
`),l=f===-1?r:r.slice(0,f),c=l.indexOf(" "),$=Number.parseInt(l.slice(c+1,c+5),10),w=l.startsWith("HTTP/1.0"),h=[],y=-1,u=!1,e=w,A=!1,B=!1,E=f===-1?r.length:f+2;while(E<r.length){let Y=r.indexOf(`\r
|
|
159
|
-
`,E);if(Y===-1)Y=r.length;let m=r.slice(E,Y);if(E=Y+2,m==="")continue;let C=m.indexOf(":");if(C===-1)continue;let a=m.slice(0,C),N=m.slice(C+1).trim(),j=a.charCodeAt(0)|32;if(j===99||j===116||j===107){let X=a.toLowerCase();if(X==="content-length"){let M=/^\d+$/.test(N)?Number(N):Number.NaN;if(!Number.isSafeInteger(M)||y>=0&&y!==M)B=!0;else y=M;continue}if(X==="transfer-encoding"){if(N.toLowerCase().includes("chunked"))u=!0;continue}if(X==="connection"){let M=N.toLowerCase();if(M.includes("close"))e=!0;if(M.includes("keep-alive"))A=!0;continue}if(X==="keep-alive")continue}h.push([a,N])}if(w&&A)e=!1;if(u&&y>=0)y=-1;return{status:$,headerEnd:n,headers:h,contentLength:y,chunked:u,closeConn:e,malformed:B}}function LY(i,t){return t||i===204||i===304}async function My(i){let{hostPort:t,method:n,path:r,reqHeaders:f,forwardedHost:l,originOverride:c,body:$}=i,w=n==="HEAD";if(f.get("expect")||f.get("upgrade"))throw dn;let h=null;if($){let A=f.get("content-length"),B=A?Number.parseInt(A,10):Number.NaN;if(Number.isNaN(B)||B>Iy)throw dn;if(h=await bY($),h===null)throw dn}let y=DY(n,r,f,t,l,c,h),u=y;if(h&&h.length)u=new Uint8Array(y.length+h.length),u.set(y),u.set(h,y.length);let e=HY(t,i.maxPerHost??JY());for(let A=0;;A++){if(A>0)await new Promise((E)=>{setTimeout(E,A)});let B;try{B=e.acquireIdleSync()??await e.acquireOrDial()}catch(E){if(E!==Kt&&A<4)continue;throw E}try{let E=B.socket.write(u);if(E<u.length)await B.writeAll(u.subarray(E));return await xY(e,B,w)}catch(E){let Y=E===Jf&&A<4&&(B.fresh||aY(n));if(e.destroy(B),Y)continue;if(E===Jf)throw Error("upstream closed connection");throw E}}}async function gY(i){let t=_y(i.buf,i.len,i.pos);while(t===-1){if(i.closed){if(i.timedOut)throw w0;if(i.len===i.pos)throw Jf;throw Error("upstream closed mid-header")}if(i.len-i.pos>Ky)throw Error("upstream header block too large");await i.waitForData(i.len),t=_y(i.buf,i.len,i.pos)}return t}async function xY(i,t,n){let r;for(;;){let l=await gY(t);if(r=qY(t.buf,t.pos,l),t.pos=l+4,r.status>=100&&r.status<200)continue;break}if(r.malformed)throw i.destroy(t),Error("upstream sent malformed response framing");let f=r.headers;if(LY(r.status,n))return Hy(i,t,r.closeConn),new Response(null,{status:r.status,headers:f});if(r.chunked)return new Response(VY(i,t,r.closeConn),{status:r.status,headers:f});if(r.contentLength>=0){if(t.len-t.pos>=r.contentLength){let c=t.pos+r.contentLength,$=t.len>c,w=null;if(r.contentLength>=zY)w=t.buf.subarray(t.pos,c),t.buf=new Uint8Array(OY);else if(r.contentLength>0)w=t.buf.slice(t.pos,c);if(t.pos=0,t.len=0,r.closeConn||$)i.destroy(t);else i.release(t);return new Response(w,{status:r.status,headers:f})}return new Response(dY(i,t,r.contentLength,r.closeConn),{status:r.status,headers:f})}return new Response(kY(t),{status:r.status,headers:f})}function Hy(i,t,n){if(n||t.pos!==t.len)i.destroy(t);else i.release(t)}function dY(i,t,n,r){let f=t.len-t.pos,l=f>0?t.buf.slice(t.pos,t.len):null;t.pos=0,t.len=0,t.bodyQueue=[],t.bodyRemaining=n-f,t.queuedBytes=0,t.streamingBody=!0;let c=($)=>{if(t.bodyQueue=null,r||t.len>0)i.destroy(t);else i.release(t);$.close()};return new ReadableStream({start($){if(l)$.enqueue(l);if(t.bodyRemaining===0&&t.bodyQueue.length===0)c($)},async pull($){for(;;){let w=t.bodyQueue;if(w&&w.length>0){let h=w.shift();if(t.queuedBytes-=h.length,t.resumeIfDrained(),$.enqueue(h),t.bodyRemaining===0&&w.length===0)c($);return}if(t.bodyRemaining===0){if(t.bodyQueue)c($);return}if(t.closed){t.bodyQueue=null,i.destroy(t),$.error(Error("upstream closed mid-body"));return}await t.waitForBody()}},cancel(){t.bodyQueue=null,i.destroy(t)}})}function kY(i){return i.streamingBody=!0,new ReadableStream({async pull(t){for(;;){if(i.len>i.pos){t.enqueue(i.buf.slice(i.pos,i.len)),i.pos=i.len,i.resumeIfDrained();return}if(i.closed){i.destroy(),t.close();return}await i.waitForData(i.len)}},cancel(){i.destroy()}})}function VY(i,t,n){t.streamingBody=!0;let r=0,f=!1;async function l(){for(;;){for(let c=t.pos;c+1<t.len;c++)if(t.buf[c]===13&&t.buf[c+1]===10){let $=zy.decode(t.buf.subarray(t.pos,c));return t.pos=c+2,$}if(t.closed)throw Error("upstream closed mid-chunk-header");if(t.len-t.pos>Ky)throw Error("upstream chunk header too large");await t.waitForData(t.len)}}return new ReadableStream({async pull(c){for(;;){if(r>0){if(t.len===t.pos){if(t.closed){i.destroy(t),c.error(Error("upstream closed mid-chunk"));return}await t.waitForData(t.len);continue}let y=Math.min(r,t.len-t.pos);if(c.enqueue(t.buf.slice(t.pos,t.pos+y)),t.pos+=y,r-=y,t.resumeIfDrained(),r===0)f=!0;return}if(f)await l(),f=!1;let $=await l(),w=$.indexOf(";"),h=Number.parseInt(w===-1?$:$.slice(0,w),16);if(!Number.isInteger(h)||h<0){i.destroy(t),c.error(Error("upstream sent malformed chunk size"));return}if(h===0){for(;;)if(await l()==="")break;Hy(i,t,n),c.close();return}r=h}},cancel(){i.destroy(t)}})}function DY(i,t,n,r,f,l,c){let $=`${i} ${t} HTTP/1.1\r
|
|
160
|
-
host: ${r}\r
|
|
161
|
-
x-forwarded-for: 127.0.0.1\r
|
|
162
|
-
x-forwarded-proto: https\r
|
|
163
|
-
x-forwarded-host: ${f}\r
|
|
164
|
-
`;if(l!==void 0)$+=`origin: ${l}\r
|
|
165
|
-
`;let w=!1;for(let[h,y]of n){let u=h.toLowerCase();if(MY.has(u))continue;if(l!==void 0&&u==="origin")continue;if(u==="content-length")w=!0;$+=`${h}: ${y}\r
|
|
166
|
-
`}if($+=`connection: keep-alive\r
|
|
167
|
-
`,c&&!w)$+=`content-length: ${c.length}\r
|
|
168
|
-
`;return $+=`\r
|
|
169
|
-
`,GY.encode($)}async function bY(i){let t=i.getReader(),n=[],r=0;for(;;){let{done:c,value:$}=await t.read();if(c)break;if($){if(r+=$.length,r>Iy)return t.cancel().catch(()=>{}),null;n.push($)}}if(n.length===1)return n[0];let f=new Uint8Array(r),l=0;for(let c of n)f.set(c,l),l+=c.length;return f}function Bj(i){let t=typeof i==="string"?{to:i}:i,n=(t.to??"").trim();if(n&&!/^[a-z][\w+.-]*:\/\//i.test(n))n=`https://${n}`;return n=n.replace(/\/+$/,""),{to:n,status:t.status??301,preservePath:t.preservePath??!0}}function qy(i,t,n){if(!i.preservePath)return i.to||"/";let r=`${t}${n}`;return r==="/"?`${i.to}/`:`${i.to}${r}`}import*as Ki from"node:path";function Ly(i,t){if(typeof i==="string")return{dir:i,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:t};return{dir:i.dir,spa:i.spa??!1,pathRewriteStyle:i.pathRewriteStyle??"directory",maxAge:i.maxAge??0,cleanUrls:t}}var QY={".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 PY(i){let t=Ki.extname(i).toLowerCase();return QY[t]??"application/octet-stream"}function vY(i){let t;try{t=decodeURIComponent(i)}catch{return null}if(t.includes("\x00")||t.includes("\\"))return null;let n=Ki.posix.normalize(`/${t}`);if(n.split("/").includes(".."))return null;return n.replace(/^\/+/,"")}function ZY(i,t){let n=vY(i);if(n===null)return null;let r=Ki.posix.extname(n);if(t.cleanUrls&&r===".html"){let f=i.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ki.join(t.dir,n),redirectTo:f||"/"}}if(n===""||i.endsWith("/"))return{filePath:Ki.join(t.dir,n,"index.html")};if(r!=="")return{filePath:Ki.join(t.dir,n)};if(t.pathRewriteStyle==="flat")return{filePath:Ki.join(t.dir,`${n}.html`)};return{filePath:Ki.join(t.dir,n,"index.html")}}async function gy(i,t){let n=ZY(i,t);if(!n)return new Response("Forbidden",{status:403});if(n.redirectTo)return new Response(null,{status:301,headers:{Location:n.redirectTo}});let r=t.maxAge>0?`public, max-age=${t.maxAge}`:"no-cache",f=Bun.file(n.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":PY(n.filePath),"Cache-Control":r}});if(t.spa){let l=Ki.join(t.dir,"index.html"),c=Bun.file(l);if(await c.exists())return new Response(c,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}function oY(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}var pY=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function iB(i){let t=i.headers.get("host")||"",n=t.indexOf(":");return n===-1?t:t.slice(0,n)}function Vy(i,t){if(!t||t==="/")return i;if(i===t)return"/";if(i.startsWith(`${t}/`)){let n=i.slice(t.length);return n===""?"/":n}return i}function xy(i){if(i.upstreamPool)return ay(i.upstreamPool);if(i.sourceHost)return{url:i.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function dy(i,t,n,r){let f=n?.url??t.sourceHost??"",c=t.stripBasePathPrefix??!1?Vy(i,t.basePath):i,$=ky(c,t.pathRewrites);if($)f=$.targetHost,c=$.targetPath,T("request",`Path rewrite: ${i} → ${f}${c}`,r);return{targetHost:f,targetPath:c}}function tB(i){let t=i.indexOf("://"),n=t===-1?i.indexOf("/"):i.indexOf("/",t+3);if(n===-1)return{pathname:"/",search:""};let r=i.indexOf("?",n);if(r===-1)return{pathname:i.slice(n),search:""};return{pathname:i.slice(n,r),search:i.slice(r)}}function h0(i,t,n){let r=async(f,l)=>{let{pathname:c,search:$}=tB(f.url),w=iB(f),h=i(w,c);if(!h&&n){let Y=await n(w,c,f);if(Y instanceof Response)return Y;if(Y&&Y.retry)h=i(w,c)}if(!h)return T("request",`No route found for host: ${w}`,t),new Response(`No proxy configured for ${w}`,{status:404});if(h.auth){let Y=Jy(f,c,h.auth);if(Y)return T("request",`401 challenge for ${w}${c}`,t),Y}if(h.redirect){let Y=qy(h.redirect,c,$);return T("request",`${h.redirect.status} redirect ${w}${c} → ${Y}`,t),new Response(null,{status:h.redirect.status,headers:{location:Y}})}if(h.static){let m=h.stripBasePathPrefix??!0?Vy(c,h.basePath):c;return gy(m,h.static)}if(f.headers.get("upgrade")?.toLowerCase()==="websocket"){let Y=xy(h);if(!l||!Y)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:m,targetPath:C}=dy(c,h,Y,t),a=`ws://${m}${C}${$}`,N={};for(let[M,o]of f.headers)if(!pY.has(M.toLowerCase())&&M.toLowerCase()!=="host")N[M]=o;N.host=m,N["x-forwarded-for"]="127.0.0.1",N["x-forwarded-proto"]="https",N["x-forwarded-host"]=w;let j={targetUrl:a,forwardHeaders:N};if(l.upgrade(f,{data:j})){T("ws",`upgraded ${w}${C} → ${a}`,t);return}return new Response("WebSocket upgrade failed",{status:400})}let y=xy(h);if(!y)return new Response(`No upstream configured for ${w}`,{status:502});if(h.cleanUrls&&c.endsWith(".html")){let Y=c.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:Y}})}let{targetHost:u,targetPath:e}=dy(c,h,y,t),A=h.changeOrigin?`http://${u}`:void 0,B=f.body!=null&&f.method!=="GET"&&f.method!=="HEAD",E=h.upstreamPool;if(E)y.activeConnections++;try{let Y=await My({hostPort:u,method:f.method,path:`${e}${$}`,reqHeaders:f.headers,forwardedHost:w,originOverride:A,body:f.body});if(E)Wf(E,y);return Y}catch(Y){if(Y===w0){if(T("request",`Upstream timeout for ${w}`,t),E)gn(E,y);return new Response("Gateway Timeout",{status:504})}if(Y===Kt)return T("request",`Upstream pool saturated for ${w}`,t),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(Y===dn||!B)try{let m=new Headers(f.headers);if(m.set("host",u),m.set("x-forwarded-for","127.0.0.1"),m.set("x-forwarded-proto","https"),m.set("x-forwarded-host",w),A!==void 0)m.set("origin",A);let C=await fetch(`http://${u}${e}${$}`,{method:f.method,headers:m,body:f.body,redirect:"manual"});if(E)Wf(E,y);return C}catch(m){if(T("request",`Proxy error for ${w}: ${m}`,t),E)gn(E,y);return new Response(`Proxy Error: ${m}`,{status:502})}if(T("request",`Proxy error for ${w}: ${Y}`,t),E)gn(E,y);return new Response(`Proxy Error: ${Y}`,{status:502})}finally{if(E)y.activeConnections--}};return async(f,l)=>{try{return await r(f,l)}catch(c){return T("request",`Unhandled proxy handler error: ${c}`,t),new Response("Bad Gateway",{status:502})}}}function y0(i){let t=new WeakMap,n=oY();return{open(r){let{targetUrl:f,forwardHeaders:l}=r.data,c;try{c=new WebSocket(f,{headers:l})}catch(w){T("ws",`failed to open upstream ${f}: ${w}`,i),r.close(1011,"upstream connect failed");return}c.binaryType="arraybuffer";let $={upstream:c,upstreamOpen:!1,pending:[],pendingBytes:0};t.set(r,$),c.addEventListener("open",()=>{$.upstreamOpen=!0;for(let w of $.pending)c.send(w);$.pending=[],$.pendingBytes=0}),c.addEventListener("message",(w)=>{r.send(w.data)}),c.addEventListener("close",(w)=>{try{r.close(w.code||1000,w.reason||"")}catch{}}),c.addEventListener("error",()=>{T("ws",`upstream error for ${f}`,i);try{r.close(1011,"upstream error")}catch{}})},message(r,f){let l=t.get(r);if(!l)return;let c=typeof f==="string"?f:new Uint8Array(f);if(l.upstreamOpen){l.upstream.send(c);return}let $=typeof c==="string"?Buffer.byteLength(c):c.byteLength;if(l.pendingBytes+$>n){T("ws",`pending buffer would exceed ${n}B before upstream open; closing socket`,i);try{r.close(1009,"buffer limit")}catch{}try{l.upstream.close(1011,"client buffer overflow")}catch{}t.delete(r);return}l.pending.push(c),l.pendingBytes+=$},close(r,f,l){let c=t.get(r);if(!c)return;t.delete(r);try{c.upstream.close(f||1000,l||"")}catch{}}}}import*as by from"node:fs";import*as Qy from"node:path";var Dy="/.well-known/acme-challenge/";function Py(i,t){if(!i||!t.startsWith(Dy))return null;let n=t.slice(Dy.length);if(!n||!/^[A-Za-z0-9_-]+$/.test(n))return null;try{return by.readFileSync(Qy.join(i,n),"utf8")}catch{return null}}function If(i){return i.startsWith("*.")}function u0(i,t){if(!If(t))return!1;let n=t.slice(1);return i.length>n.length&&i.endsWith(n)}function vy(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[l,c]of i){if(!If(l))continue;if(u0(t,l)){let $=l.length-1;if($>f)f=$,r=c}}return r}function zt(i){if(!i||i==="/")return"/";let t=i.trim();if(!t.startsWith("/"))t=`/${t}`;return t=t.replace(/\/+$/,""),t===""?"/":t}function nB(i,t){if(t==="/")return!0;if(i===t)return!0;return i.startsWith(`${t}/`)}function e0(i){let t=new Map;for(let r of i){let f=zt(r.path),l=t.get(r.host);if(!l)l=new Map,t.set(r.host,l);l.set(f,r.route)}let n=new Map;for(let[r,f]of t){let l=[];for(let[c,$]of f)l.push({path:c,route:$});l.sort((c,$)=>$.path.length-c.path.length),n.set(r,l)}return n}function A0(i,t){let n=i.get(t);if(n!==void 0)return n;let r,f=-1;for(let[l,c]of i){if(!If(l))continue;if(u0(t,l)){let $=l.length-1;if($>f)f=$,r=c}}return r}function E0(i,t,n){let r=A0(i,t);if(!r)return;for(let f of r)if(nB(n,f.path))return f.route;return}import*as kn from"node:fs/promises";import*as T0 from"node:path";function rB(i){if(!i.endsWith(".crt"))return null;let t=i.slice(0,-4);if(t.length===0)return null;if(t.startsWith("_wildcard."))return`*.${t.slice(10)}`;return t}async function fB(i,t,n,r){try{let[f,l]=await Promise.all([kn.readFile(t,"utf8"),kn.readFile(n,"utf8")]);return{serverName:i,cert:f,key:l}}catch(f){return T("sni",`skipping ${i}: ${f.message}`,r),null}}async function Y0(i,t){let n=new Map;if(i.certsDir){let f=[];try{f=await kn.readdir(i.certsDir)}catch(l){T("sni",`certsDir read failed (${i.certsDir}): ${l.message}`,t)}for(let l of f){let c=rB(l);if(!c)continue;let $=l.slice(0,-4);n.set(c,{certPath:T0.join(i.certsDir,l),keyPath:T0.join(i.certsDir,`${$}.key`)})}}if(i.domains)for(let[f,l]of Object.entries(i.domains))n.set(f,l);let r=[];for(let[f,l]of n){let c=await fB(f,l.certPath,l.keyPath,t);if(c)r.push(c)}return r}import*as st from"node:fs/promises";import*as B0 from"node:path";var lB=60000,Zy=4096;function cB(i,t){if(!t||t.length===0)return!1;return t.some((n)=>{let r=n.startsWith(".")?n.slice(1):n;return i===r||i.endsWith(`.${r}`)})}function oy(i){if(!i||i.length>253)return!1;if(i.includes("/")||i.includes(":")||i.includes(" "))return!1;if(i.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(i)}class Kf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(i){this.config=i.config,this.certsDir=i.certsDir,this.onCertAdded=i.onCertAdded,this.http01Store=i.http01Store??Or,this.issuer=i.issuer??Hl,this.verbose=i.verbose??!1,this.negativeCacheMs=i.negativeCacheMs??lB;for(let t of i.initial??[])this.certs.set(t.serverName,t)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(i){return this.certs.has(i)}async isApproved(i){if(!oy(i))return!1;if(cB(i,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(i)}catch(t){return T("on-demand",`ask(${i}) threw: ${t.message}`,this.verbose),!1}return!1}async ensureCert(i){if(!this.config.enabled)return!1;if(this.certs.has(i))return!0;if(!oy(i))return!1;let t=this.inFlight.get(i);if(t)return t;let n=this.negativeCache.get(i);if(n!==void 0&&Date.now()<n)return T("on-demand",`${i} negatively cached for ${n-Date.now()}ms`,this.verbose),!1;let r=this.issue(i).finally(()=>{this.inFlight.delete(i)});return this.inFlight.set(i,r),r}async issue(i){if(this.certs.has(i))return!0;if(await this.loadFromDisk(i))return!0;if(!await this.isApproved(i))return T("on-demand",`refused issuance for ${i} (not approved)`,this.verbose),this.cacheNegative(i),!1;try{T("on-demand",`issuing cert for ${i} (staging=${this.config.staging??!1})`,this.verbose);let t=await this.issuer({domains:[i],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(i,t.fullChainPem,t.keyPem);let n={serverName:i,cert:t.fullChainPem,key:t.keyPem};return this.certs.set(i,n),this.negativeCache.delete(i),T("on-demand",`issued + installed cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(t){return this.cacheNegative(i),T("on-demand",`issuance for ${i} failed: ${t.message}`,this.verbose),!1}}cacheNegative(i){if(this.negativeCache.size>=Zy){let t=Date.now();for(let[n,r]of this.negativeCache)if(r<=t)this.negativeCache.delete(n);if(this.negativeCache.size>=Zy){let n=this.negativeCache.keys().next().value;if(n!==void 0)this.negativeCache.delete(n)}}this.negativeCache.set(i,Date.now()+this.negativeCacheMs)}async loadFromDisk(i){let{certPath:t,keyPath:n}=this.pathsFor(i);try{let[r,f]=await Promise.all([st.readFile(t,"utf8"),st.readFile(n,"utf8")]),l={serverName:i,cert:r,key:f};return this.certs.set(i,l),T("on-demand",`adopted existing on-disk cert for ${i}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(i){return{certPath:B0.join(this.certsDir,`${i}.crt`),keyPath:B0.join(this.certsDir,`${i}.key`)}}async persist(i,t,n){await st.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:r,keyPath:f}=this.pathsFor(i);await Promise.all([st.writeFile(r,t,"utf8"),st.writeFile(f,n,{encoding:"utf8",mode:384})])}}import{existsSync as $B,readdirSync as wB,readFileSync as hB,statSync as yB}from"node:fs";import{homedir as tu}from"node:os";import{isAbsolute as uB,join as Tn}from"node:path";var nu=["~/Code"],ru=["localhost","test"],eB=1800000,m0={dirExists:(i)=>{try{return yB(i).isDirectory()}catch{return!1}},fileExists:(i)=>{try{return $B(i)}catch{return!1}},readText:(i)=>{try{return hB(i,"utf8")}catch{return null}}};function C0(i,t){if(i==="~")return t;if(i.startsWith("~/"))return Tn(t,i.slice(2));return i}function AB(i){let t=i.indexOf(":");return(t===-1?i:i.slice(0,t)).toLowerCase()}function py(i){return i.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function EB(i,t){for(let n of t){let r=`.${n}`;if(i.endsWith(r)){let f=i.slice(0,-r.length);if(f.length>0&&!f.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(f))return f}}return null}function TB(i,t){let n=t.readText(Tn(i,"rpx.site.json"));if(n)try{let f=JSON.parse(n);if(f&&typeof f==="object")return f}catch{}let r=t.readText(Tn(i,"package.json"));if(r)try{let f=JSON.parse(r);if(f.rpx&&typeof f.rpx==="object")return f.rpx}catch{}return null}function YB(i){let t=i.selfRegisters??!1;return{command:i.command,env:i.env,urlEnv:i.urlEnv,selfRegisters:t,routes:i.routes??(t?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function BB(i,t){let n=TB(i,t);if(n?.command)return YB(n);let r=t.fileExists(Tn(i,"buddy")),f=t.readText(Tn(i,"package.json")),l=null;if(f)try{l=JSON.parse(f)}catch{l=null}let c={...l?.dependencies??{},...l?.devDependencies??{}};if(r||Object.keys(c).some((w)=>w==="stacks"||w.startsWith("@stacksjs/")))return{command:r?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(l?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function R0(i,t={}){let n={dirExists:t.dirExists??m0.dirExists,fileExists:t.fileExists??m0.fileExists,readText:t.readText??m0.readText},r=t.detect??BB,f=t.homeDir??tu(),l=i.tlds??ru,c=(i.roots??nu).map((e)=>C0(e,f)),$=i.idleTimeoutMs??eB,w=new Map;for(let e of i.sites??[])w.set(e.to,e);let h=(e)=>e.idleTimeoutMs??$;function y(e){let A=vy(w,e);if(!A)return null;let B=uB(A.dir)?A.dir:C0(A.dir,f),E=A.selfRegisters??!1,Y=A.routes??[];if(!E&&Y.length===0)Y=r(B,n)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let m=iu({...A.env??{}},void 0,e);return{host:e,id:py(e),dir:B,command:A.command,env:m,routes:Y,selfRegisters:E,idleTimeoutMs:h(A),source:"config"}}function u(e){let A=EB(e,l);if(!A)return null;for(let B of c){let E=Tn(B,A);if(!n.dirExists(E))continue;let Y=r(E,n);if(!Y)continue;let m=Y.selfRegisters??!1;return{host:e,id:py(e),dir:E,command:Y.command,env:iu({...Y.env??{}},Y.urlEnv,e),routes:m?[]:Y.routes??[],selfRegisters:m,idleTimeoutMs:$,source:"discovered"}}return null}return{resolve(e){let A=AB(e);if(!A)return null;return y(A)??u(A)}}}function mB(i){try{return wB(i,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>t.name)}catch{return[]}}function Lj(i,t={}){let n=t.homeDir??tu(),r=i.tlds??ru,f=(i.roots??nu).map((u)=>C0(u,n)),l=t.readdir??mB,c=R0(i,t),$=[],w=new Set,h=(u)=>{if(u&&!w.has(u.host))w.add(u.host),$.push(u)};for(let u of i.sites??[])if(!u.to.includes("*"))h(c.resolve(u.to));let y=r[0]??"localhost";for(let u of f)for(let e of l(u))h(c.resolve(`${e}.${y}`));return $}function iu(i,t,n){if(!t)return i;let r=`https://${n}`;for(let f of t)if(i[f]===void 0)i[f]=r;return i}import{closeSync as hu,openSync as jB,readFileSync as SB}from"node:fs";import*as yu from"node:fs/promises";import{spawn as aB}from"node:child_process";import{homedir as NB}from"node:os";import*as Dn from"node:path";import*as di from"node:process";import*as zf from"node:net";function lu(i,t,n){return T("port",`Checking if port ${i} is in use on ${t}`,n),new Promise((r)=>{let f=zf.createServer(),l=setTimeout(()=>{T("port",`Checking port ${i} timed out, assuming it's in use`,n),f.close(),r(!0)},3000);f.once("error",(c)=>{if(clearTimeout(l),c.code==="EADDRINUSE")T("port",`Port ${i} is in use`,n),r(!0);else T("port",`Error checking port ${i}: ${c.message}`,n),r(!0)}),f.once("listening",()=>{clearTimeout(l),T("port",`Port ${i} is available`,n),f.close(),r(!1)});try{f.listen(i,t)}catch(c){clearTimeout(l),T("port",`Exception checking port ${i}: ${c}`,n),r(!0)}})}async function s0(i,t,n,r=50){T("port",`Finding available port starting from ${i} (max attempts: ${r})`,n);let f=i,l=0;while(l<r){if(l++,!await lu(f,t,n))return T("port",`Found available port: ${f} after ${l} attempts`,n),f;T("port",`Port ${f} is in use, trying ${f+1} (attempt ${l}/${r})`,n),f++}throw Error(`Unable to find available port after ${r} attempts starting from ${i}`)}function fu(i,t,n=5000,r){return T("port",`Testing connection to ${t}:${i}`,r),new Promise((f)=>{let l=zf.connect({host:t,port:i,timeout:n});l.once("connect",()=>{T("port",`Successfully connected to ${t}:${i}`,r),l.end(),f(!0)}),l.once("timeout",()=>{T("port",`Connection to ${t}:${i} timed out`,r),l.destroy(),f(!1)}),l.once("error",(c)=>{T("port",`Failed to connect to ${t}:${i}: ${c.message}`,r),l.destroy(),f(!1)})})}class cu{usedPorts=new Set;hostname;verbose;maxRetries;constructor(i="0.0.0.0",t,n=50){this.hostname=i,this.verbose=t,this.maxRetries=n}async getNextAvailablePort(i,t=!1){if(this.usedPorts.has(i))return this.findNextAvailablePort(i+1,t);if(await lu(i,this.hostname,this.verbose))return this.findNextAvailablePort(i+1,t);if(t){if(!await fu(i,this.hostname,3000,this.verbose))return T("port",`Port ${i} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(i+1,t)}return this.usedPorts.add(i),i}async findNextAvailablePort(i,t=!1){let n=await s0(i,this.hostname,this.verbose,this.maxRetries);if(t){if(!await fu(n,this.hostname,3000,this.verbose))if(n<i+this.maxRetries)return this.findNextAvailablePort(n+1,t);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(n),n}releasePort(i){T("port",`Releasing port ${i}`,this.verbose),this.usedPorts.delete(i)}}var dj=new cu;import*as Of from"node:fs";import*as Ci from"node:fs/promises";import{homedir as CB}from"node:os";import*as U0 from"node:path";import*as Gf from"node:process";var RB=/^[a-zA-Z0-9._-]+$/;function Ut(){return U0.join(CB(),".stacks","rpx","registry.d")}function j0(i){return typeof i==="string"&&i.length>0&&i.length<=128&&RB.test(i)}function S0(i,t){if(!j0(t))throw Error(`invalid registry id: ${JSON.stringify(t)}`);return U0.join(i,`${t}.json`)}function xi(i){if(!Number.isInteger(i)||i<=0)return!1;try{return Gf.kill(i,0),!0}catch(t){return t.code==="EPERM"}}function $u(i){if(!i||typeof i!=="object")return!1;let t=i,n=t.pid===void 0||typeof t.pid==="number"&&Number.isInteger(t.pid)&&t.pid>0,r=typeof t.from==="string"&&t.from.length>0||Array.isArray(t.from)&&t.from.length>0,f=typeof t.static==="string"||!!t.static&&typeof t.static==="object"&&typeof t.static.dir==="string",l=t.path===void 0||typeof t.path==="string";return typeof t.id==="string"&&j0(t.id)&&(r||f)&&typeof t.to==="string"&&t.to.length>0&&l&&n&&typeof t.createdAt==="string"}async function sB(i){await Ci.mkdir(i,{recursive:!0})}async function wu(i,t=Ut(),n){if(!$u(i))throw Error(`invalid registry entry: ${JSON.stringify(i)}`);await sB(t);let r=S0(t,i.id),f=`${r}.tmp.${Gf.pid}.${Date.now()}`,l=JSON.stringify(i,null,2);try{await Ci.writeFile(f,l,{encoding:"utf8",mode:420}),await Ci.rename(f,r),T("registry",`wrote entry ${i.id} → ${r}`,n)}catch(c){throw await Ci.unlink(f).catch(()=>{}),c}}async function a0(i,t=Ut(),n){let r=S0(t,i);try{await Ci.unlink(r),T("registry",`removed entry ${i}`,n)}catch(f){if(f.code!=="ENOENT")throw f}}async function UB(i,t=Ut(),n){let r=S0(t,i);try{let f=await Ci.readFile(r,"utf8"),l=JSON.parse(f);if(!$u(l))return T("registry",`entry ${i} failed validation, removing`,n),await Ci.unlink(r).catch(()=>{}),null;return l}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return T("registry",`entry ${i} has invalid JSON, removing`,n),await Ci.unlink(r).catch(()=>{}),null;throw f}}async function yt(i=Ut(),t){let n;try{n=await Ci.readdir(i)}catch(f){if(f.code==="ENOENT")return[];throw f}let r=[];for(let f of n){if(!f.endsWith(".json"))continue;let l=f.slice(0,-5);if(!j0(l))continue;let c=await UB(l,i,t);if(c)r.push(c)}return r}async function Vn(i=Ut(),t){let n=await yt(i,t),r=0;for(let f of n){if(f.pid===void 0)continue;if(!xi(f.pid))T("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,t),await a0(f.id,i,t).catch(()=>{}),r++}return r}function Mf(i,t={}){let n=t.dir??Ut(),r=t.debounceMs??100,f=t.pollMs??Math.max(r*2,250),l=t.verbose;Of.mkdirSync(n,{recursive:!0});let c=null,$=!1,w=null,h=!1,y=(Y)=>{return JSON.stringify(Y.map((m)=>({id:m.id,from:m.from,to:m.to,path:m.path,pid:m.pid,pathRewrites:m.pathRewrites,cleanUrls:m.cleanUrls,changeOrigin:m.changeOrigin,static:m.static,loadBalancer:m.loadBalancer})).sort((m,C)=>m.id.localeCompare(C.id)))},u=()=>{if(c=null,$)return;yt(n,l).then((Y)=>{return w=y(Y),i(Y)}).catch((Y)=>{T("registry",`watcher onChange failed: ${Y}`,l)})},e=()=>{if($)return;if(c)clearTimeout(c);c=setTimeout(u,r)},B=setInterval(()=>{if($||h)return;h=!0,yt(n,l).then((Y)=>{if(y(Y)!==w)e()}).catch((Y)=>{T("registry",`watcher poll failed: ${Y}`,l)}).finally(()=>{h=!1})},f),E=Of.watch(n,{persistent:!0},(Y,m)=>{if(m&&/\.tmp\.\d+\.\d+$/.test(m))return;e()});return E.on("error",(Y)=>{T("registry",`watcher error: ${Y}`,l)}),e(),{close:()=>{if($=!0,c)clearTimeout(c);clearInterval(B),E.close()}}}var XB=120000,FB=200,WB=30000,JB=3000,_B=4000;class X0{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(i){this.resolver=i.resolver,this.registryDir=i.registryDir??Ut(),this.rpxDir=i.rpxDir??Dn.join(NB(),".stacks","rpx"),this.verbose=i.verbose??!1,this.startupTimeoutMs=i.startupTimeoutMs??XB,this.pollIntervalMs=i.pollIntervalMs??FB,this.restartDelayMs=i.restartDelayMs??JB,this.killGraceMs=i.killGraceMs??_B,this.launch=i.launcher??KB(this.verbose),this.probePort=i.probePort??IB,this.pickPort=i.pickPort??((n)=>s0(n,"127.0.0.1")),this.isHostRoutable=i.isHostRoutable??(()=>!1),this.onSiteActivating=i.onSiteActivating,this.now=i.now??Date.now,this.writeEntry=i.writeEntry??wu,this.removeEntry=i.removeEntry??a0;let t=i.reapIntervalMs??WB;if(this.reaper=setInterval(()=>{this.reapIdle()},t),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(i){if(this.stopped)return{kind:"unknown"};let t=this.sites.get(i);if(t&&t.status==="failed"&&this.now()-t.failedAt>=this.restartDelayMs)this.sites.delete(i),t=void 0;if(!t){let n=this.resolver.resolve(i);if(!n)return{kind:"unknown"};t=await this.start(n)}if(t.lastAccess=this.now(),t.status==="ready")return{kind:"ready",host:i};if(t.status==="failed")return{kind:"failed",host:i,error:t.error??"failed to start",logTail:this.readLogTail(t)};return{kind:"starting",host:i,sinceMs:this.now()-t.startedAt,source:t.site.source,logTail:this.readLogTail(t,16)}}async start(i){try{this.onSiteActivating?.(i.host)}catch{}let t=new Map;if(!i.selfRegisters)for(let $ of i.routes){if(t.has($.portEnv))continue;let w=await this.pickPort($.defaultPort??3000);t.set($.portEnv,w)}let n=Dn.join(this.rpxDir,"sites",`${i.id}.log`);await yu.mkdir(Dn.dirname(n),{recursive:!0}).catch(()=>{});let r=this.buildEnv(i,t),f=null,l;try{f=this.launch({command:i.command,cwd:i.dir,env:r,logPath:n})}catch($){l=`failed to spawn: ${$.message}`}let c={site:i,status:l?"failed":"starting",handle:f,ports:t,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:l?this.now():0,error:l,logPath:n,exited:!1,ready:Promise.resolve()};if(this.sites.set(i.host,c),l)return F.warn(`rpx: site ${i.host} ${l}`),c;return F.info(`rpx: booting ${i.host} → ${i.command} (${i.dir})`),f.exited.then(($)=>this.onProcessExit(c,$)).catch(()=>{}),c.ready=this.driveReadiness(c).catch(($)=>{T("sites",`readiness loop for ${i.host} threw: ${$}`,this.verbose)}),c}async onProcessExit(i,t){if(i.exited=!0,this.stopped||this.sites.get(i.site.host)!==i)return;if(i.status==="ready"){F.warn(`rpx: ${i.site.host} exited${t!==null?` (code ${t})`:""} — will reboot on next request`),this.sites.delete(i.site.host);for(let n of i.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{})}else if(i.status==="starting")this.fail(i,`process exited${t!==null?` with code ${t}`:""} before becoming ready`)}async driveReadiness(i){let{site:t}=i,n=this.now()+this.startupTimeoutMs,r=t.selfRegisters?()=>this.isHostRoutable(t.host):await this.makeGateProbe(t,i.ports);while(this.now()<n&&!this.stopped){if(i.status!=="starting"||i.exited)return;if(await r()){if(await this.publishRoutes(i),i.status==="starting")i.status="ready",F.success(`rpx: ${t.host} ready`);return}await N0(this.pollIntervalMs)}if(i.status==="starting")this.fail(i,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(i,t){let n=i.routes.filter((f)=>f.readyGate??zt(f.path)==="/").map((f)=>t.get(f.portEnv)).filter((f)=>typeof f==="number"),r=n.length>0?n:[...t.values()];return async()=>{for(let f of r)if(!await this.probePort(f))return!1;return r.length>0}}async publishRoutes(i){let{site:t,ports:n}=i;if(t.selfRegisters||t.routes.length===0)return;let r=t.routes.find((w)=>zt(w.path)==="/")??t.routes[0],f=n.get(r.portEnv);if(f===void 0)return;let l=[];for(let w of t.routes){if(w===r)continue;let h=n.get(w.portEnv);if(h===void 0)continue;l.push({from:zt(w.path),to:`localhost:${h}`,stripPrefix:w.stripPrefix??!1})}let c={id:t.id,from:`localhost:${f}`,to:t.host,cwd:t.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:l.length>0?l:void 0,pid:i.handle?.pid};await this.writeEntry(c,this.registryDir,this.verbose),i.routeIds=[t.id];let $=this.now()+2000;while(this.now()<$&&!this.isHostRoutable(t.host))await N0(50)}fail(i,t){i.status="failed",i.error=t,i.failedAt=this.now(),F.warn(`rpx: site ${i.site.host} failed — ${t}`),this.killProcess(i)}buildEnv(i,t){let n={};for(let[r,f]of Object.entries(di.env))if(typeof f==="string")n[r]=f;Object.assign(n,i.env);for(let[r,f]of t)n[r]=String(f);return n.RPX_SITE_HOST=i.host,n.RPX_SITE_URL=`https://${i.host}`,n}readLogTail(i,t=40){try{return SB(i.logPath,"utf8").split(`
|
|
170
|
-
`).slice(-t).join(`
|
|
171
|
-
`).trim()}catch{return""}}async stop(i){let t=this.sites.get(i);if(!t)return;this.sites.delete(i);for(let n of t.routeIds)await this.removeEntry(n,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(t),F.info(`rpx: stopped ${i}`)}async killProcess(i){let t=i.handle;if(!t)return;i.handle=null;try{t.stop("SIGTERM")}catch{}let n=setTimeout(()=>{try{t.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof n.unref==="function")n.unref();await Promise.race([t.exited.catch(()=>{}),N0(this.killGraceMs+500)]),clearTimeout(n)}async reapIdle(){if(this.stopped)return;let i=this.now();for(let[t,n]of this.sites){let r=n.site.idleTimeoutMs;if(r<=0)continue;let f=i-n.lastAccess;if((n.status==="ready"||i-n.startedAt>this.startupTimeoutMs)&&f>r)T("sites",`reaping ${t} (idle ${Math.round(f/1000)}s)`,this.verbose),await this.stop(t)}}list(){let i=this.now();return[...this.sites.values()].map((t)=>({host:t.site.host,dir:t.site.dir,status:t.status,pid:t.handle?.pid??null,ports:Object.fromEntries(t.ports),uptimeMs:i-t.startedAt,idleMs:i-t.lastAccess,error:t.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((i)=>this.stop(i)))}}function N0(i){return new Promise((t)=>setTimeout(t,i))}async function IB(i){let t=new AbortController,n=setTimeout(()=>t.abort(),2000);try{return await fetch(`http://127.0.0.1:${i}/`,{signal:t.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(n)}}function KB(i){let t=zB();return({command:n,cwd:r,env:f,logPath:l})=>{let c=jB(l,"a");try{let $=aB("sh",["-c",n],{cwd:r,env:f,detached:!0,stdio:["ignore",c,c],...t?{uid:t.uid,gid:t.gid}:{}}),w=$.pid;if(w===void 0)throw Error("spawn returned no pid");let h=new Promise((y)=>{$.once("exit",(u)=>{y(u)}),$.once("error",()=>{y(null)})}).finally(()=>{try{hu(c)}catch{}});return T("sites",`spawned pid ${w}: sh -c ${n} (cwd ${r})`,i),{pid:w,exited:h,stop:(y="SIGTERM")=>{try{di.kill(-w,y)}catch{try{$.kill(y)}catch{}}}}}catch($){try{hu(c)}catch{}throw $}}}function zB(){if(di.platform==="win32")return null;if(!(typeof di.getuid==="function"&&di.getuid()===0))return null;let t=Number.parseInt(di.env.SUDO_UID??"",10),n=Number.parseInt(di.env.SUDO_GID??"",10);if(!Number.isInteger(t)||t<=0||!Number.isInteger(n)||n<=0)return null;return{uid:t,gid:n}}function Yn(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var OB=`
|
|
172
|
-
:root { color-scheme: light dark }
|
|
173
|
-
* { box-sizing: border-box }
|
|
174
|
-
body {
|
|
175
|
-
margin: 0; min-height: 100vh; display: grid; place-items: center;
|
|
176
|
-
font: 15px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
177
|
-
background: #0b0c0f; color: #e7e9ee;
|
|
178
|
-
}
|
|
179
|
-
.card { width: min(92vw, 540px); padding: 2.25rem 2.5rem; }
|
|
180
|
-
.row { display: flex; align-items: center; gap: .75rem; }
|
|
181
|
-
h1 { font-size: 1.15rem; margin: 0; font-weight: 600; letter-spacing: -.01em }
|
|
182
|
-
p { margin: .5rem 0 0; color: #9aa1ad }
|
|
183
|
-
code { color: #cbd2dc; background: #16181d; padding: .1rem .4rem; border-radius: 5px }
|
|
184
|
-
pre {
|
|
185
|
-
margin: 1.25rem 0 0; padding: 1rem; max-height: 40vh; overflow: auto;
|
|
186
|
-
background: #16181d; border: 1px solid #23262d; border-radius: 8px;
|
|
187
|
-
font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color: #aeb6c2;
|
|
188
|
-
white-space: pre-wrap; word-break: break-word;
|
|
189
|
-
}
|
|
190
|
-
.spinner {
|
|
191
|
-
width: 16px; height: 16px; border-radius: 50%;
|
|
192
|
-
border: 2px solid #3a3f4b; border-top-color: #8ab4f8;
|
|
193
|
-
animation: spin .8s linear infinite;
|
|
194
|
-
}
|
|
195
|
-
.dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
|
|
196
|
-
@keyframes spin { to { transform: rotate(360deg) } }
|
|
197
|
-
`;function uu(i,t,n){return`<!doctype html>
|
|
198
|
-
<html lang="en">
|
|
199
|
-
<head>
|
|
200
|
-
<meta charset="utf-8">
|
|
201
|
-
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
202
|
-
${n>0?`<meta http-equiv="refresh" content="${n}">`:""}
|
|
203
|
-
<title>${Yn(i)}</title>
|
|
204
|
-
<style>${OB}</style>
|
|
205
|
-
</head>
|
|
206
|
-
<body><main class="card">${t}</main></body>
|
|
207
|
-
</html>`}function eu(i){let t=Math.max(1,Math.round(i.sinceMs/1000)),n=i.logTail?`<pre>${Yn(i.logTail)}</pre>`:"",r=`
|
|
208
|
-
<div class="row"><div class="spinner"></div><h1>Starting ${Yn(i.host)}…</h1></div>
|
|
209
|
-
<p>rpx is booting this site's dev server on demand. This page reloads itself —
|
|
210
|
-
it'll switch to the app as soon as it's ready (usually a few seconds).</p>
|
|
211
|
-
<p>Booting for ${t}s.</p>
|
|
212
|
-
${n}`;return new Response(uu(`Starting ${i.host}`,r,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function Au(i){let t=i.logTail?`<pre>${Yn(i.logTail)}</pre>`:"<p>No output was captured.</p>",n=`
|
|
213
|
-
<div class="row"><div class="dot"></div><h1>${Yn(i.host)} failed to start</h1></div>
|
|
214
|
-
<p>${Yn(i.error)}</p>
|
|
215
|
-
${t}
|
|
216
|
-
<p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(uu(`${i.host} failed`,n,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var GB=5000;function Ri(){return bi.join(Cu(),".stacks","rpx")}function gf(i=Ri()){return bi.join(i,"daemon.pid")}async function mn(i=Ri()){try{let t=await Ai.readFile(gf(i),"utf8"),n=Number.parseInt(t.trim(),10);if(!Number.isFinite(n)||n<=0)return null;return n}catch(t){if(t.code==="ENOENT")return null;throw t}}async function MB(i=Ri()){let t=await mn(i);return t!==null&&xi(t)}async function Ru(i=Ri()){await Ai.mkdir(i,{recursive:!0});let t=gf(i);while(!0){try{let r=await Ai.open(t,"wx");try{await r.write(`${R.pid}
|
|
217
|
-
`)}finally{await r.close()}return t}catch(r){if(r.code!=="EEXIST")throw r}let n=await mn(i);if(n!==null&&xi(n))throw Error(`rpx daemon already running (pid=${n})`);await Ai.unlink(t).catch(()=>{})}}async function Bn(i=Ri()){await Ai.unlink(gf(i)).catch(()=>{})}var qf=new Map;function Lf(i){for(let[t,n]of qf)if(!i.has(t))c0(n),qf.delete(t)}function HB(i,t){let n=Uy(t??"localhost:1");if(i.upstreams.length!==n.length)return!1;return i.upstreams.every((r,f)=>r.url===n[f])}function su(i){let t=i.cleanUrls??!1,n=zt(i.path),r=Wy(i.auth);if(i.static)return{static:Ly(i.static,t),cleanUrls:t,basePath:n,auth:r};let f=i.from??"localhost:1",l=jy(f),c=new URL(l.startsWith("http")?l:`http://${l}`),$=qf.get(i.id);if($&&!HB($,f))c0($),$=void 0;if(!$)$=Sy(f,i.loadBalancer),Ny($),qf.set(i.id,$);return{sourceHost:c.host,upstreamPool:$,cleanUrls:t,changeOrigin:i.changeOrigin??!1,pathRewrites:i.pathRewrites,basePath:n,auth:r}}function qB(i){return i.find((n)=>!/^api\./.test(n)&&!/^docs\./.test(n)&&!/^dashboard\./.test(n))??i[0]??"rpx.localhost"}async function Hf(i,t,n=[],r=!1){let f=await yt(t,i.verbose),l=[...new Set([...f.map((y)=>y.to).filter(Boolean),...n])],c=qB(l),$=[...new Set([c,...l,"rpx.localhost"])],w=my(l,c,i.verbose);if(typeof i.https==="object"&&typeof w.https==="object")w.https={...w.https,...i.https};let h=await f0(w);if(h&&(r||!Qc(t0,$)))T("daemon",`regenerating shared cert for host(s): ${$.join(", ")}`,i.verbose),r0(),h=null;if(!h)T("daemon","no usable cert on disk, generating one via tlsx",i.verbose),await Ry({...w,forceRegenerate:!0}),h=await f0(w);if(!h)throw Error("failed to bootstrap TLS for rpx daemon");return h}async function LB(i,t,n,r){let f=R.env.SUDO_PASSWORD,l=R.env.HOME??Cu(),c=[R.execPath,...R.argv.slice(1)],$=[`HOME=${l}`,`PATH=${R.env.PATH??""}`];if(r)$.push("RPX_VERBOSE=1");for(let[B,E]of Object.entries(R.env))if(E!==void 0&&B!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(B))$.push(`${B}=${E}`);let w=f?["-S","-p","","env",...$,...c]:["-n","env",...$,...c];T("daemon",`elevating daemon via sudo for privileged ports ${t}/${n}`,r);let h=mu("sudo",w,{detached:!0,stdio:["pipe","ignore","ignore"]}),y=null,u=null;if(h.once("error",(B)=>{y=B}),h.once("exit",(B)=>{u=B??0}),f&&h.stdin)h.stdin.write(`${f}
|
|
218
|
-
`),h.stdin.end();h.unref();let e=gf(i),A=Date.now()+15000;while(Date.now()<A){if(y)throw y;let B=await mn(i);if(B!==null&&xi(B)){if(r)F.success(`rpx daemon elevated to root (pid=${B}, https on :${t})`);return{httpsPort:t,httpPort:n,pidPath:e,done:Promise.resolve(),stop:async()=>{try{R.kill(B,"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((E)=>setTimeout(E,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${i})`)}var Eu=!1;function F0(){if(Eu)return;Eu=!0,R.on("uncaughtException",(i)=>{F.error(`rpx daemon: uncaught exception (continuing): ${i?.stack??i}`)}),R.on("unhandledRejection",(i)=>{F.error(`rpx daemon: unhandled rejection (continuing): ${i}`)})}function Uu(i,t,n){let r;try{r=new URL(i.url)}catch{return new Response("Bad Request",{status:400})}let f=(i.headers.get("host")??r.hostname).split(":")[0];if(r.pathname.startsWith("/.well-known/acme-challenge/")){if(t){let l=t.challengeStore.handlePath(r.pathname);if(l!==void 0)return new Response(l,{status:200,headers:{"content-type":"text/plain"}})}if(n){let l=Py(n,r.pathname);if(l!=null)return new Response(l,{status:200,headers:{"content-type":"text/plain"}})}if(t)return new Response("challenge not found",{status:404})}if(t&&!t.hasCert(f))t.ensureCert(f).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${f}${r.pathname}${r.search}`}})}async function jS(i={}){F0();let t=i.verbose??!1,n=i.rpxDir??Ri(),r=i.registryDir??bi.join(n,"registry.d"),f=i.httpsPort??443,l=i.httpPort??80,c=i.hostname??"0.0.0.0",$=i.gcIntervalMs??GB;if(R.env.RPX_DAEMON_WORKER==="1")return dB({rpxDir:R.env.RPX_WORKER_RPXDIR??n,registryDir:R.env.RPX_WORKER_REGISTRYDIR??r,httpsPort:Number.parseInt(R.env.RPX_WORKER_HTTPSPORT??"",10)||f,hostname:R.env.RPX_WORKER_HOSTNAME??c,verbose:R.env.RPX_WORKER_VERBOSE==="1"||t});let w=f>0&&f<1024||l>0&&l<1024,h=typeof R.getuid==="function"&&R.getuid()===0;if(R.platform!=="win32"&&w&&!h)return LB(n,f,l,t);let y=Math.max(1,i.workers??(Number.parseInt(R.env.RPX_WORKERS??"",10)||1));if(y>1){if(i.onDemandSites?.enabled)F.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return kB(i,{rpxDir:n,registryDir:r,httpsPort:f,httpPort:l,hostname:c,verbose:t,gcIntervalMs:$,workers:y})}let u=await Ru(n),e=new Map,A=(s,W)=>E0(e,s,W);function B(s){e=e0(s.map((Di)=>({host:Di.to,path:Di.path,route:su(Di)}))),Lf(new Set(s.map((Di)=>Di.id)));let W=Array.from(e.keys());T("daemon",`routing table now covers ${W.length} host(s): ${W.join(", ")||"<empty>"}`,t)}await Vn(r,t).catch((s)=>{T("daemon",`initial gc failed: ${s}`,t)});let E=await yt(r,t);B(E),await Rn({rpxDir:n,verbose:t}).catch((s)=>{T("daemon",`DNS reconcile on start failed: ${s}`,t)}),await bn(E,{rpxDir:n,verbose:t,ownerPid:R.pid}).catch((s)=>{T("daemon",`DNS setup on start failed: ${s}`,t)});let Y=[];if(i.productionCerts){if(Y=await Y0(i.productionCerts,t),t&&Y.length>0)F.info(`SNI: serving ${Y.length} real cert(s): ${Y.map((s)=>s.serverName).join(", ")}`)}let m=new Set,C=null,a;if(i.onDemandSites?.enabled){if(C=new X0({resolver:R0(i.onDemandSites),registryDir:r,rpxDir:n,verbose:t,startupTimeoutMs:i.onDemandSites.startupTimeoutMs,isHostRoutable:(s)=>A0(e,s)!==void 0,onSiteActivating:(s)=>{Xt(s)}}),a=async(s)=>{let W=await C.onRequest(s);switch(W.kind){case"ready":return{retry:!0};case"starting":return eu({host:W.host,sinceMs:W.sinceMs,logTail:W.logTail});case"failed":return Au({host:W.host,error:W.error,logTail:W.logTail});case"unknown":default:return}},t)F.info("rpx: on-demand sites enabled")}let N=h0(A,t,a),j=y0(t),X=null;if(Y.length===0)X=await Hf(i,r);let M=i.onDemandTls,o=M?.enabled?new Kf({config:M,certsDir:M.certsDir??i.productionCerts?.certsDir??bi.join(n,"on-demand-certs"),initial:Y,verbose:t,onCertAdded:(s)=>{Gt(s)}}):null;function ki(s){if(s.length>0)return s.map((W)=>({serverName:W.serverName,cert:W.cert,key:W.key}));return{key:X.key,cert:X.cert,ca:X.ca,requestCert:!1,rejectUnauthorized:!1}}function vn(s){return Bun.serve({port:f,hostname:c,reusePort:Bu(),tls:ki(s),fetch(W,Di){return N(W,Di)},websocket:j,error(W){return T("daemon",`https server error: ${W}`,t),new Response(`Server Error: ${W.message}`,{status:500})}})}let St=(s)=>[...new Set(s.map((W)=>W.to).filter(Boolean))],Ot=(s)=>{if(!X)return Y;return By([...St(s),...m,"rpx.localhost"],X)},et=vn(o?o.sniEntries():Y.length>0?Y:Ot(E)),at=null,Nt=!1;async function Gt(s){if(Vi)return;if(at=s,Nt)return;Nt=!0;try{while(!Vi&&at){let W=at;at=null,T("daemon",`rebuilding :443 with ${W.length} SNI cert(s)`,t),et.stop(!1);let Di,Qf=!1,H0=60,Mu=500;for(let Pf=0;!Vi&&!Qf;Pf++)try{et=vn(W),Qf=!0;break}catch(Hu){if(Di=Hu,Pf>=H0)break;await new Promise((qu)=>setTimeout(qu,Math.min(25*2**Math.min(Pf,4),Mu)))}if(!Qf)F.error(`rpx: CRITICAL — could not rebind :443 after ${H0} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Di?.message}`)}}finally{Nt=!1}}let Qi=null;if(l>0)Qi=Bun.serve({port:l,hostname:c,fetch(s){return Uu(s,o,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(t)F.success(`rpx daemon listening on https://${c}:${f}${Qi?` (http→https on :${l})`:""}`),F.info(`pid file: ${u}`),F.info(`registry: ${r}`);async function J(s){if(Vi||Y.length>0||o||!X)return;try{X=await Hf(i,r,[...m]),await Gt(Ot(s))}catch(W){T("daemon",`TLS sync on registry change failed: ${W}`,t)}}async function Xt(s){if(Vi||Y.length>0||o||!X||!s)return;if(m.has(s))return;m.add(s);try{X=await Hf(i,r,[...m],!0);let W=await yt(r,t);await Gt(Ot(W))}catch(W){T("daemon",`dev cert refresh for ${s} failed: ${W}`,t)}}let Df=Mf((s)=>{B(s),J(s),bn(s,{rpxDir:n,verbose:t,ownerPid:R.pid}).catch((W)=>{T("daemon",`DNS sync on registry change failed: ${W}`,t)})},{dir:r,verbose:t}),Mt=setInterval(()=>{Vn(r,t).then((s)=>{if(s>0)T("daemon",`gc reaped ${s} stale entries`,t)}).catch((s)=>{T("daemon",`periodic gc failed: ${s}`,t)})},$);if(typeof Mt.unref==="function")Mt.unref();let Vi=!1,sn,Ht=new Promise((s)=>{sn=s});async function bf(){if(Vi)return Ht;if(Vi=!0,clearInterval(Mt),Df.close(),await C?.stopAll().catch((s)=>{T("daemon",`site supervisor stopAll failed: ${s}`,t)}),et.stop(!1),Qi?.stop(!1),await Cn({rpxDir:n,verbose:t}).catch((s)=>{T("daemon",`DNS teardown failed: ${s}`,t)}),Lf(new Set),await Bn(n),t)F.info("rpx daemon stopped");return sn(),Ht}let M0=(s)=>{T("daemon",`received ${s}, shutting down`,t),bf().catch(()=>{})};return R.once("SIGINT",M0),R.once("SIGTERM",M0),{stop:bf,done:Ht,httpsPort:typeof et.port==="number"?et.port:f,httpPort:Qi&&typeof Qi.port==="number"?Qi.port:l,pidPath:u,ensureCert:(s)=>o?o.ensureCert(s):Promise.resolve(!1),listSites:()=>C?.list()??[]}}function W0(i){return bi.join(i,"cluster-sni.json")}async function Tu(i,t,n){let r=W0(i),f=`${r}.${R.pid}.tmp`;await Ai.writeFile(f,JSON.stringify({sni:t,dev:n}),"utf8"),await Ai.rename(f,r)}async function Yu(i){try{return JSON.parse(await Ai.readFile(W0(i),"utf8"))}catch{return{sni:[],dev:null}}}function gB(i){if(i.sni.length>0)return i.sni.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key}));if(i.dev)return{key:i.dev.key,cert:i.dev.cert,ca:i.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function xB(){let i=R.execPath,t=R.env.RPX_WORKER_BIN;if(t)return[i,t,"daemon:start"];let n=bi.basename(i).toLowerCase();if((n==="bun"||n==="node"||n.startsWith("bun-"))&&R.argv[1])return[i,R.argv[1],"daemon:start"];return[i,"daemon:start"]}async function dB(i){F0();let{rpxDir:t,registryDir:n,httpsPort:r,hostname:f,verbose:l}=i,c=new Map,$=(j,X)=>E0(c,j,X),w=(j)=>{c=e0(j.map((X)=>({host:X.to,path:X.path,route:su(X)}))),Lf(new Set(j.map((X)=>X.id)))};w(await yt(n,l));let h=h0($,l),y=y0(l),u=!1,e=(j)=>Bun.serve({port:r,hostname:f,reusePort:!0,tls:gB(j),fetch(X,M){return h(X,M)},websocket:y,error(X){return T("daemon",`worker https error: ${X}`,l),new Response(`Server Error: ${X.message}`,{status:500})}}),A=e(await Yu(t));async function B(){if(u)return;let j=await Yu(t),X=null;for(let o=0;o<20&&!u;o++)try{X=e(j);break}catch{await new Promise((ki)=>setTimeout(ki,25))}if(!X){T("daemon","worker reloadTls: could not bind new listener; keeping current",l);return}let M=A;A=X,M.stop(!1)}let E=Mf((j)=>w(j),{dir:n,verbose:l}),Y=()=>{B().catch(()=>{})};R.on("SIGHUP",Y);let m,C=new Promise((j)=>{m=j});async function a(){if(u)return C;return u=!0,R.off("SIGHUP",Y),E.close(),A.stop(!1),Lf(new Set),m(),C}let N=()=>{a().then(()=>R.exit(0)).catch(()=>R.exit(0))};if(R.once("SIGTERM",N),R.once("SIGINT",N),l)F.success(`rpx worker (pid ${R.pid}) serving :${r}`);return{stop:a,done:C,httpsPort:typeof A.port==="number"?A.port:r,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function kB(i,t){F0();let{rpxDir:n,registryDir:r,httpsPort:f,httpPort:l,hostname:c,verbose:$,gcIntervalMs:w,workers:h}=t,y=await Ru(n),u=[];if(i.productionCerts)u=await Y0(i.productionCerts,$);let e=null;if(u.length===0)e=await Hf(i,r);let A=e?{key:e.key,cert:e.cert,ca:Array.isArray(e.ca)?e.ca.join(`
|
|
219
|
-
`):e.ca}:null,B=!1,E=[];function Y(J){for(let Xt of E)try{Xt.kill(J)}catch{}}async function m(J){await Tu(n,J,A),Y("SIGHUP")}let C=i.onDemandTls,a=C?.enabled?new Kf({config:C,certsDir:C.certsDir??i.productionCerts?.certsDir??bi.join(n,"on-demand-certs"),initial:u,verbose:$,onCertAdded:(J)=>{m(J)}}):null;await Tu(n,a?a.sniEntries():u,A);let N=await yt(r,$);await Rn({rpxDir:n,verbose:$}).catch((J)=>{T("daemon",`DNS reconcile on start failed: ${J}`,$)}),await bn(N,{rpxDir:n,verbose:$,ownerPid:R.pid}).catch((J)=>{T("daemon",`DNS setup on start failed: ${J}`,$)}),await Vn(r,$).catch(()=>{});let j=Mf((J)=>{bn(J,{rpxDir:n,verbose:$,ownerPid:R.pid}).catch((Xt)=>{T("daemon",`DNS sync on registry change failed: ${Xt}`,$)})},{dir:r,verbose:$}),X=setInterval(()=>{Vn(r,$).catch(()=>{})},w);X.unref?.();let M=null;if(l>0)M=Bun.serve({port:l,hostname:c,fetch(J){return Uu(J,a,i.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let o=10,ki=60000,vn=30000,St=0,Ot=Date.now();function et(){if(B)return;let J={...R.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:n,RPX_WORKER_REGISTRYDIR:r,RPX_WORKER_HTTPSPORT:String(f),RPX_WORKER_HOSTNAME:c,RPX_WORKER_VERBOSE:$?"1":"0"},Xt=Bun.spawn(xB(),{env:J,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(Df,Mt){if(B)return;let Vi=E.indexOf(Df);if(Vi!==-1)E.splice(Vi,1);let sn=Date.now();if(sn-Ot>ki)Ot=sn,St=0;if(St++,St>o){F.error(`rpx: worker keeps exiting (code ${Mt}); giving up after ${o} restarts in ${Math.round(ki/1000)}s`);return}let Ht=Math.min(vn,100*2**Math.min(St,8));T("daemon",`worker exited (code ${Mt}); respawning in ${Ht}ms (restart ${St}/${o})`,$),setTimeout(et,Ht).unref?.()}});E.push(Xt)}for(let J=0;J<h;J++)et();if($)F.success(`rpx coordinator listening on https://${c}:${f} via ${h} worker(s)${M?` (http→https on :${l})`:""}`),F.info(`pid file: ${y}`);let at,Nt=new Promise((J)=>{at=J});async function Gt(){if(B)return Nt;if(B=!0,clearInterval(X),j.close(),M?.stop(!1),Y("SIGTERM"),await Promise.race([Promise.all(E.map((J)=>J.exited)),new Promise((J)=>setTimeout(J,3000))]),Y("SIGKILL"),await Cn({rpxDir:n,verbose:$}).catch((J)=>{T("daemon",`DNS teardown failed: ${J}`,$)}),await Bn(n),await Ai.unlink(W0(n)).catch(()=>{}),$)F.info("rpx coordinator stopped");return at(),Nt}let Qi=(J)=>{T("daemon",`coordinator received ${J}, shutting down`,$),Gt().catch(()=>{})};return R.once("SIGINT",Qi),R.once("SIGTERM",Qi),{stop:Gt,done:Nt,httpsPort:f,httpPort:l,pidPath:y,ensureCert:(J)=>a?a.ensureCert(J):Promise.resolve(!1),listSites:()=>[]}}function VB(){let i=R.execPath,t=bi.basename(i).toLowerCase();if((t==="bun"||t==="node"||t.startsWith("bun-"))&&R.argv[1])return[i,R.argv[1],"daemon:start"];return[i,"daemon:start"]}async function SS(i={}){let t=i.rpxDir??Ri(),n=i.verbose??!1;await Rn({rpxDir:t,verbose:n}).catch((y)=>{T("daemon",`DNS reconcile before ensureDaemonRunning: ${y}`,n)});let r=await mn(t);if(r!==null&&xi(r))return T("daemon",`ensureDaemonRunning: already running pid=${r}`,n),{pid:r,spawned:!1};if(r!==null)T("daemon",`ensureDaemonRunning: clearing stale pid=${r}`,n),await Bn(t);await Ai.mkdir(t,{recursive:!0});let f=i.spawnCommand??VB();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");T("daemon",`spawning daemon: ${f.join(" ")}`,n);let l=mu(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:i.spawnCwd??R.cwd(),env:i.spawnEnv?{...R.env,...i.spawnEnv}:R.env});l.unref();let c=null;l.once("error",(y)=>{c=y});let $=i.startupTimeoutMs??5000,w=i.pollIntervalMs??50,h=Date.now()+$;while(Date.now()<h){if(c)throw c;let y=await mn(t);if(y!==null&&xi(y))return T("daemon",`daemon registered with pid=${y}`,n),{pid:y,spawned:!0};await new Promise((u)=>setTimeout(u,w))}if(c)throw c;throw Error(`rpx daemon failed to start within ${$}ms (rpxDir=${t})`)}async function aS(i={}){let t=i.rpxDir??Ri(),n=i.verbose??!1,r=i.timeoutMs??5000,f=i.pollIntervalMs??50,l=i.forceAfterTimeout??!0,c=await mn(t);if(c===null||!xi(c)){if(c!==null)await Bn(t);return await Rn({rpxDir:t,verbose:n}).catch(()=>{}),{stopped:!1,pid:c,forced:!1}}try{R.kill(c,"SIGTERM")}catch(w){if(w.code==="ESRCH")return await Bn(t),{stopped:!1,pid:c,forced:!1};throw w}let $=Date.now()+r;while(Date.now()<$){if(!xi(c))return T("daemon",`daemon pid=${c} stopped cleanly`,n),{stopped:!0,pid:c,forced:!1};await new Promise((w)=>setTimeout(w,f))}if(!l)throw Error(`rpx daemon (pid=${c}) did not exit within ${r}ms`);T("daemon",`daemon pid=${c} did not exit, escalating to SIGKILL`,n);try{R.kill(c,"SIGKILL")}catch(w){if(w.code!=="ESRCH")throw w}return await Bn(t),await Cn({rpxDir:t,verbose:n}).catch((w)=>{T("daemon",`DNS teardown after SIGKILL: ${w}`,n)}),{stopped:!0,pid:c,forced:!0}}async function NS(i={}){let t=i.rpxDir??Ri();if(await MB(t))return;await Rn({rpxDir:t,verbose:i.verbose})}import*as jt from"node:fs/promises";import{homedir as DB}from"node:os";import*as J0 from"node:path";var xf=1,bB="dns-state.json",ju=["com","test","dev","app","page","local","localhost","example","invalid"];function Su(){return J0.join(DB(),".stacks","rpx")}function _0(i=Su()){return J0.join(i,bB)}async function df(i=Su()){try{let t=await jt.readFile(_0(i),"utf8"),n=JSON.parse(t);if(n.version!==xf||!Array.isArray(n.resolvers))return null;return{version:xf,resolvers:n.resolvers.filter((r)=>typeof r==="string"),domains:Array.isArray(n.domains)?n.domains.filter((r)=>typeof r==="string"):[],ownerPid:typeof n.ownerPid==="number"?n.ownerPid:null,updatedAt:typeof n.updatedAt==="string"?n.updatedAt:""}}catch(t){if(t.code==="ENOENT")return null;throw t}}async function au(i,t){await jt.mkdir(i,{recursive:!0}),await jt.writeFile(_0(i),`${JSON.stringify(t,null,2)}
|
|
220
|
-
`,"utf8")}async function I0(i){await jt.rm(_0(i),{force:!0})}function Nu(i){let t=i.trim().toLowerCase().replace(/\.$/,"");if(!t||t.includes("127.0.0.1"))return null;if(t==="localhost"||t.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(t))return null;if(!/^[a-z0-9.-]+$/.test(t))return null;return t}function QB(i){let t=Nu(i);if(!t)return null;let n=t.split(".");if(n.length<2)return null;return n.slice(-2).join(".")}function K0(i){let t=new Set;for(let n of i){let r=QB(n);if(r)t.add(r)}return Array.from(t).sort()}function z0(i){let t=new Set;for(let n of i){let r=Nu(n);if(r)t.add(r)}return Array.from(t).sort()}var Vf=15353,PB="# managed-by: rpx",Ju="/etc/resolver",si=null,kf=new Set;function _u(i){return{id:i.readUInt16BE(0),flags:i.readUInt16BE(2),qdcount:i.readUInt16BE(4),ancount:i.readUInt16BE(6),nscount:i.readUInt16BE(8),arcount:i.readUInt16BE(10)}}function Iu(i,t,n=0){let r=[],f=t,l=0;while(!0){if(f>=i.length||++l>128)break;let c=i[f];if(c===0){f++;break}if((c&192)===192){if(f+1>=i.length||n>=10)break;let $=i.readUInt16BE(f)&16383,{name:w}=Iu(i,$,n+1);if(w)r.push(w);f+=2;break}if(f++,f+c>i.length)break;r.push(i.subarray(f,f+c).toString("ascii")),f+=c}return{name:r.join("."),newOffset:f}}function vB(i,t){let{name:n,newOffset:r}=Iu(i,t),f=i.readUInt16BE(r),l=i.readUInt16BE(r+2);return{question:{name:n,type:f,class:l},newOffset:r+4}}function Qn(i){let t=i.split("."),n=[];for(let r of t)n.push(Buffer.from([r.length])),n.push(Buffer.from(r,"ascii"));return n.push(Buffer.from([0])),Buffer.concat(n)}function ZB(i,t,n){let r=[],f=Buffer.alloc(12);f.writeUInt16BE(i,0),f.writeUInt16BE(33152,2),f.writeUInt16BE(1,4),f.writeUInt16BE(1,6),f.writeUInt16BE(0,8),f.writeUInt16BE(0,10),r.push(f),r.push(Qn(t.name));let l=Buffer.alloc(4);l.writeUInt16BE(t.type,0),l.writeUInt16BE(t.class,2),r.push(l),r.push(Qn(t.name));let c=Buffer.alloc(10);if(c.writeUInt16BE(t.type,0),c.writeUInt16BE(1,2),c.writeUInt32BE(300,4),t.type===1){c.writeUInt16BE(4,8),r.push(c);let $=n.split(".").map((w)=>Number.parseInt(w,10));r.push(Buffer.from($))}else if(t.type===28)c.writeUInt16BE(16,8),r.push(c),r.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return f.writeUInt16BE(33155,2),f.writeUInt16BE(0,6),Buffer.concat([f,Qn(t.name),l]);return Buffer.concat(r)}function oB(i,t){let n=[],r=Buffer.alloc(12);r.writeUInt16BE(i,0),r.writeUInt16BE(33155,2),r.writeUInt16BE(1,4),r.writeUInt16BE(0,6),r.writeUInt16BE(0,8),r.writeUInt16BE(0,10),n.push(r),n.push(Qn(t.name));let f=Buffer.alloc(4);return f.writeUInt16BE(t.type,0),f.writeUInt16BE(t.class,2),n.push(f),Buffer.concat(n)}async function pB(i,t){if(ut.platform!=="darwin")return!1;let n=z0(i);if(n.length===0)return!1;if(si){for(let r of n)kf.add(r);return T("dns","DNS server already running — merged domains",t),!0}return kf=new Set(n),new Promise((r)=>{si=Xu.createSocket("udp4"),si.on("error",(f)=>{T("dns",`DNS server error: ${f.message}`,t),si?.close(),si=null,r(!1)}),si.on("message",(f,l)=>{try{let c=_u(f),{question:$}=vB(f,12);T("dns",`Query for ${$.name} type ${$.type} from ${l.address}`,t);let w=$.name.toLowerCase(),h=!1;for(let u of kf)if(w===u||w.endsWith(`.${u}`)){h=!0;break}let y;if(h&&($.type===1||$.type===28))y=ZB(c.id,$,"127.0.0.1"),T("dns",`Responding with localhost for ${$.name}`,t);else y=oB(c.id,$),T("dns",`NXDOMAIN for ${$.name}`,t);si?.send(y,l.port,l.address)}catch(c){T("dns",`Error processing DNS query: ${c}`,t)}}),si.on("listening",()=>{let f=si?.address();T("dns",`DNS server listening on ${f?.address}:${f?.port}`,t),r(!0)});try{si.bind(Vf,"127.0.0.1")}catch(f){T("dns",`Failed to bind DNS server: ${f}`,t),r(!1)}})}function Ku(i){if(si)T("dns","Stopping DNS server",i),si.close(),si=null,kf=new Set}function OS(){return si!==null}async function im(i,t=500){let n=i.trim().toLowerCase().replace(/\.$/,"");if(!n)return!1;return new Promise((r)=>{let f=Xu.createSocket("udp4"),l=setTimeout(()=>{f.close(),r(!1)},t);f.on("message",($)=>{clearTimeout(l),f.close();try{let w=_u($);r(w.ancount>0)}catch{r(!1)}}),f.on("error",()=>{clearTimeout(l),f.close(),r(!1)});let c=tm(n,1);f.send(c,Vf,"127.0.0.1",($)=>{if($)clearTimeout(l),f.close(),r(!1)})})}function tm(i,t){let n=Buffer.alloc(12);n.writeUInt16BE(1,0),n.writeUInt16BE(256,2),n.writeUInt16BE(1,4);let r=Buffer.concat([Qn(i),Buffer.from([0,t,0,1])]);return Buffer.concat([n,r])}function nm(){return`${PB}
|
|
221
|
-
nameserver 127.0.0.1
|
|
222
|
-
port ${Vf}
|
|
223
|
-
`}function Pn(i){return Wu.join(Ju,i)}function rm(i){return i.includes("127.0.0.1")&&i.includes(String(Vf))}async function fm(i){try{return await Fu.readFile(Pn(i),"utf8")}catch(t){if(t.code==="ENOENT")return null;throw t}}async function O0(i){if(ut.platform!=="darwin")return;let{execSudoSync:t,getSudoPassword:n,isProcessElevated:r}=await import("./chunk-6nvjwawp.js");if(!r()&&!n()){T("dns","Cannot flush DNS cache without SUDO_PASSWORD",i);return}try{t("dscacheutil -flushcache"),t("killall -HUP mDNSResponder 2>/dev/null || true"),T("dns","DNS cache flushed",i)}catch(f){T("dns",`Could not flush DNS cache: ${f}`,i)}}function zu(i){if(!/^[a-z0-9.-]+$/.test(i))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(i)}`)}async function lm(i,t){zu(i);let{execSudoSync:n}=await import("./chunk-6nvjwawp.js"),r=nm().replace(/\n/g,"\\n"),f=`bash -c 'mkdir -p ${Ju} && printf "%b" "${r}" > ${Pn(i)}'`;n(f),T("dns",`Created ${Pn(i)}`,t)}async function cm(i,t){zu(i);let{execSudoSync:n}=await import("./chunk-6nvjwawp.js");n(`rm -f ${Pn(i)}`),T("dns",`Removed ${Pn(i)}`,t)}async function GS(i,t){return Gu({domains:t??[],verbose:i})}async function $m(i,t){if(ut.platform!=="darwin")return!0;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-6nvjwawp.js");if(!r()&&!n())return T("dns","SUDO_PASSWORD not set, cannot create resolver files",t),!1;try{for(let f of i)await lm(f,t);return await O0(t),!0}catch(f){return T("dns",`Failed to create resolver file: ${f}`,t),!1}}async function G0(i,t){if(ut.platform!=="darwin")return;let{getSudoPassword:n,isProcessElevated:r}=await import("./chunk-6nvjwawp.js");if(!r()&&!n())return;try{for(let f of i)await cm(f,t);await O0(t)}catch(f){T("dns",`Failed to remove resolver files: ${f}`,t)}}async function Ou(i){if(ut.platform!=="darwin")return[];let t=[];for(let n of ju){let r=await fm(n);if(r&&rm(r))await G0([n],i),t.push(n)}return t}async function Gu(i){let t=i.rpxDir??Ri(),n=z0(i.domains);if(n.length===0)return!1;let r=K0(n),f=await pB(n,i.verbose);if(!f){let $=n[0];if($&&await im($))f=!0;else T("dns","Dev DNS server not available on 127.0.0.1:15353",i.verbose)}if(!f)return!1;if(!await $m(r,i.verbose))return!1;let c={version:xf,resolvers:r,domains:n,ownerPid:i.ownerPid??ut.pid,updatedAt:new Date().toISOString()};return await au(t,c),!0}async function bn(i,t={}){let n=i.map((w)=>w.to).filter(Boolean),r=t.rpxDir??Ri(),f=K0(n),$=((await df(r))?.resolvers??[]).filter((w)=>!f.includes(w));if($.length>0)await G0($,t.verbose);if(f.length===0){Ku(t.verbose),await I0(r);return}await Gu({domains:n,rpxDir:r,verbose:t.verbose,ownerPid:t.ownerPid??ut.pid})}async function Cn(i={}){let t=i.rpxDir??Ri();Ku(i.verbose);let r=(await df(t))?.resolvers??[];await G0(r,i.verbose),await Ou(i.verbose),await I0(t)}async function MS(i){await Cn({verbose:i})}async function Rn(i={}){let t=i.rpxDir??Ri(),n=await df(t),r=n?.ownerPid!=null&&xi(n.ownerPid);if(n&&!r){T("dns",`reconcile: owner pid ${n.ownerPid} is gone — tearing down DNS`,i.verbose),await Cn(i);return}let f=await Ou(i.verbose);if(f.length>0)T("dns",`reconcile: removed legacy TLD resolvers: ${f.join(", ")}`,i.verbose);await O0(i.verbose)}
|
|
224
|
-
export{F as a,hy as b,tY as c,_t as d,bc as e,Qc as f,nY as g,rY as h,Ct as i,It as j,Pc as k,Hn as l,vc as m,yy as n,Xf as o,qn as p,Ln as q,Zc as r,t0 as s,By as t,my as u,n0 as v,lj as w,cj as x,$j as y,Ry as z,r0 as A,f0 as B,l0 as C,wj as D,sy as E,jy as F,Sy as G,ay as H,Wf as I,gn as J,Ny as K,c0 as L,UY as M,Wy as N,Jy as O,Bj as P,qy as Q,Ly as R,PY as S,vY as T,ZY as U,gy as V,Vy as W,h0 as X,y0 as Y,Dy as Z,Py as _,If as $,u0 as aa,vy as ba,zt as ca,nB as da,e0 as ea,A0 as fa,E0 as ga,rB as ha,Y0 as ia,cB as ja,oy as ka,Kf as la,C0 as ma,py as na,EB as oa,TB as pa,BB as qa,R0 as ra,Lj as sa,lu as ta,s0 as ua,cu as va,dj as wa,Ut as xa,j0 as ya,xi as za,wu as Aa,a0 as Ba,UB as Ca,yt as Da,Vn as Ea,Mf as Fa,X0 as Ga,Yn as Ha,eu as Ia,Au as Ja,xf as Ka,ju as La,Nu as Ma,QB as Na,K0 as Oa,z0 as Pa,Vf as Qa,PB as Ra,pB as Sa,Ku as Ta,OS as Ua,im as Va,Pn as Wa,rm as Xa,GS as Ya,Ou as Za,Gu as _a,bn as $a,Cn as ab,MS as bb,Rn as cb,Ri as db,gf as eb,mn as fb,MB as gb,Ru as hb,Bn as ib,jS as jb,VB as kb,SS as lb,aS as mb,NS as nb};
|