@stacksjs/rpx 0.11.15 → 0.11.17
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 +119 -119
- package/dist/{chunk-kv17r01q.js → chunk-a0b9f9fs.js} +1 -1
- package/dist/{chunk-pjwm8py7.js → chunk-fndafyac.js} +1 -1
- package/dist/{chunk-hf6e07v4.js → chunk-rbgb5fyg.js} +1 -1
- package/dist/{chunk-0zdj72ps.js → chunk-zx2ghrc1.js} +62 -62
- package/dist/daemon-runner.d.ts +3 -1
- package/dist/host-routes.d.ts +43 -0
- package/dist/index.d.ts +11 -1
- package/dist/index.js +7 -6
- package/dist/origin-guard.d.ts +12 -0
- package/dist/proxy-handler.d.ts +14 -1
- package/dist/registry.d.ts +2 -0
- package/dist/types.d.ts +1 -0
- package/package.json +1 -1
- package/src/daemon-runner.ts +14 -3
- package/src/daemon.ts +17 -10
- package/src/host-routes.ts +147 -0
- package/src/https.ts +2 -2
- package/src/index.ts +13 -1
- package/src/origin-guard.ts +105 -0
- package/src/proxy-handler.ts +60 -7
- package/src/registry.ts +12 -0
- package/src/start.ts +40 -14
- package/src/types.ts +7 -0
|
@@ -1,25 +1,25 @@
|
|
|
1
|
-
import{Da as O,Fa as yr,Ga as $,Ka as aa,La as os,Na as re,Oa as oa,Qa as Ea,Ra as ua}from"./chunk-hf6e07v4.js";import O0 from"node:dgram";import*as Xa from"node:fs/promises";import*as _a from"node:path";import*as fi from"node:process";import{spawn as Ua}from"node:child_process";import*as Gt from"node:fs/promises";import{homedir as Ss}from"node:os";import*as Nt from"node:path";import*as N from"node:process";var K={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};import{execSync as pi}from"node:child_process";import D from"node:fs/promises";import*as as from"node:os";import{homedir as ne}from"node:os";import{join as tt}from"node:path";import*as Mt from"node:process";import{createRequire as La}from"node:module";import{Resolver as ye}from"node:dns/promises";import{createHash as xa,sign as qa}from"node:crypto";import{createHash as ka}from"node:crypto";import{sign as ba}from"node:crypto";import{generateKeyPairSync as Ll,X509Certificate as io}from"node:crypto";import we from"node:os";import $e from"node:path";import{existsSync as Os,statSync as Hs}from"fs";import{existsSync as no,mkdirSync as sm,readdirSync as lm,readFileSync as eo,writeFileSync as cm}from"fs";import{homedir as Ti}from"os";import{dirname as om,resolve as gt}from"path";import on from"process";import{existsSync as Ks,statSync as Ms}from"fs";import{existsSync as Me,mkdirSync as fo,readdirSync as so,writeFileSync as lo}from"fs";import{homedir as Ci}from"os";import{dirname as zs,resolve as at}from"path";import di from"process";import{join as co,relative as ho,resolve as Ls}from"path";import Dr from"process";import{existsSync as Gl,mkdirSync as Cm,readdirSync as gm,writeFileSync as Sm}from"fs";import{homedir as me}from"os";import{dirname as Ym,resolve as ht}from"path";import nr from"process";import{join as ao,relative as oo,resolve as Gs}from"path";import pr from"process";import{existsSync as xl,mkdirSync as Wm,readdirSync as Xm,writeFileSync as _m}from"fs";import{dirname as Jm,resolve as Vr}from"path";import ze from"process";import{Buffer as si}from"buffer";import{createCipheriv as uo,createDecipheriv as yo,randomBytes as de}from"crypto";import{closeSync as Ae,createReadStream as xs,createWriteStream as wo,existsSync as Ee,fsyncSync as qs,openSync as ks,writeFileSync as $o}from"fs";import{access as mo,constants as bs,mkdir as Ao,readdir as Rr,rename as Ds,stat as gi,unlink as Yr,writeFile as Te}from"fs/promises";import{join as Si}from"path";import nt from"process";import{pipeline as Eo}from"stream/promises";import{createGzip as ps}from"zlib";import Bi from"process";import Dt from"process";import{Buffer as qt}from"buffer";import{createCipheriv as To,createDecipheriv as Co,randomBytes as Ce}from"crypto";import{closeSync as ge,createReadStream as Vs,createWriteStream as go,existsSync as Ur,fsyncSync as Ps,openSync as vs,writeFileSync as So}from"fs";import{access as Bo,constants as Qs,mkdir as Ro,readdir as Fr,rename as Zs,stat as Ri,unlink as Nr,writeFile as Se}from"fs/promises";import{isAbsolute as Yo,join as Yi,resolve as Uo}from"path";import _ from"process";import{pipeline as Fo}from"stream/promises";import{createGzip as tl}from"zlib";import Ui from"process";import pt from"process";import jr from"process";import{existsSync as Wr}from"fs";import{resolve as Be}from"path";import{existsSync as No}from"fs";import{existsSync as jo,readdirSync as Wo}from"fs";import{extname as Re,resolve as il}from"path";import Xo from"process";import{join as _o,relative as Io,resolve as rl}from"path";import Pr from"process";import{Buffer as kt}from"buffer";import{createCipheriv as Jo,createDecipheriv as Oo,randomBytes as Ye}from"crypto";import{closeSync as Ue,createReadStream as nl,createWriteStream as Ho,existsSync as Xr,fsyncSync as el,openSync as fl,writeFileSync as Ko}from"fs";import{access as Mo,constants as sl,mkdir as zo,readdir as _r,rename as ll,stat as Fi,unlink as Ir,writeFile as Fe}from"fs/promises";import{isAbsolute as Lo,join as Ni,resolve as Go}from"path";import I from"process";import{pipeline as xo}from"stream/promises";import{createGzip as cl}from"zlib";import ji from"process";import Vt from"process";import Jr from"process";import{existsSync as Or}from"fs";import{resolve as Ne}from"path";import{existsSync as qo}from"fs";import{exec as uy}from"node:child_process";import gl from"node:fs";import yy from"node:os";import Xt from"node:path";import Rc from"node:process";import{promisify as wy}from"node:util";import Ii from"node:crypto";import Pt from"node:fs";import Ze from"node:path";import{execSync as Ul}from"node:child_process";import hn from"node:os";var Ga=La(import.meta.url);async function Fl(t,i,r={}){let n=r.timeoutMs??120000,e=r.intervalMs??3000,f=t.split(".").slice(-2).join("."),s;try{let h=new ye,a=await h.resolveNs(f),o=(await Promise.all(a.map((y)=>h.resolve4(y).catch(()=>[])))).flat();if(o.length>0)s=new ye,s.setServers(o)}catch{}let c=Date.now()+n,l=s??new ye;for(;;){try{if((await l.resolveTxt(t)).some((h)=>h.join("")===i))return!0}catch{}if(Date.now()>=c)return!1;await new Promise((h)=>setTimeout(h,e))}}class rr{tokens=new Map;add(t,i){this.tokens.set(t,i)}get(t){return this.tokens.get(t)}remove(t){this.tokens.delete(t)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(t){let i=t.indexOf(rr.PATH_PREFIX);if(i===-1)return;let r=t.slice(i+rr.PATH_PREFIX.length);return this.get(r)}}var an=new rr;function Mr(t){return(typeof t==="string"?Buffer.from(t,"utf8"):Buffer.from(t)).toString("base64url")}function Je(t){return Buffer.from(t,"base64url")}function Nl(t){let i=t.export({format:"jwk"});if(i.kty!=="EC"||i.crv!=="P-256"||!i.x||!i.y)throw Error(`Expected a P-256 EC public key, got kty=${i.kty} crv=${i.crv}`);return{crv:"P-256",kty:"EC",x:i.x,y:i.y}}function jl(t){let i=`{"crv":"${t.crv}","kty":"${t.kty}","x":"${t.x}","y":"${t.y}"}`;return xa("sha256").update(i).digest("base64url")}function Wl(t){let{protectedHeader:i,payload:r,privateKey:n}=t,e=Mr(JSON.stringify(i)),f=r===""?"":Mr(JSON.stringify(r)),s=`${e}.${f}`,c=qa("sha256",Buffer.from(s),{key:n,dsaEncoding:"ieee-p1363"});return{protected:e,payload:f,signature:Mr(c)}}var Xl="https://acme-staging-v02.api.letsencrypt.org/directory",_l="https://acme-v02.api.letsencrypt.org/directory";class kr extends Error{problem;httpStatus;constructor(t,i,r){super(t);this.name="AcmeError",this.problem=i,this.httpStatus=r}}class br{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor(t){this.directoryUrl=t.directoryUrl,this.accountKey=t.accountKey,this.jwk=Nl(t.accountPublicKey),this.thumbprint=jl(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let t=await fetch(this.directoryUrl);if(!t.ok)throw Error(`Failed to fetch ACME directory: HTTP ${t.status}`);return this.directoryCache=await t.json(),this.directoryCache}async newNonce(){let t=await this.directory(),i=(await fetch(t.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!i)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=i,i}async ensureNonce(){if(this.nonce){let t=this.nonce;return this.nonce=void 0,t}return this.newNonce()}async signedPost(t){let{url:i,payload:r,useJwk:n}=t,e={alg:"ES256",nonce:await this.ensureNonce(),url:i};if(n)e.jwk=this.jwk;else e.kid=this.requireKid();let f=Wl({protectedHeader:e,payload:r,privateKey:this.accountKey}),s=await fetch(i,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(f)}),c=s.headers.get("replay-nonce");if(c)this.nonce=c;let l=s.headers.get("content-type")??"",h;if(l.includes("application/pem-certificate-chain")||l.startsWith("text/"))h=await s.text();else{let a=await s.text();h=a?JSON.parse(a):{}}if(s.status>=400){let a=h??{};throw new kr(`ACME request to ${i} failed (HTTP ${s.status}): ${a.type??""} ${a.detail??""}`.trim(),a,s.status)}return{status:s.status,headers:s.headers,body:h,location:s.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(t={}){let i=await this.directory(),r={termsOfServiceAgreed:!0};if(t.email)r.contact=[`mailto:${t.email}`];let n=await this.signedPost({url:i.newAccount,payload:r,useJwk:!0});if(!n.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=n.location,this.accountKid}async newOrder(t){let i=await this.directory(),r={identifiers:t.map((e)=>({type:"dns",value:e}))},n=await this.signedPost({url:i.newOrder,payload:r});if(!n.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:n.body,orderUrl:n.location}}async getAuthorization(t){return(await this.signedPost({url:t,payload:""})).body}keyAuthorization(t){return`${t}.${this.thumbprint}`}dns01TxtValue(t){return ka("sha256").update(this.keyAuthorization(t)).digest("base64url")}async notifyChallengeReady(t){await this.signedPost({url:t,payload:{}})}async pollAuthorization(t,i={}){let r=i.timeoutMs??60000,n=i.intervalMs??2000,e=Date.now()+r;while(Date.now()<e){let f=await this.getAuthorization(t);if(f.status==="valid")return;if(f.status==="invalid"){let s=f.challenges.find((c)=>c.status==="invalid");throw new kr(`Authorization for ${f.identifier.value} became invalid: ${s?.error?.detail??"unknown reason"}`,s?.error??{},0)}await Js(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${t} to become valid`)}async finalizeOrder(t,i){return(await this.signedPost({url:t,payload:{csr:i}})).body}async getOrder(t){return(await this.signedPost({url:t,payload:""})).body}async pollOrder(t,i={}){let r=i.timeoutMs??60000,n=i.intervalMs??2000,e=Date.now()+r;while(Date.now()<e){let f=await this.getOrder(t);if(f.status==="valid"){if(!f.certificate)throw Error("ACME order is valid but has no certificate URL");return f.certificate}if(f.status==="invalid")throw Error(`ACME order ${t} became invalid`);await Js(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${t} to become valid`)}async downloadCertificate(t){let i=await this.signedPost({url:t,payload:""});return typeof i.body==="string"?i.body:String(i.body)}static selectChallenge(t,i){let r=t.challenges.find((n)=>n.type===i);if(!r)throw Error(`No ${i} challenge available for ${t.identifier.value}`);return r}}function Il(t){let i=t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=i[0];if(!r)return{certPem:`${t.trim()}
|
|
1
|
+
import{Ja as O,La as yr,Ma as $,Qa as ya,Ra as os,Ta as re,Ua as wa,Wa as Sa,Xa as $a}from"./chunk-rbgb5fyg.js";import L0 from"node:dgram";import*as Oa from"node:fs/promises";import*as Ka from"node:path";import*as fi from"node:process";import{spawn as Wa}from"node:child_process";import*as Gt from"node:fs/promises";import{homedir as Ys}from"node:os";import*as jt from"node:path";import*as N from"node:process";var H={info:(...t)=>console.log("[info]",...t),success:(...t)=>console.log("[success]",...t),warn:(...t)=>console.warn("[warn]",...t),error:(...t)=>console.error("[error]",...t),debug:(...t)=>console.debug("[debug]",...t),log:(...t)=>console.log(...t),start:(...t)=>console.log("[start]",...t),box:(...t)=>console.log("[box]",...t)};import{execSync as Vi}from"node:child_process";import b from"node:fs/promises";import*as us from"node:os";import{homedir as ne}from"node:os";import{join as tt}from"node:path";import*as Mt from"node:process";import{createRequire as ka}from"node:module";import{Resolver as we}from"node:dns/promises";import{createHash as ba,sign as Va}from"node:crypto";import{createHash as pa}from"node:crypto";import{sign as Pa}from"node:crypto";import{generateKeyPairSync as ql,X509Certificate as fu}from"node:crypto";import $e from"node:os";import me from"node:path";import{existsSync as Ms,statSync as zs}from"fs";import{existsSync as lu,mkdirSync as um,readdirSync as om,readFileSync as cu,writeFileSync as ym}from"fs";import{homedir as Ti}from"os";import{dirname as mm,resolve as gt}from"path";import un from"process";import{existsSync as Ls,statSync as Gs}from"fs";import{existsSync as ze,mkdirSync as hu,readdirSync as au,writeFileSync as uu}from"fs";import{homedir as Ci}from"os";import{dirname as xs,resolve as at}from"path";import di from"process";import{join as ou,relative as yu,resolve as qs}from"path";import br from"process";import{existsSync as kl,mkdirSync as Ym,readdirSync as Um,writeFileSync as Fm}from"fs";import{homedir as de}from"os";import{dirname as Wm,resolve as ht}from"path";import nr from"process";import{join as wu,relative as $u,resolve as ks}from"path";import Vr from"process";import{existsSync as Dl,mkdirSync as Om,readdirSync as Km,writeFileSync as Hm}from"fs";import{dirname as zm,resolve as pr}from"path";import Le from"process";import{Buffer as si}from"buffer";import{createCipheriv as mu,createDecipheriv as du,randomBytes as Ae}from"crypto";import{closeSync as Ee,createReadStream as Ds,createWriteStream as Au,existsSync as Te,fsyncSync as bs,openSync as Vs,writeFileSync as Eu}from"fs";import{access as Tu,constants as ps,mkdir as Cu,readdir as Rr,rename as Ps,stat as Si,unlink as Yr,writeFile as Ce}from"fs/promises";import{join as gi}from"path";import nt from"process";import{pipeline as Su}from"stream/promises";import{createGzip as vs}from"zlib";import Bi from"process";import bt from"process";import{Buffer as qt}from"buffer";import{createCipheriv as gu,createDecipheriv as Bu,randomBytes as Se}from"crypto";import{closeSync as ge,createReadStream as Qs,createWriteStream as Ru,existsSync as Ur,fsyncSync as Zs,openSync as tl,writeFileSync as Yu}from"fs";import{access as Uu,constants as il,mkdir as Fu,readdir as Fr,rename as rl,stat as Ri,unlink as Nr,writeFile as Be}from"fs/promises";import{isAbsolute as Nu,join as Yi,resolve as ju}from"path";import _ from"process";import{pipeline as Wu}from"stream/promises";import{createGzip as nl}from"zlib";import Ui from"process";import Vt from"process";import jr from"process";import{existsSync as Wr}from"fs";import{resolve as Re}from"path";import{existsSync as Xu}from"fs";import{existsSync as _u,readdirSync as Iu}from"fs";import{extname as Ye,resolve as el}from"path";import Ju from"process";import{join as Ou,relative as Ku,resolve as fl}from"path";import Pr from"process";import{Buffer as kt}from"buffer";import{createCipheriv as Hu,createDecipheriv as Mu,randomBytes as Ue}from"crypto";import{closeSync as Fe,createReadStream as sl,createWriteStream as zu,existsSync as Xr,fsyncSync as ll,openSync as cl,writeFileSync as Lu}from"fs";import{access as Gu,constants as hl,mkdir as xu,readdir as _r,rename as al,stat as Fi,unlink as Ir,writeFile as Ne}from"fs/promises";import{isAbsolute as qu,join as Ni,resolve as ku}from"path";import I from"process";import{pipeline as Du}from"stream/promises";import{createGzip as ul}from"zlib";import ji from"process";import pt from"process";import Jr from"process";import{existsSync as Or}from"fs";import{resolve as je}from"path";import{existsSync as bu}from"fs";import{exec as my}from"node:child_process";import Rl from"node:fs";import dy from"node:os";import Xt from"node:path";import Fc from"node:process";import{promisify as Ay}from"node:util";import Ii from"node:crypto";import Pt from"node:fs";import tf from"node:path";import{execSync as jl}from"node:child_process";import hn from"node:os";var Da=ka(import.meta.url);async function Wl(t,i,r={}){let n=r.timeoutMs??120000,e=r.intervalMs??3000,f=t.split(".").slice(-2).join("."),s;try{let h=new we,a=await h.resolveNs(f),u=(await Promise.all(a.map((y)=>h.resolve4(y).catch(()=>[])))).flat();if(u.length>0)s=new we,s.setServers(u)}catch{}let c=Date.now()+n,l=s??new we;for(;;){try{if((await l.resolveTxt(t)).some((h)=>h.join("")===i))return!0}catch{}if(Date.now()>=c)return!1;await new Promise((h)=>setTimeout(h,e))}}class rr{tokens=new Map;add(t,i){this.tokens.set(t,i)}get(t){return this.tokens.get(t)}remove(t){this.tokens.delete(t)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(t){let i=t.indexOf(rr.PATH_PREFIX);if(i===-1)return;let r=t.slice(i+rr.PATH_PREFIX.length);return this.get(r)}}var an=new rr;function Mr(t){return(typeof t==="string"?Buffer.from(t,"utf8"):Buffer.from(t)).toString("base64url")}function Oe(t){return Buffer.from(t,"base64url")}function Xl(t){let i=t.export({format:"jwk"});if(i.kty!=="EC"||i.crv!=="P-256"||!i.x||!i.y)throw Error(`Expected a P-256 EC public key, got kty=${i.kty} crv=${i.crv}`);return{crv:"P-256",kty:"EC",x:i.x,y:i.y}}function _l(t){let i=`{"crv":"${t.crv}","kty":"${t.kty}","x":"${t.x}","y":"${t.y}"}`;return ba("sha256").update(i).digest("base64url")}function Il(t){let{protectedHeader:i,payload:r,privateKey:n}=t,e=Mr(JSON.stringify(i)),f=r===""?"":Mr(JSON.stringify(r)),s=`${e}.${f}`,c=Va("sha256",Buffer.from(s),{key:n,dsaEncoding:"ieee-p1363"});return{protected:e,payload:f,signature:Mr(c)}}var Jl="https://acme-staging-v02.api.letsencrypt.org/directory",Ol="https://acme-v02.api.letsencrypt.org/directory";class kr extends Error{problem;httpStatus;constructor(t,i,r){super(t);this.name="AcmeError",this.problem=i,this.httpStatus=r}}class Dr{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor(t){this.directoryUrl=t.directoryUrl,this.accountKey=t.accountKey,this.jwk=Xl(t.accountPublicKey),this.thumbprint=_l(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let t=await fetch(this.directoryUrl);if(!t.ok)throw Error(`Failed to fetch ACME directory: HTTP ${t.status}`);return this.directoryCache=await t.json(),this.directoryCache}async newNonce(){let t=await this.directory(),i=(await fetch(t.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!i)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=i,i}async ensureNonce(){if(this.nonce){let t=this.nonce;return this.nonce=void 0,t}return this.newNonce()}async signedPost(t){let{url:i,payload:r,useJwk:n}=t,e={alg:"ES256",nonce:await this.ensureNonce(),url:i};if(n)e.jwk=this.jwk;else e.kid=this.requireKid();let f=Il({protectedHeader:e,payload:r,privateKey:this.accountKey}),s=await fetch(i,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(f)}),c=s.headers.get("replay-nonce");if(c)this.nonce=c;let l=s.headers.get("content-type")??"",h;if(l.includes("application/pem-certificate-chain")||l.startsWith("text/"))h=await s.text();else{let a=await s.text();h=a?JSON.parse(a):{}}if(s.status>=400){let a=h??{};throw new kr(`ACME request to ${i} failed (HTTP ${s.status}): ${a.type??""} ${a.detail??""}`.trim(),a,s.status)}return{status:s.status,headers:s.headers,body:h,location:s.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(t={}){let i=await this.directory(),r={termsOfServiceAgreed:!0};if(t.email)r.contact=[`mailto:${t.email}`];let n=await this.signedPost({url:i.newAccount,payload:r,useJwk:!0});if(!n.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=n.location,this.accountKid}async newOrder(t){let i=await this.directory(),r={identifiers:t.map((e)=>({type:"dns",value:e}))},n=await this.signedPost({url:i.newOrder,payload:r});if(!n.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:n.body,orderUrl:n.location}}async getAuthorization(t){return(await this.signedPost({url:t,payload:""})).body}keyAuthorization(t){return`${t}.${this.thumbprint}`}dns01TxtValue(t){return pa("sha256").update(this.keyAuthorization(t)).digest("base64url")}async notifyChallengeReady(t){await this.signedPost({url:t,payload:{}})}async pollAuthorization(t,i={}){let r=i.timeoutMs??60000,n=i.intervalMs??2000,e=Date.now()+r;while(Date.now()<e){let f=await this.getAuthorization(t);if(f.status==="valid")return;if(f.status==="invalid"){let s=f.challenges.find((c)=>c.status==="invalid");throw new kr(`Authorization for ${f.identifier.value} became invalid: ${s?.error?.detail??"unknown reason"}`,s?.error??{},0)}await Hs(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for authorization ${t} to become valid`)}async finalizeOrder(t,i){return(await this.signedPost({url:t,payload:{csr:i}})).body}async getOrder(t){return(await this.signedPost({url:t,payload:""})).body}async pollOrder(t,i={}){let r=i.timeoutMs??60000,n=i.intervalMs??2000,e=Date.now()+r;while(Date.now()<e){let f=await this.getOrder(t);if(f.status==="valid"){if(!f.certificate)throw Error("ACME order is valid but has no certificate URL");return f.certificate}if(f.status==="invalid")throw Error(`ACME order ${t} became invalid`);await Hs(n),n=Math.min(n*1.5,1e4)}throw Error(`Timed out waiting for order ${t} to become valid`)}async downloadCertificate(t){let i=await this.signedPost({url:t,payload:""});return typeof i.body==="string"?i.body:String(i.body)}static selectChallenge(t,i){let r=t.challenges.find((n)=>n.type===i);if(!r)throw Error(`No ${i} challenge available for ${t.identifier.value}`);return r}}function Kl(t){let i=t.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],r=i[0];if(!r)return{certPem:`${t.trim()}
|
|
2
2
|
`,chainPem:""};let n=`${r.trim()}
|
|
3
3
|
`,e=i.slice(1).map((f)=>f.trim()).join(`
|
|
4
4
|
`);return{certPem:n,chainPem:e?`${e}
|
|
5
|
-
`:""}}function Jl(t){return`_acme-challenge.${t.startsWith("*.")?t.slice(2):t}`}function Js(t){return new Promise((i)=>setTimeout(i,t))}function Da(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function hi(t,i){return Buffer.concat([Buffer.from([t]),Da(i.length),i])}function Ol(t){let i;if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=[],n=t;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);i=Buffer.from(r)}else if(i=t.length===0?Buffer.from([0]):t,i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return hi(2,i)}function mi(t){let i=t.split(".").map(Number);if(i.length<2)throw Error(`Invalid OID: ${t}`);let r=[40*i[0]+i[1]];for(let n=2;n<i.length;n++){let e=i[n],f=[e&127];e=Math.floor(e/128);while(e>0)f.unshift(e&127|128),e=Math.floor(e/128);r.push(...f)}return hi(6,Buffer.from(r))}function Ct(...t){return hi(48,Buffer.concat(t))}function Oe(...t){return hi(49,Buffer.concat(t))}function He(t){return hi(3,Buffer.concat([Buffer.from([0]),t]))}function Hl(t){return hi(4,t)}function Kl(t){return hi(12,Buffer.from(t,"utf8"))}function Ke(t,i,r){let n=128|(r?32:0)|t;return hi(n,i)}var pa="1.2.840.10045.2.1",Va="1.2.840.10045.3.1.7",Pa="1.2.840.10045.4.3.2",va="2.5.4.3",Qa="1.2.840.113549.1.9.14",Za="2.5.29.17";function to(t){let i=t.export({format:"jwk"});if(!i.x||!i.y)throw Error("Public key JWK is missing x/y coordinates");let r=Je(i.x),n=Je(i.y);if(r.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),r,n])}function Ml(t){let{domains:i,publicKey:r,privateKey:n}=t;if(i.length===0)throw Error("At least one domain is required to build a CSR");let e=Ct(Oe(Ct(mi(va),Kl(i[0])))),f=Ct(Ct(mi(pa),mi(Va)),He(to(r))),s=i.map((w)=>Ke(2,Buffer.from(w,"ascii"),!1)),c=Ct(...s),l=Ct(mi(Za),Hl(c)),h=Ct(l),a=Ct(mi(Qa),Oe(h)),o=Ke(0,a,!0),y=Ct(Ol(0),e,f,o),u=ba("sha256",y,n),m=Ct(mi(Pa));return Ct(y,m,He(u))}function zl(t){return Ml(t).toString("base64url")}function ro(t){if(t){let{createPrivateKey:e,createPublicKey:f}=Ga("node:crypto"),s=e(t),c=f(s);return{privateKey:s,publicKey:c,pem:t}}let{privateKey:i,publicKey:r}=Ll("ec",{namedCurve:"P-256"}),n=i.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:i,publicKey:r,pem:n}}async function tf(t){let{domains:i,method:r}=t;if(i.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!t.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(i.some((o)=>o.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=t.directoryUrl??(t.staging===!1?_l:Xl),e=ro(t.accountKeyPem),f=new br({directoryUrl:n,accountKey:e.privateKey,accountPublicKey:e.publicKey});await f.newAccount({email:t.email});let{order:s,orderUrl:c}=await f.newOrder(i),l=t.http01Store??an,h=[],a=[];try{for(let X of s.authorizations){let xt=await f.getAuthorization(X);if(xt.status==="valid")continue;let jt=br.selectChallenge(xt,r);if(r==="dns-01"){let Qi=Jl(xt.identifier.value),Lt=f.dns01TxtValue(jt.token);await t.dnsProvider.setTxt(Qi,Lt),h.push({name:Qi,value:Lt}),await Fl(Qi,Lt,{timeoutMs:t.dnsPropagationTimeoutMs??120000})}else l.add(jt.token,f.keyAuthorization(jt.token)),a.push(jt.token);await f.notifyChallengeReady(jt.url),await f.pollAuthorization(X,{timeoutMs:t.timeoutMs})}let{privateKey:o,publicKey:y}=Ll("ec",{namedCurve:"P-256"}),u=zl({domains:i,publicKey:y,privateKey:o});await f.finalizeOrder(s.finalize,u);let m=await f.pollOrder(c,{timeoutMs:t.timeoutMs}),w=await f.downloadCertificate(m),{certPem:d,chainPem:A}=Il(w),T=A?`${d}${A}`:d,Y=o.export({format:"pem",type:"pkcs8"}).toString(),S=new Date(new io(d).validTo);return{certPem:d,keyPem:Y,chainPem:A,fullChainPem:T,accountKeyPem:e.pem,notAfter:S}}finally{for(let{name:o,value:y}of h)await t.dnsProvider?.removeTxt(o,y).catch(()=>{});for(let o of a)l.remove(o)}}class ql{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Os(t))return!0;return Hs(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Os(r)?Hs(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class kl{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var vr=new ql,rf=new kl,ko=Object.defineProperty,bo=(t)=>t;function Do(t,i){this[t]=bo.bind(null,i)}var po=(t,i)=>{for(var r in i)ko(t,r,{get:i[r],enumerable:!0,configurable:!0,set:Do.bind(i,r)})},Vo=(t,i)=>()=>(t&&(i=t(t=0)),i),bl={};po(bl,{withErrorRecovery:()=>Vl,tryLoadConfig:()=>Au,loadConfigWithResult:()=>mu,loadConfig:()=>tc,isRetryableError:()=>au,isConfigNotFoundError:()=>hu,isBunfigError:()=>Pl,globalPerformanceMonitor:()=>lr,globalCache:()=>Xi,getEnvOrDefault:()=>ou,generateConfigTypes:()=>Eu,defaultGeneratedDir:()=>cc,defaultConfigDir:()=>lc,deepMergeWithArrayStrategy:()=>lf,deepMerge:()=>vl,createLibraryConfig:()=>Tu,config:()=>du,bunfigPlugin:()=>Cu,applyEnvVarsToConfig:()=>tr,TypeGenerationError:()=>De,SchemaValidationError:()=>fr,PluginError:()=>Ve,PerformanceMonitor:()=>ef,FileSystemError:()=>be,ErrorFactory:()=>ci,EnvVarError:()=>en,EnvProcessor:()=>un,ConfigValidator:()=>cf,ConfigValidationError:()=>qe,ConfigNotFoundError:()=>nn,ConfigMergeError:()=>ke,ConfigLoader:()=>hf,ConfigLoadError:()=>er,ConfigFileLoader:()=>yn,ConfigCache:()=>nf,CacheUtils:()=>rc,BunfigError:()=>dt,BrowserConfigError:()=>pe,ArrayMergeStrategies:()=>fc});class nf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Ks(t))return!0;return Ms(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Ks(r)?Ms(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ef{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function Po(t,i={}){let r=Object.keys(i).sort().map((n)=>`${n}:${i[n]}`).join("|");return r?`${t}:${r}`:t}function vo(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Qo(t){return t.getStats().size*2}function ff(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&G(i[0])&&"id"in i[0]&&i[0].id===3&&G(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(G(i)&&G(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(G(t)&&"arr"in t&&Array.isArray(t.arr)&&G(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&G(i[0])&&G(t[0])){let n=[...i];for(let e of t)if(G(e)&&"name"in e){if(!n.find((f)=>G(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(G(e)&&"path"in e){if(!n.find((f)=>G(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Qr(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!G(i)||!G(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(G(e)&&G(r[n]))r[n]=ff(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&G(e[0])&&G(r[n][0])){let f=[...e];for(let s of r[n])if(G(s)&&"name"in s){if(!f.find((c)=>G(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(G(s)&&"path"in s){if(!f.find((c)=>G(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Qr(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Qr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Qr(t[r],i[r]))return!1;return!0}if(G(t)&&G(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Qr(t[e],i[e]))return!1}return!0}return!1}function G(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Zo(t,i){if(!xl(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return ff(i,n)}catch{return null}}catch{return null}}async function tu({name:t="",cwd:i,defaultConfig:r}){let n=i||ze.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Vr(n,`${s}${c}`),h=await Zo(l,r);if(h!==null)return h}try{let s=Vr(n,"package.json");if(xl(s)){let c=(await import(s))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return ff(r,c)}catch{}}}catch{}return r}function iu(t,i={}){let r=pr.cwd();while(r.includes("storage"))r=Gs(r,"..");let n=Gs(r,t||"");if(i?.relative)return oo(pr.cwd(),n);return n}async function ru(){try{let t=await tu({name:"clarity",defaultConfig:Lr,cwd:pr.cwd(),endpoint:"",headers:{}});return{...Lr,...t}}catch{return Lr}}function q(){if(Dt.env.NODE_ENV==="test"||Dt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nu(){if(Dt.env.NODE_ENV==="test"||Dt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Dt<"u"){let t=Dt.type;if(t==="renderer"||t==="worker")return!1;return!!(Dt.versions&&(Dt.versions.node||Dt.versions.bun))}return!1}class Dl{async format(t){let i=await nu(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Bi.pid,hostname:i(),environment:Bi.env.NODE_ENV||"development",platform:Bi.platform,version:Bi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Bi.env.NODE_ENV||Bi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Zr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Ge},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Dl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??nt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Gr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Gr};return{...Gr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Ge.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await mo(this.config.logDirectory,bs.F_OK|bs.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Ao(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:si.from(t);try{if(!Ee(this.currentLogFile))await Te(this.currentLogFile,"",{mode:420});if(n=ks(this.currentLogFile,"a",420),$o(n,c,{flag:"a"}),qs(n),n!==void 0)Ae(n),n=void 0;if((await gi(this.currentLogFile)).size===0){if(await Te(this.currentLogFile,c,{flag:"w",mode:420}),(await gi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let a=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,a);let o=s*2**e;await new Promise((y)=>setTimeout(y,o)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{Ae(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,a=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",a),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Si(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 Si(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Si(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(q())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return de(16).toString("hex")}generateKey(){return de(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=de(16),n=uo("aes-256-gcm",i,r),e=si.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:si.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=ps(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(si.from(si.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(q())return;let t=await gi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Rr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await gi(r).catch(()=>null))try{if(await Ds(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Yr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Te(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await gi(r).catch(()=>null))await Ds(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await Rr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Yr(Si(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=xs(t),n=wo(i),e=ps();await Eo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Ee(this.currentLogFile))try{let t=ks(this.currentLogFile,"r+");qs(t),Ae(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Rr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Yr(Si(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?M.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=nt.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${M.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!q()){let h=nc[t],a=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:M.gray(s),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:M.green(s),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(o),c){let y=c.split(`
|
|
6
|
-
`);for(let
|
|
5
|
+
`:""}}function Hl(t){return`_acme-challenge.${t.startsWith("*.")?t.slice(2):t}`}function Hs(t){return new Promise((i)=>setTimeout(i,t))}function va(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function hi(t,i){return Buffer.concat([Buffer.from([t]),va(i.length),i])}function Ml(t){let i;if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=[],n=t;while(n>0)r.unshift(n&255),n>>=8;if(r[0]&128)r.unshift(0);i=Buffer.from(r)}else if(i=t.length===0?Buffer.from([0]):t,i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return hi(2,i)}function mi(t){let i=t.split(".").map(Number);if(i.length<2)throw Error(`Invalid OID: ${t}`);let r=[40*i[0]+i[1]];for(let n=2;n<i.length;n++){let e=i[n],f=[e&127];e=Math.floor(e/128);while(e>0)f.unshift(e&127|128),e=Math.floor(e/128);r.push(...f)}return hi(6,Buffer.from(r))}function St(...t){return hi(48,Buffer.concat(t))}function Ke(...t){return hi(49,Buffer.concat(t))}function He(t){return hi(3,Buffer.concat([Buffer.from([0]),t]))}function zl(t){return hi(4,t)}function Ll(t){return hi(12,Buffer.from(t,"utf8"))}function Me(t,i,r){let n=128|(r?32:0)|t;return hi(n,i)}var Qa="1.2.840.10045.2.1",Za="1.2.840.10045.3.1.7",tu="1.2.840.10045.4.3.2",iu="2.5.4.3",ru="1.2.840.113549.1.9.14",nu="2.5.29.17";function eu(t){let i=t.export({format:"jwk"});if(!i.x||!i.y)throw Error("Public key JWK is missing x/y coordinates");let r=Oe(i.x),n=Oe(i.y);if(r.length!==32||n.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${r.length} y=${n.length}`);return Buffer.concat([Buffer.from([4]),r,n])}function Gl(t){let{domains:i,publicKey:r,privateKey:n}=t;if(i.length===0)throw Error("At least one domain is required to build a CSR");let e=St(Ke(St(mi(iu),Ll(i[0])))),f=St(St(mi(Qa),mi(Za)),He(eu(r))),s=i.map((w)=>Me(2,Buffer.from(w,"ascii"),!1)),c=St(...s),l=St(mi(nu),zl(c)),h=St(l),a=St(mi(ru),Ke(h)),u=Me(0,a,!0),y=St(Ml(0),e,f,u),o=Pa("sha256",y,n),m=St(mi(tu));return St(y,m,He(o))}function xl(t){return Gl(t).toString("base64url")}function su(t){if(t){let{createPrivateKey:e,createPublicKey:f}=Da("node:crypto"),s=e(t),c=f(s);return{privateKey:s,publicKey:c,pem:t}}let{privateKey:i,publicKey:r}=ql("ec",{namedCurve:"P-256"}),n=i.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:i,publicKey:r,pem:n}}async function rf(t){let{domains:i,method:r}=t;if(i.length===0)throw Error("obtainCertificate requires at least one domain");if(r==="dns-01"&&!t.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(i.some((u)=>u.startsWith("*."))&&r!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let n=t.directoryUrl??(t.staging===!1?Ol:Jl),e=su(t.accountKeyPem),f=new Dr({directoryUrl:n,accountKey:e.privateKey,accountPublicKey:e.publicKey});await f.newAccount({email:t.email});let{order:s,orderUrl:c}=await f.newOrder(i),l=t.http01Store??an,h=[],a=[];try{for(let X of s.authorizations){let xt=await f.getAuthorization(X);if(xt.status==="valid")continue;let Wt=Dr.selectChallenge(xt,r);if(r==="dns-01"){let Qi=Hl(xt.identifier.value),Lt=f.dns01TxtValue(Wt.token);await t.dnsProvider.setTxt(Qi,Lt),h.push({name:Qi,value:Lt}),await Wl(Qi,Lt,{timeoutMs:t.dnsPropagationTimeoutMs??120000})}else l.add(Wt.token,f.keyAuthorization(Wt.token)),a.push(Wt.token);await f.notifyChallengeReady(Wt.url),await f.pollAuthorization(X,{timeoutMs:t.timeoutMs})}let{privateKey:u,publicKey:y}=ql("ec",{namedCurve:"P-256"}),o=xl({domains:i,publicKey:y,privateKey:u});await f.finalizeOrder(s.finalize,o);let m=await f.pollOrder(c,{timeoutMs:t.timeoutMs}),w=await f.downloadCertificate(m),{certPem:d,chainPem:A}=Kl(w),T=A?`${d}${A}`:d,Y=u.export({format:"pem",type:"pkcs8"}).toString(),g=new Date(new fu(d).validTo);return{certPem:d,keyPem:Y,chainPem:A,fullChainPem:T,accountKeyPem:e.pem,notAfter:g}}finally{for(let{name:u,value:y}of h)await t.dnsProvider?.removeTxt(u,y).catch(()=>{});for(let u of a)l.remove(u)}}class bl{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Ms(t))return!0;return zs(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Ms(r)?zs(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Vl{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var vr=new bl,nf=new Vl,Vu=Object.defineProperty,pu=(t)=>t;function Pu(t,i){this[t]=pu.bind(null,i)}var vu=(t,i)=>{for(var r in i)Vu(t,r,{get:i[r],enumerable:!0,configurable:!0,set:Pu.bind(i,r)})},Qu=(t,i)=>()=>(t&&(i=t(t=0)),i),pl={};vu(pl,{withErrorRecovery:()=>Ql,tryLoadConfig:()=>So,loadConfigWithResult:()=>To,loadConfig:()=>nc,isRetryableError:()=>yo,isConfigNotFoundError:()=>oo,isBunfigError:()=>Zl,globalPerformanceMonitor:()=>lr,globalCache:()=>Xi,getEnvOrDefault:()=>wo,generateConfigTypes:()=>go,defaultGeneratedDir:()=>uc,defaultConfigDir:()=>ac,deepMergeWithArrayStrategy:()=>cf,deepMerge:()=>tc,createLibraryConfig:()=>Bo,config:()=>Co,bunfigPlugin:()=>Ro,applyEnvVarsToConfig:()=>tr,TypeGenerationError:()=>Ve,SchemaValidationError:()=>fr,PluginError:()=>Pe,PerformanceMonitor:()=>ff,FileSystemError:()=>be,ErrorFactory:()=>ci,EnvVarError:()=>en,EnvProcessor:()=>on,ConfigValidator:()=>hf,ConfigValidationError:()=>ke,ConfigNotFoundError:()=>nn,ConfigMergeError:()=>De,ConfigLoader:()=>af,ConfigLoadError:()=>er,ConfigFileLoader:()=>yn,ConfigCache:()=>ef,CacheUtils:()=>fc,BunfigError:()=>dt,BrowserConfigError:()=>pe,ArrayMergeStrategies:()=>cc});class ef{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Ls(t))return!0;return Gs(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Ls(r)?Gs(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class ff{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function Zu(t,i={}){let r=Object.keys(i).sort().map((n)=>`${n}:${i[n]}`).join("|");return r?`${t}:${r}`:t}function to(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function io(t){return t.getStats().size*2}function sf(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&G(i[0])&&"id"in i[0]&&i[0].id===3&&G(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(G(i)&&G(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(G(t)&&"arr"in t&&Array.isArray(t.arr)&&G(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&G(i[0])&&G(t[0])){let n=[...i];for(let e of t)if(G(e)&&"name"in e){if(!n.find((f)=>G(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(G(e)&&"path"in e){if(!n.find((f)=>G(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>Qr(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!G(i)||!G(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(G(e)&&G(r[n]))r[n]=sf(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&G(e[0])&&G(r[n][0])){let f=[...e];for(let s of r[n])if(G(s)&&"name"in s){if(!f.find((c)=>G(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(G(s)&&"path"in s){if(!f.find((c)=>G(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>Qr(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Qr(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Qr(t[r],i[r]))return!1;return!0}if(G(t)&&G(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Qr(t[e],i[e]))return!1}return!0}return!1}function G(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function ro(t,i){if(!Dl(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return sf(i,n)}catch{return null}}catch{return null}}async function no({name:t="",cwd:i,defaultConfig:r}){let n=i||Le.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=pr(n,`${s}${c}`),h=await ro(l,r);if(h!==null)return h}try{let s=pr(n,"package.json");if(Dl(s)){let c=(await import(s))[t];if(c&&typeof c==="object"&&!Array.isArray(c))try{return sf(r,c)}catch{}}}catch{}return r}function eo(t,i={}){let r=Vr.cwd();while(r.includes("storage"))r=ks(r,"..");let n=ks(r,t||"");if(i?.relative)return $u(Vr.cwd(),n);return n}async function fo(){try{let t=await no({name:"clarity",defaultConfig:Lr,cwd:Vr.cwd(),endpoint:"",headers:{}});return{...Lr,...t}}catch{return Lr}}function q(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function so(){if(bt.env.NODE_ENV==="test"||bt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bt<"u"){let t=bt.type;if(t==="renderer"||t==="worker")return!1;return!!(bt.versions&&(bt.versions.node||bt.versions.bun))}return!1}class Pl{async format(t){let i=await so(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Bi.pid,hostname:i(),environment:Bi.env.NODE_ENV||"development",platform:Bi.platform,version:Bi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Bi.env.NODE_ENV||Bi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Zr{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...xe},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Pl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??nt.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Gr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Gr};return{...Gr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:xe.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Tu(this.config.logDirectory,ps.F_OK|ps.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Cu(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:si.from(t);try{if(!Te(this.currentLogFile))await Ce(this.currentLogFile,"",{mode:420});if(n=Vs(this.currentLogFile,"a",420),Eu(n,c,{flag:"a"}),bs(n),n!==void 0)Ee(n),n=void 0;if((await Si(this.currentLogFile)).size===0){if(await Ce(this.currentLogFile,c,{flag:"w",mode:420}),(await Si(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let a=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,a);let u=s*2**e;await new Promise((y)=>setTimeout(y,u)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{Ee(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,a=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",a),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return gi(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return gi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return gi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(q())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ae(16).toString("hex")}generateKey(){return Ae(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ae(16),n=mu("aes-256-gcm",i,r),e=si.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:si.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=vs(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(si.from(si.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(q())return;let t=await Si(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Rr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Si(r).catch(()=>null))try{if(await Ps(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Yr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Ce(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Si(r).catch(()=>null))await Ps(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await Rr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Yr(gi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Ds(t),n=Au(i),e=vs();await Su(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Te(this.currentLogFile))try{let t=Vs(this.currentLogFile,"r+");bs(t),Ee(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!q()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Rr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Yr(gi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?M.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(o)=>o.replace(this.ANSI_PATTERN,"");if(!this.fancy){let o=[];if(s)o.push(i);if(f==="warning")o.push("WARN");else if(f==="error")o.push("ERROR");else if(r)o.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)o.push(n.replace(/[[\]]/g,""));return o.push(e),o.join(" ")}let l=nt.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${M.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,u=c(i).length,y=Math.max(1,l-2-a-u);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!q()){let h=sc[t],a=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:M.gray(s),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:M.green(s),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(u),c){let y=c.split(`
|
|
6
|
+
`);for(let o of y)if(o.trim()&&!o.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:M.gray(` ${o}`),level:t,showTimestamp:!1}))}break}}else if(!q()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
|
|
7
7
|
`;if(c)l+=`${c}
|
|
8
8
|
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!q()){let r=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:M.blue("◐"),tag:r,message:`${M.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
9
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!q()){let h=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:M.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!q())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Zr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(q())throw Error("createReadStream is not supported in browser environments");if(!
|
|
10
|
-
`),s=Math.max(...f.map((a)=>a.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((a)=>{let
|
|
9
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.fancy&&!q()){let h=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:M.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!q())console.error(l.trim());await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Zr(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(q())throw Error("createReadStream is not supported in browser environments");if(!Te(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ds(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=si.isBuffer(t)?t:si.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=du("aes-256-gcm",r,e);return c.setAuthTag(f),si.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q()}isServerMode(){return!q()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!q()){let f=t.split(`
|
|
10
|
+
`),s=Math.max(...f.map((a)=>a.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((a)=>{let u=" ".repeat(s-a.length-2);return`│ ${a}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:M.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(c)})),h.forEach((a)=>console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(a),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:M.cyan(l),showTimestamp:!1}))}else if(!q())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
|
|
11
11
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(q())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${M.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();nt.stdin.removeListener("data",r);try{if(typeof nt.stdin.setRawMode==="function")nt.stdin.setRawMode(!1)}catch{}nt.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof nt.stdin.setRawMode==="function")nt.stdin.setRawMode(!0)}catch{}nt.stdin.resume(),nt.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let e=/%([sdijfo%])/g,f=0;if(r=t.replace(e,(s,c)=>{if(c==="%")return"%";if(f>=i.length)return s;let l=i[f++];switch(c){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return s}}),f<i.length)r+=` ${i.slice(f).map((s)=>typeof s==="object"?JSON.stringify(s,null,2):String(s)).join(" ")}`}if(this.fancy&&!q()){let e=this.options.showTags!==!1&&this.name?M.gray(this.formatTag(this.name)):"",f=M.blue("◐");console.error(`${f} ${e} ${M.cyan(r)}`)}let n=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
12
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(t,i=""){if(!this.enabled||!this.fancy||q()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,e)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,n)),e!==void 0)this.activeProgressBar.message=e;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,e="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;nt.stdout.write(`${"\r".padEnd(nt.stdout.columns||80)}\r`),this.log(e,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||q()||!nt.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=M.green("━".repeat(n)),s=M.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=i||r===100?M.green("✓"):M.blue("▶"),
|
|
13
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||q()||!nt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Rr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Si(this.config.logDirectory,n);if(t.before)try{if((await gi(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Yr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function zr(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&J(i[0])&&"id"in i[0]&&i[0].id===3&&J(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(J(i)&&J(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(J(t)&&"arr"in t&&Array.isArray(t.arr)&&J(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&J(i[0])&&J(t[0])){let n=[...i];for(let e of t)if(J(e)&&"name"in e){if(!n.find((f)=>J(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(J(e)&&"path"in e){if(!n.find((f)=>J(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>tn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!J(i)||!J(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(J(e)&&J(r[n]))r[n]=zr(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&J(e[0])&&J(r[n][0])){let f=[...e];for(let s of r[n])if(J(s)&&"name"in s){if(!f.find((c)=>J(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(J(s)&&"path"in s){if(!f.find((c)=>J(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>tn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function sf(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:zr(t,i);if(Array.isArray(t))return r==="replace"?i:zr(t,i);if(!J(i)||!J(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=zr(s,f);else if(J(f)&&J(s))n[e]=sf(s,f,r);else n[e]=f}return n}function tn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!tn(t[r],i[r]))return!1;return!0}if(J(t)&&J(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!tn(t[e],i[e]))return!1}return!0}return!1}function J(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Hr(t,i,r="replace"){if(!Gl(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return sf(i,e,r)}catch{return null}}catch{return null}}function eu(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=(w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${n}_${o.map(y).join("_")}`,m=`${n}_${o.map((w)=>w.toUpperCase()).join("_")}`;if(r)ft.info(`Checking environment variable ${u} for config ${t}.${o.join(".")}`);if(typeof a==="object"&&a!==null&&!Array.isArray(a))l[h]=f(a,o);else{let w=nr.env[u]||nr.env[m];if(w!==void 0){if(r)ft.info(`Using environment variable ${w?u:m} for config ${t}.${o.join(".")}`);if(typeof a==="number")l[h]=Number(w);else if(typeof a==="boolean")l[h]=w.toLowerCase()==="true";else if(Array.isArray(a))try{let d=JSON.parse(w);if(Array.isArray(d))l[h]=d;else l[h]=w.split(",").map((A)=>A.trim())}catch{l[h]=w.split(",").map((d)=>d.trim())}else l[h]=w}}}return l}return f(e)}async function fu({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?eu(t,e,f):e,h=r||nr.cwd(),a=[".ts",".js",".mjs",".cjs",".json"];if(f)ft.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let o=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],w=Array.from(new Set([h,ht(h,"config"),ht(h,".config"),n?ht(h,n):void 0].filter(Boolean)));for(let d of w){if(f)ft.info(`Searching for configuration in: ${d}`);let A=[ht(h,"config"),ht(h,".config")].concat(n?[ht(h,n)]:[]).includes(d)?[...o,...y,...u,...m]:[...y,...o,...m,...u];for(let T of A)for(let Y of a){let S=ht(d,`${T}${Y}`),X=await Hr(S,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from: ${S}`);return X}}}if(t){let d=ht(me(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)ft.info(`Checking user config directory: ${d}`);for(let T of A)for(let Y of a){let S=ht(d,`${T}${Y}`),X=await Hr(S,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from user config directory: ${S}`);return X}}}if(t){let d=ht(me(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)ft.info(`Checking user config directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let S=ht(d,`${T}${Y}`),X=await Hr(S,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from user config directory dotfile: ${S}`);return X}}}if(t){let d=me(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)ft.info(`Checking user home directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let S=ht(d,`${T}${Y}`),X=await Hr(S,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from user home directory: ${S}`);return X}}}try{let d=ht(h,"package.json");if(Gl(d)){let A=await import(d),T=A[t];if(!T&&i){if(T=A[i],T&&f)ft.success(`Using alias "${i}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(f)ft.success(`Configuration loaded from package.json: ${T===A[t]?t:i}`);return sf(l,T,c)}catch(Y){if(f)ft.warn("Failed to merge package.json config:",Y)}}}catch(d){if(f)ft.warn("Failed to load package.json:",d)}if(f)ft.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function su(t,i={}){let r=Dr.cwd();while(r.includes("storage"))r=Ls(r,"..");let n=Ls(r,t||"");if(i?.relative)return ho(Dr.cwd(),n);return n}async function lu(){try{let t=await fu({name:"clarity",alias:"logging",defaultConfig:xr,cwd:Dr.cwd()});return{...xr,...t||{}}}catch{return xr}}function p(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cu(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let t=pt.type;if(t==="renderer"||t==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class pl{async format(t){let i=await cu(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ui.pid,hostname:i(),environment:Ui.env.NODE_ENV||"development",platform:Ui.platform,version:Ui.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ui.env.NODE_ENV||Ui.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...xe},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new pl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...qr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...qr};return{...qr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:xe.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Bo(this.config.logDirectory,Qs.F_OK|Qs.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Ro(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:qt.from(t);try{if(!Ur(this.currentLogFile))await Se(this.currentLogFile,"",{mode:420});if(n=vs(this.currentLogFile,"a",420),So(n,c,{flag:"a"}),Ps(n),n!==void 0)ge(n),n=void 0;if((await Ri(this.currentLogFile)).size===0){if(await Se(this.currentLogFile,c,{flag:"w",mode:420}),(await Ri(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let a=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,a);let o=s*2**e;await new Promise((y)=>setTimeout(y,o)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{ge(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,a=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",a),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Yi(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 Yi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Yi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ce(16).toString("hex")}generateKey(){return Ce(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ce(16),n=To("aes-256-gcm",i,r),e=qt.isBuffer(t)?t:qt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=qt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=tl(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(qt.from(qt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let t=await Ri(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Fr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ri(r).catch(()=>null))try{if(await Zs(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Nr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Se(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ri(r).catch(()=>null))await Zs(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await Fr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Nr(Yi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Vs(t),n=go(i),e=tl();await Fo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Ur(this.currentLogFile))try{let t=vs(this.currentLogFile,"r+");Ps(t),ge(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Fr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Nr(Yi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?U.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let t=typeof _.env.NO_COLOR<"u",i=_.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=_.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${U.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=U.underline(U.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>U.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>U.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>U.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>U.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>U.strikethrough(n)),i}supportsHyperlinks(){if(p())return!1;let t=_.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=_.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Yo(i)||i.startsWith("./")||i.startsWith("../"))i=Uo(i);else return null;return Ur(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":ec[t],y=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:U.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:U.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.error(u),c){let m=c.split(`
|
|
14
|
-
`);for(let w of m)if(w.trim()&&!w.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:U.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!
|
|
12
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(n)}progress(t,i=""){if(!this.enabled||!this.fancy||q()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(n,e)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,n)),e!==void 0)this.activeProgressBar.message=e;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(n)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;if(this.activeProgressBar.current=this.activeProgressBar.total,n!==void 0)this.activeProgressBar.message=n;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(n,e="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||q())return;nt.stdout.write(`${"\r".padEnd(nt.stdout.columns||80)}\r`),this.log(e,n),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||q()||!nt.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=M.green("━".repeat(n)),s=M.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=i||r===100?M.green("✓"):M.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${M.gray(this.formatTag(this.name))}`:"",y=`\r${a}${u} ${c} ${l}${h}`,o=nt.stdout.columns||80,m=" ".repeat(Math.max(0,o-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,nt.stdout.write(t.lastRenderedLine),i)nt.stdout.write(`
|
|
13
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||q()||!nt.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(q()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Rr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=gi(this.config.logDirectory,n);if(t.before)try{if((await Si(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Yr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function zr(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&J(i[0])&&"id"in i[0]&&i[0].id===3&&J(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(J(i)&&J(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(J(t)&&"arr"in t&&Array.isArray(t.arr)&&J(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&J(i[0])&&J(t[0])){let n=[...i];for(let e of t)if(J(e)&&"name"in e){if(!n.find((f)=>J(f)&&("name"in f)&&f.name===e.name))n.push(e)}else if(J(e)&&"path"in e){if(!n.find((f)=>J(f)&&("path"in f)&&f.path===e.path))n.push(e)}else if(!n.some((f)=>tn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!J(i)||!J(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(J(e)&&J(r[n]))r[n]=zr(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&J(e[0])&&J(r[n][0])){let f=[...e];for(let s of r[n])if(J(s)&&"name"in s){if(!f.find((c)=>J(c)&&("name"in c)&&c.name===s.name))f.push(s)}else if(J(s)&&"path"in s){if(!f.find((c)=>J(c)&&("path"in c)&&c.path===s.path))f.push(s)}else if(!f.some((c)=>tn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function lf(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:zr(t,i);if(Array.isArray(t))return r==="replace"?i:zr(t,i);if(!J(i)||!J(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=zr(s,f);else if(J(f)&&J(s))n[e]=lf(s,f,r);else n[e]=f}return n}function tn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!tn(t[r],i[r]))return!1;return!0}if(J(t)&&J(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!tn(t[e],i[e]))return!1}return!0}return!1}function J(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Kr(t,i,r="replace"){if(!kl(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return lf(i,e,r)}catch{return null}}catch{return null}}function lo(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let u=[...c,h],y=(w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase(),o=`${n}_${u.map(y).join("_")}`,m=`${n}_${u.map((w)=>w.toUpperCase()).join("_")}`;if(r)ft.info(`Checking environment variable ${o} for config ${t}.${u.join(".")}`);if(typeof a==="object"&&a!==null&&!Array.isArray(a))l[h]=f(a,u);else{let w=nr.env[o]||nr.env[m];if(w!==void 0){if(r)ft.info(`Using environment variable ${w?o:m} for config ${t}.${u.join(".")}`);if(typeof a==="number")l[h]=Number(w);else if(typeof a==="boolean")l[h]=w.toLowerCase()==="true";else if(Array.isArray(a))try{let d=JSON.parse(w);if(Array.isArray(d))l[h]=d;else l[h]=w.split(",").map((A)=>A.trim())}catch{l[h]=w.split(",").map((d)=>d.trim())}else l[h]=w}}}return l}return f(e)}async function co({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?lo(t,e,f):e,h=r||nr.cwd(),a=[".ts",".js",".mjs",".cjs",".json"];if(f)ft.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let u=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),o=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],w=Array.from(new Set([h,ht(h,"config"),ht(h,".config"),n?ht(h,n):void 0].filter(Boolean)));for(let d of w){if(f)ft.info(`Searching for configuration in: ${d}`);let A=[ht(h,"config"),ht(h,".config")].concat(n?[ht(h,n)]:[]).includes(d)?[...u,...y,...o,...m]:[...y,...u,...m,...o];for(let T of A)for(let Y of a){let g=ht(d,`${T}${Y}`),X=await Kr(g,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from: ${g}`);return X}}}if(t){let d=ht(de(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)ft.info(`Checking user config directory: ${d}`);for(let T of A)for(let Y of a){let g=ht(d,`${T}${Y}`),X=await Kr(g,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from user config directory: ${g}`);return X}}}if(t){let d=ht(de(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)ft.info(`Checking user config directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let g=ht(d,`${T}${Y}`),X=await Kr(g,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from user config directory dotfile: ${g}`);return X}}}if(t){let d=de(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)ft.info(`Checking user home directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let g=ht(d,`${T}${Y}`),X=await Kr(g,l,c);if(X!==null){if(f)ft.success(`Configuration loaded from user home directory: ${g}`);return X}}}try{let d=ht(h,"package.json");if(kl(d)){let A=await import(d),T=A[t];if(!T&&i){if(T=A[i],T&&f)ft.success(`Using alias "${i}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(f)ft.success(`Configuration loaded from package.json: ${T===A[t]?t:i}`);return lf(l,T,c)}catch(Y){if(f)ft.warn("Failed to merge package.json config:",Y)}}}catch(d){if(f)ft.warn("Failed to load package.json:",d)}if(f)ft.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function ho(t,i={}){let r=br.cwd();while(r.includes("storage"))r=qs(r,"..");let n=qs(r,t||"");if(i?.relative)return yu(br.cwd(),n);return n}async function ao(){try{let t=await co({name:"clarity",alias:"logging",defaultConfig:xr,cwd:br.cwd()});return{...xr,...t||{}}}catch{return xr}}function V(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function uo(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Vt<"u"){let t=Vt.type;if(t==="renderer"||t==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class vl{async format(t){let i=await uo(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Ui.pid,hostname:i(),environment:Ui.env.NODE_ENV||"development",platform:Ui.platform,version:Ui.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Ui.env.NODE_ENV||Ui.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...qe},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new vl,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...qr,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...qr};return{...qr,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:qe.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!V()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Uu(this.config.logDirectory,il.F_OK|il.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await Fu(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:qt.from(t);try{if(!Ur(this.currentLogFile))await Be(this.currentLogFile,"",{mode:420});if(n=tl(this.currentLogFile,"a",420),Yu(n,c,{flag:"a"}),Zs(n),n!==void 0)ge(n),n=void 0;if((await Ri(this.currentLogFile)).size===0){if(await Be(this.currentLogFile,c,{flag:"w",mode:420}),(await Ri(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let a=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,a);let u=s*2**e;await new Promise((y)=>setTimeout(y,u)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{ge(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,a=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",a),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Yi(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 Yi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Yi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(V())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Se(16).toString("hex")}generateKey(){return Se(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Se(16),n=gu("aes-256-gcm",i,r),e=qt.isBuffer(t)?t:qt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=qt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=nl(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(qt.from(qt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(V())return;if(!this.shouldWriteToFile())return;let t=await Ri(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Fr(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ri(r).catch(()=>null))try{if(await rl(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Nr(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Be(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ri(r).catch(()=>null))await rl(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await Fr(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Nr(Yi(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=Qs(t),n=Ru(i),e=nl();await Wu(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Ur(this.currentLogFile))try{let t=tl(this.currentLogFile,"r+");Zs(t),ge(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!V()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await Fr(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Nr(Yi(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?U.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||V())return!1;let t=typeof _.env.NO_COLOR<"u",i=_.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(o)=>o.replace(this.ANSI_PATTERN,"");if(!this.fancy){let o=[];if(s)o.push(i);if(f==="warning")o.push("WARN");else if(f==="error")o.push("ERROR");else if(r)o.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)o.push(n.replace(/[[\]]/g,""));return o.push(e),o.join(" ")}let l=_.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${U.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,u=c(i).length,y=Math.max(1,l-2-a-u);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=U.underline(U.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>U.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>U.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>U.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>U.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>U.strikethrough(n)),i}supportsHyperlinks(){if(V())return!1;let t=_.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=_.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Nu(i)||i.startsWith("./")||i.startsWith("../"))i=ju(i);else return null;return Ur(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":lc[t],y=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:U.gray(l),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.warn(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:U.green(l),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.error(o),c){let m=c.split(`
|
|
14
|
+
`);for(let w of m)if(w.trim()&&!w.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:U.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!V()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let a=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
15
15
|
`;if(c)a+=`${c}
|
|
16
|
-
`;if(a=a.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(a)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!
|
|
17
|
-
`);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!
|
|
18
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":U.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!
|
|
19
|
-
`),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(
|
|
21
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=U.green("━".repeat(n)),s=U.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?U.green("✓"):U.blue("▶"),
|
|
22
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||
|
|
16
|
+
`;if(a=a.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(a)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!V()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!V()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!V()&&_.stdout.isTTY)_.stdout.write(`
|
|
17
|
+
`);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!V()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":U.blue("◐"),tag:r,message:`${U.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
18
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":U.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!V())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new rn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(V())throw Error("createReadStream is not supported in browser environments");if(!Ur(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Qs(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=qt.isBuffer(t)?t:qt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Bu("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),a=l.length+h.length,u=qt.allocUnsafe(a);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return V()}isServerMode(){return!V()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
|
|
19
|
+
`),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,u=c.map((y)=>{return this.formatConsoleMessage({timestamp:r,message:U.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(h),showTimestamp:!1})),u.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:U.cyan(a),showTimestamp:!1}))}else if(!V())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
|
|
20
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(V())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${U.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();_.stdin.removeListener("data",r);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let a=i[c++];switch(h){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?U.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${U.blue("◐")} `;console.error(`${c}${s} ${U.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
|
|
21
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=U.green("━".repeat(n)),s=U.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?U.green("✓"):U.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${U.gray(this.formatTag(this.name))}`:"",y=`\r${a}${u} ${c} ${l}${h}`,o=_.stdout.columns||80,m=" ".repeat(Math.max(0,o-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,_.stdout.write(t.lastRenderedLine),i)_.stdout.write(`
|
|
22
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||V()||!_.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(V()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Fr(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Yi(this.config.logDirectory,n);if(t.before)try{if((await Ri(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Nr(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function Ql(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function Zl(t){return t instanceof dt}function oo(t){return t instanceof nn}function yo(t){if(Zl(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((i)=>t.message.toLowerCase().includes(i.toLowerCase()))}class on{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let a=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],a,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return lr.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((a)=>this.formatEnvKey(a,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((a)=>a.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let a=jr.env[l]||(h?jr.env[h]:void 0);if(a!==void 0){if(n.verbose){let u=jr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(a,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof en)throw u;throw ci.envVar(l,a,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw ci.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(jr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
|
|
23
23
|
|
|
24
24
|
`;for(let n of t)r+=`${n.key}
|
|
25
25
|
`,r+=` Type: ${n.type}
|
|
@@ -31,25 +31,25 @@ import{Da as O,Fa as yr,Ga as $,Ka as aa,La as os,Na as re,Oa as oa,Qa as Ea,Ra
|
|
|
31
31
|
`;r+=`| Variable | Type | Description | Example |
|
|
32
32
|
`,r+=`|----------|------|-------------|----------|
|
|
33
33
|
`;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
34
|
-
`;return r}}function ou(t,i){let r=ic("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function vl(t,i,r={}){return Ql(t,i,r,new WeakMap)}function Ql(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Zl(t,i,e,n);if(!St(i)||!St(t))return i;return $u(t,i,r,n)}function Zl(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return uu(t,i);case"smart":return yu(t,i,n);default:return i}return i}function uu(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Le(e,n)))r.push(n);return r}function yu(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(St(i[0])&&St(t[0]))return wu(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function wu(t,i,r){let n=[...i];for(let e of t){if(!St(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>St(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function $u(t,i,r,n){let e=i;if(St(e)&&n.has(e))return n.get(e);let f={...t};if(St(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(St(c)&&St(l))f[s]=Ql(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Zl(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function lf(t,i,r="replace"){return vl(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Le(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Le(t[r],i[r]))return!1;return!0}if(St(t)&&St(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Le(t[e],i[e]))return!1}return!0}return!1}function St(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class yn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Xi.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Wr(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),o=a.default||a,y="default"in a,u=Object.keys(a).length>0;if(!y&&!u)throw new er(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new er(t,Error("Configuration must export a valid object"),"unknown");let m={config:lf(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Xi.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?ci.configLoad(t,h):ci.configLoad(t,Error(String(h)))}};if(s)return lr.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Be(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return Vl(async()=>{return Wr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Wr(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Be(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Be(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Wr(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class cf{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],o=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return a.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:a,warnings:o}}};if(c)return await lr.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!No(i))throw new fr(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new fr(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:sc},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class hf{fileLoader=new yn;envProcessor=new un;validator=new cf;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(o&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)_t.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw _t.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,o=f||di.cwd(),y=[],u=await this.loadLocalConfiguration(n,e,o,s,c,h,a,l,r);if(u)return y.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(u,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,o,c,h,a,l);if(w)return y.push(at(o,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,o,s)),i)throw ci.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?tr(t,e,s):e,a=this.getLocalDirectories(r,n);for(let o of a){if(s)_t.info(`Searching for configuration in: ${o}`);let y=this.fileLoader.generateConfigPaths(t,o,i),u=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(s)_t.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?tr(t,r,e):r,c=[at(Ci(),".config",t),at(Ci(),".config"),Ci()];for(let l of c){if(e)_t.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)_t.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?tr(t,n,f):n;try{let l=at(r,"package.json");if(!Me(l))return null;let h=await import(l),a=h[t],o=t;if(!a&&i)a=h[i],o=i;if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)_t.success(`Configuration loaded from package.json: ${o}`);return{config:lf(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)_t.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:tr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw ci.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Xi.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Xi.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,at(t,"config"),at(t,".config"),i?at(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(at(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[at(Ci(),".config",t),at(Ci(),".config"),Ci()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function hl(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||r}async function mu(t){return vt.loadConfig({...t,__strictErrorHandling:!0})}async function tc(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await vt.loadConfig(t);else n=await vt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)_t.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await vt.applyEnvironmentVariables(s.name||"",i,!0,s.verbose||!1))?.config??i;return i}}async function du(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await vt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&hl(r)))return(await vt.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await vt.loadConfig({...t,cwd:t.cwd||di.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&hl(i)))return(await vt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function Au(t,i,r="replace"){let n=new yn;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function tr(t,i,r=!1){let n=new un,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((w)=>w.toUpperCase()).join("")}`,`${e}_${o.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let w of y)if(u=di.env[w],u!==void 0){m=w;break}if(u!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(u.toLowerCase());else if(typeof a==="number"){let w=Number(u);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(u)}catch{l[h]=u.split(",").map((w)=>w.trim())}else l[h]=u;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,o)}return l}return f(i)}function Eu(t){let i=at(di.cwd(),t.configDir),r=at(di.cwd(),t.generatedDir),n=at(r,"config-types.ts");if(!Me(zs(n)))fo(zs(n),{recursive:!0,mode:511});let e=Me(i)?so(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${pu}
|
|
34
|
+
`;return r}}function wo(t,i){let r=ec("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function tc(t,i,r={}){return ic(t,i,r,new WeakMap)}function ic(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return rc(t,i,e,n);if(!Bt(i)||!Bt(t))return i;return Eo(t,i,r,n)}function rc(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return $o(t,i);case"smart":return mo(t,i,n);default:return i}return i}function $o(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Ge(e,n)))r.push(n);return r}function mo(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Bt(i[0])&&Bt(t[0]))return Ao(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function Ao(t,i,r){let n=[...i];for(let e of t){if(!Bt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>Bt(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function Eo(t,i,r,n){let e=i;if(Bt(e)&&n.has(e))return n.get(e);let f={...t};if(Bt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Bt(c)&&Bt(l))f[s]=ic(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=rc(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function cf(t,i,r="replace"){return tc(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Ge(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Ge(t[r],i[r]))return!1;return!0}if(Bt(t)&&Bt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Ge(t[e],i[e]))return!1}return!0}return!1}function Bt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class yn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Xi.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Wr(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),u=a.default||a,y="default"in a,o=Object.keys(a).length>0;if(!y&&!o)throw new er(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new er(t,Error("Configuration must export a valid object"),"unknown");let m={config:cf(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Xi.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?ci.configLoad(t,h):ci.configLoad(t,Error(String(h)))}};if(s)return lr.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Re(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return Ql(async()=>{return Wr(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Wr(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Re(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Re(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Wr(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class hf{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],u=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(o){return a.push({path:"",message:`Validation failed: ${o}`,rule:"system"}),{isValid:!1,errors:a,warnings:u}}};if(c)return await lr.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!Xu(i))throw new fr(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new fr(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:hc},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class af{fileLoader=new yn;envProcessor=new on;validator=new hf;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(u&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)_t.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw _t.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,u=f||di.cwd(),y=[],o=await this.loadLocalConfiguration(n,e,u,s,c,h,a,l,r);if(o)return y.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(o,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,u,c,h,a,l);if(w)return y.push(at(u,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,u,s)),i)throw ci.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?tr(t,e,s):e,a=this.getLocalDirectories(r,n);for(let u of a){if(s)_t.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),o=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(o){if(s)_t.success(`Configuration loaded from: ${o.source.path}`);return o}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?tr(t,r,e):r,c=[at(Ci(),".config",t),at(Ci(),".config"),Ci()];for(let l of c){if(e)_t.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)_t.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?tr(t,n,f):n;try{let l=at(r,"package.json");if(!ze(l))return null;let h=await import(l),a=h[t],u=t;if(!a&&i)a=h[i],u=i;if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)_t.success(`Configuration loaded from package.json: ${u}`);return{config:cf(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)_t.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:tr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw ci.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Xi.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Xi.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,at(t,"config"),at(t,".config"),i?at(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(at(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[at(Ci(),".config",t),at(Ci(),".config"),Ci()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function ol(t){let i=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),r=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return i||r}async function To(t){return vt.loadConfig({...t,__strictErrorHandling:!0})}async function nc(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await vt.loadConfig(t);else n=await vt.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)_t.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let s=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await vt.applyEnvironmentVariables(s.name||"",i,!0,s.verbose||!1))?.config??i;return i}}async function Co(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await vt.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&ol(r)))return(await vt.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await vt.loadConfig({...t,cwd:t.cwd||di.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&ol(i)))return(await vt.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function So(t,i,r="replace"){let n=new yn;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function tr(t,i,r=!1){let n=new on,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let u=[...c,h],y=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((w)=>w.toUpperCase()).join("")}`,`${e}_${u.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],o,m;for(let w of y)if(o=di.env[w],o!==void 0){m=w;break}if(o!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(o.toLowerCase());else if(typeof a==="number"){let w=Number(o);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(o)}catch{l[h]=o.split(",").map((w)=>w.trim())}else l[h]=o;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,u)}return l}return f(i)}function go(t){let i=at(di.cwd(),t.configDir),r=at(di.cwd(),t.generatedDir),n=at(r,"config-types.ts");if(!ze(xs(n)))hu(xs(n),{recursive:!0,mode:511});let e=ze(i)?au(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${Qo}
|
|
35
35
|
export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
|
|
36
|
-
`;
|
|
37
|
-
${e.map((l)=>{let h=
|
|
36
|
+
`;uu(n,f,{mode:438})}function Bo(t){let i=null,r=null,n=()=>{if(!r)r=nc(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)_t.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function Ro(t){let i=el(Ju.cwd(),t?.configDir||"./config");function r(){if(!_u(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Iu(i).filter((l)=>e.has(Ye(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let a=Ye(h).toLowerCase(),u=c.get(l);if(!u){c.set(l,h);continue}let y=Ye(u).toLowerCase();if(f.indexOf(a)<f.indexOf(y))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((l)=>l.base),s=f.length?f.map((l)=>`'${l}'`).join(" | "):"string",c=e.length?`{
|
|
37
|
+
${e.map((l)=>{let h=el(i,l.file).replace(/\\/g,"/");return` '${l.base}': typeof import('${h}').default`}).join(`,
|
|
38
38
|
`)}
|
|
39
39
|
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
40
40
|
export type ConfigByName = ${c}
|
|
41
41
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
42
42
|
export type ConfigOf = Config
|
|
43
|
-
`}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var ic,Xi,lr,rc,gu,Su,al,Lr,Ge,et,M,Bu,ol,Ru,ul,Yu,Uu,je,Fu,yl,wl,We,Nu,ju,Wu,Xu,Gr,nc,_u,ft,Iu,Ju,$l,xr,xe,V,U,Ou,ml,Hu,dl,Ku,Mu,Xe,zu,Al,El,Lu,_e,Gu,xu,qu,ku,bu,qr,ec,Du,pu="0.15.6",dt,nn,er,qe,ke,en,be,De,fr,pe,Ve,ci,fc,sc,_t,vt,lc,cc,Vu=Vo(async()=>{ic=import.meta.require,Xi=new nf,lr=new ef,rc={createKey:Po,isEquivalent:vo,estimateMemoryUsage:Qo},gu=Vr(ze.cwd(),"config"),Su=Vr(ze.cwd(),"src/generated"),al=pr.env.CLARITY_LOG_DIR||ao(iu(),"logs"),Lr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:al,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Ge=await ru(),et={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},M=et,Bu=et.red,ol=et.green,Ru=et.yellow,ul=et.blue,Yu=et.magenta,Uu=et.cyan,je=et.white,Fu=et.gray,yl=et.bgRed,wl=et.bgYellow,We=et.bold,Nu=et.dim,ju=et.italic,Wu=et.underline,Xu=et.reset,Gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nc={debug:"\uD83D\uDD0D",info:ul("ℹ"),success:ol("✓"),warning:wl(je(We(" WARN "))),error:yl(je(We(" ERROR ")))},_u=new Zr("stacks"),ft=new Zr("bunfig",{showTags:!0}),Iu=ht(nr.cwd(),"config"),Ju=ht(nr.cwd(),"src/generated"),$l=Dr.env.CLARITY_LOG_DIR||co(su(),"logs"),xr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$l,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},xe=await lu(),V={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},U=V,Ou=V.red,ml=V.green,Hu=V.yellow,dl=V.blue,Ku=V.magenta,Mu=V.cyan,Xe=V.white,zu=V.gray,Al=V.bgRed,El=V.bgYellow,Lu=V.bgGray,_e=V.bold,Gu=V.dim,xu=V.italic,qu=V.underline,ku=V.strikethrough,bu=V.reset,qr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ec={debug:"\uD83D\uDD0D",info:dl("ℹ"),success:ml("✓"),warning:El(Xe(_e(" WARN "))),error:Al(Xe(_e(" ERROR ")))},Du=new rn("stacks"),dt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},nn=class extends dt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}},er=class extends dt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},qe=class extends dt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}},ke=class extends dt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},en=class extends dt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}},be=class extends dt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}},De=class extends dt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}},fr=class extends dt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}},pe=class extends dt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}},Ve=class extends dt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}},ci={configNotFound(t,i,r){return new nn(t,i,r)},configLoad(t,i,r){return new er(t,i,r)},configValidation(t,i,r){return new qe(t,i,r)},configMerge(t,i,r,n){return new ke(t,i,r,n)},envVar(t,i,r,n){return new en(t,i,r,n)},fileSystem(t,i,r){return new be(t,i,r)},typeGeneration(t,i,r){return new De(t,i,r)},schemaValidation(t,i,r){return new fr(t,i,r)},browserConfig(t,i,r,n){return new pe(t,i,r,n)},plugin(t,i,r){return new Ve(t,i,r)}},fc={replace:"replace",concat:"concat",smart:"smart"},sc=/^https?:\/\//,_t=new rn("bunfig",{showTags:!0}),vt=new hf,lc=at(di.cwd(),"config"),cc=at(di.cwd(),"src/generated")});function Pu(t,i={}){let r=Pr.cwd();while(r.includes("storage"))r=rl(r,"..");let n=rl(r,t||"");if(i?.relative)return Io(Pr.cwd(),n);return n}var vu=Pr.env.CLARITY_LOG_DIR||_o(Pu(),"logs"),hc={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:vu,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},fn={...hc},Yd=(async()=>{try{let{loadConfig:t}=await Vu().then(()=>bl),i=await t({name:"clarity",alias:"logging",defaultConfig:hc,cwd:Pr.cwd()});if(i)Object.assign(fn,i)}catch{}return fn})();function P(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Qu(){if(Vt.env.NODE_ENV==="test"||Vt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Vt<"u"){let t=Vt.type;if(t==="renderer"||t==="worker")return!1;return!!(Vt.versions&&(Vt.versions.node||Vt.versions.bun))}return!1}class ac{async format(t){let i=await Qu(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ji.pid,hostname:i(),environment:ji.env.NODE_ENV||"development",platform:ji.platform,version:ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ji.env.NODE_ENV||ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},j=it,Ud=it.red,Zu=it.green,Fd=it.yellow,ty=it.blue,Nd=it.magenta,jd=it.cyan,Tl=it.white,Wd=it.gray,iy=it.bgRed,ry=it.bgYellow,Xd=it.bgGray,Cl=it.bold,_d=it.dim,Id=it.italic,Jd=it.underline,Od=it.strikethrough,Hd=it.reset,Ie={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ny={debug:"\uD83D\uDD0D",info:ty("ℹ"),success:Zu("✓"),warning:ry(Tl(Cl(" WARN "))),error:iy(Tl(Cl(" ERROR ")))};class wn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...fn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new ac,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Ie,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Ie};return{...Ie,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:fn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Mo(this.config.logDirectory,sl.F_OK|sl.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await zo(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:kt.from(t);try{if(!Xr(this.currentLogFile))await Fe(this.currentLogFile,"",{mode:420});if(n=fl(this.currentLogFile,"a",420),Ko(n,c,{flag:"a"}),el(n),n!==void 0)Ue(n),n=void 0;if((await Fi(this.currentLogFile)).size===0){if(await Fe(this.currentLogFile,c,{flag:"w",mode:420}),(await Fi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let a=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,a);let o=s*2**e;await new Promise((y)=>setTimeout(y,o)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{Ue(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,a=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",a),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ni(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 Ni(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ni(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ye(16).toString("hex")}generateKey(){return Ye(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ye(16),n=Jo("aes-256-gcm",i,r),e=kt.isBuffer(t)?t:kt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=kt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=cl(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(kt.from(kt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await Fi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await _r(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Fi(r).catch(()=>null))try{if(await ll(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Ir(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Fe(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Fi(r).catch(()=>null))await ll(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await _r(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Ir(Ni(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=nl(t),n=Ho(i),e=cl();await xo(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Xr(this.currentLogFile))try{let t=fl(this.currentLogFile,"r+");el(t),Ue(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await _r(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Ir(Ni(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?j.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof I.env.NO_COLOR<"u",i=I.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=I.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${j.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=j.underline(j.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>j.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>j.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>j.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>j.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>j.strikethrough(n)),i}supportsHyperlinks(){if(P())return!1;let t=I.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=I.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Lo(i)||i.startsWith("./")||i.startsWith("../"))i=Go(i);else return null;return Xr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":ny[t],y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:j.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:j.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.error(u),c){let m=c.split(`
|
|
43
|
+
`}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var ec,Xi,lr,fc,Yo,Uo,yl,Lr,xe,et,M,Fo,wl,No,$l,jo,Wo,We,Xo,ml,dl,Xe,_o,Io,Jo,Oo,Gr,sc,Ko,ft,Ho,Mo,Al,xr,qe,p,U,zo,El,Lo,Tl,Go,xo,_e,qo,Cl,Sl,ko,Ie,Do,bo,Vo,po,Po,qr,lc,vo,Qo="0.15.6",dt,nn,er,ke,De,en,be,Ve,fr,pe,Pe,ci,cc,hc,_t,vt,ac,uc,Zo=Qu(async()=>{ec=import.meta.require,Xi=new ef,lr=new ff,fc={createKey:Zu,isEquivalent:to,estimateMemoryUsage:io},Yo=pr(Le.cwd(),"config"),Uo=pr(Le.cwd(),"src/generated"),yl=Vr.env.CLARITY_LOG_DIR||wu(eo(),"logs"),Lr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:yl,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},xe=await fo(),et={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},M=et,Fo=et.red,wl=et.green,No=et.yellow,$l=et.blue,jo=et.magenta,Wo=et.cyan,We=et.white,Xo=et.gray,ml=et.bgRed,dl=et.bgYellow,Xe=et.bold,_o=et.dim,Io=et.italic,Jo=et.underline,Oo=et.reset,Gr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sc={debug:"\uD83D\uDD0D",info:$l("ℹ"),success:wl("✓"),warning:dl(We(Xe(" WARN "))),error:ml(We(Xe(" ERROR ")))},Ko=new Zr("stacks"),ft=new Zr("bunfig",{showTags:!0}),Ho=ht(nr.cwd(),"config"),Mo=ht(nr.cwd(),"src/generated"),Al=br.env.CLARITY_LOG_DIR||ou(ho(),"logs"),xr={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Al,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},qe=await ao(),p={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},U=p,zo=p.red,El=p.green,Lo=p.yellow,Tl=p.blue,Go=p.magenta,xo=p.cyan,_e=p.white,qo=p.gray,Cl=p.bgRed,Sl=p.bgYellow,ko=p.bgGray,Ie=p.bold,Do=p.dim,bo=p.italic,Vo=p.underline,po=p.strikethrough,Po=p.reset,qr={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lc={debug:"\uD83D\uDD0D",info:Tl("ℹ"),success:El("✓"),warning:Sl(_e(Ie(" WARN "))),error:Cl(_e(Ie(" ERROR ")))},vo=new rn("stacks"),dt=class extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}},nn=class extends dt{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r?` or alias "${r}"`:"";super(`Configuration "${t}"${n} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}},er=class extends dt{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}},ke=class extends dt{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}},De=class extends dt{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},en=class extends dt{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}},be=class extends dt{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}},Ve=class extends dt{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}},fr=class extends dt{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}},pe=class extends dt{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}},Pe=class extends dt{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}},ci={configNotFound(t,i,r){return new nn(t,i,r)},configLoad(t,i,r){return new er(t,i,r)},configValidation(t,i,r){return new ke(t,i,r)},configMerge(t,i,r,n){return new De(t,i,r,n)},envVar(t,i,r,n){return new en(t,i,r,n)},fileSystem(t,i,r){return new be(t,i,r)},typeGeneration(t,i,r){return new Ve(t,i,r)},schemaValidation(t,i,r){return new fr(t,i,r)},browserConfig(t,i,r,n){return new pe(t,i,r,n)},plugin(t,i,r){return new Pe(t,i,r)}},cc={replace:"replace",concat:"concat",smart:"smart"},hc=/^https?:\/\//,_t=new rn("bunfig",{showTags:!0}),vt=new af,ac=at(di.cwd(),"config"),uc=at(di.cwd(),"src/generated")});function ty(t,i={}){let r=Pr.cwd();while(r.includes("storage"))r=fl(r,"..");let n=fl(r,t||"");if(i?.relative)return Ku(Pr.cwd(),n);return n}var iy=Pr.env.CLARITY_LOG_DIR||Ou(ty(),"logs"),oc={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:iy,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},fn={...oc},Wd=(async()=>{try{let{loadConfig:t}=await Zo().then(()=>pl),i=await t({name:"clarity",alias:"logging",defaultConfig:oc,cwd:Pr.cwd()});if(i)Object.assign(fn,i)}catch{}return fn})();function P(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ry(){if(pt.env.NODE_ENV==="test"||pt.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pt<"u"){let t=pt.type;if(t==="renderer"||t==="worker")return!1;return!!(pt.versions&&(pt.versions.node||pt.versions.bun))}return!1}class yc{async format(t){let i=await ry(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ji.pid,hostname:i(),environment:ji.env.NODE_ENV||"development",platform:ji.platform,version:ji.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ji.env.NODE_ENV||ji.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var it={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},j=it,Xd=it.red,ny=it.green,_d=it.yellow,ey=it.blue,Id=it.magenta,Jd=it.cyan,gl=it.white,Od=it.gray,fy=it.bgRed,sy=it.bgYellow,Kd=it.bgGray,Bl=it.bold,Hd=it.dim,Md=it.italic,zd=it.underline,Ld=it.strikethrough,Gd=it.reset,Je={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},ly={debug:"\uD83D\uDD0D",info:ey("ℹ"),success:ny("✓"),warning:sy(gl(Bl(" WARN "))),error:fy(gl(Bl(" ERROR ")))};class wn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...fn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new yc,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??I.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Je,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Je};return{...Je,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:fn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!P()&&this.config.writeToFile===!0}async writeToFile(t){let i=(async()=>{let n,e=0,f=3,s=1000;while(e<f)try{try{try{await Gu(this.config.logDirectory,hl.F_OK|hl.W_OK)}catch(l){if(l instanceof Error&&"code"in l)if(l.code==="ENOENT")await xu(this.config.logDirectory,{recursive:!0,mode:493});else if(l.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw l;else throw l}}catch(l){throw console.error("Debug: [writeToFile] Failed to create log directory:",l),l}let c=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:kt.from(t);try{if(!Xr(this.currentLogFile))await Ne(this.currentLogFile,"",{mode:420});if(n=cl(this.currentLogFile,"a",420),Lu(n,c,{flag:"a"}),ll(n),n!==void 0)Fe(n),n=void 0;if((await Fi(this.currentLogFile)).size===0){if(await Ne(this.currentLogFile,c,{flag:"w",mode:420}),(await Fi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(l){let h=l;if(h.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(h.code)){if(e<f-1){let a=typeof h.message==="string"?h.message:"Unknown error";console.error(`Network error during write attempt ${e+1}/${f}:`,a);let u=s*2**e;await new Promise((y)=>setTimeout(y,u)),e++;continue}}if(h?.code&&["ENOSPC","EDQUOT"].includes(h.code))throw Error(`Disk quota exceeded or no space left on device: ${h.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",h),h}finally{if(n!==void 0)try{Fe(n)}catch(l){console.error("Debug: [writeToFile] Error closing file descriptor:",l)}}}catch(c){if(e===f-1){let h=c,a=typeof h.message==="string"?h.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",a),c}e++;let l=s*2**(e-1);await new Promise((h)=>setTimeout(h,l))}})();this.pendingOperations.push(i);let r=this.pendingOperations.length-1;try{await i}catch(n){throw console.error("Debug: [writeToFile] Error in operation:",n),n}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ni(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 Ni(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ni(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(P())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let t=this.config.rotation.keyRotation;if(!t?.enabled)return;let i=typeof t.interval==="number"?t.interval:60,r=Math.max(i,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((n)=>{console.error("Error rotating keys:",n)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let t=this.config.rotation.keyRotation,i=this.generateKeyId(),r=this.generateKey();this.currentKeyId=i,this.keys.set(i,r),this.encryptionKeys.set(i,{key:r,createdAt:new Date});let n=Array.from(this.encryptionKeys.entries()).sort(([,s],[,c])=>c.createdAt.getTime()-s.createdAt.getTime()),e=typeof t.maxKeys==="number"?t.maxKeys:1,f=Math.max(1,e);if(n.length>f)for(let[s]of n.slice(f))this.encryptionKeys.delete(s),this.keys.delete(s)}generateKeyId(){return Ue(16).toString("hex")}generateKey(){return Ue(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ue(16),n=Hu("aes-256-gcm",i,r),e=kt.isBuffer(t)?t:kt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=kt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=ul(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(kt.from(kt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(P())return;if(!this.shouldWriteToFile())return;let t=await Fi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await _r(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Fi(r).catch(()=>null))try{if(await al(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Ir(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Ne(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Fi(r).catch(()=>null))await al(r,f)}if(this.currentLogFile=n,i.maxFiles){let e=(await _r(this.config.logDirectory)).filter((f)=>f.startsWith(this.name)).sort((f,s)=>s.localeCompare(f));for(let f of e.slice(i.maxFiles))await Ir(Ni(this.config.logDirectory,f))}}}async compressLogFile(t,i){let r=sl(t),n=zu(i),e=ul();await Du(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Xr(this.currentLogFile))try{let t=cl(this.currentLogFile,"r+");ll(t),Fe(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!P()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let t=(await _r(this.config.logDirectory)).filter((i)=>(i.includes("temp")||i.includes(".tmp"))&&i.includes(this.name));for(let i of t)try{await Ir(Ni(this.config.logDirectory,i))}catch(r){console.error(`Failed to delete temp file ${i}:`,r)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?j.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||P())return!1;let t=typeof I.env.NO_COLOR<"u",i=I.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof I.stderr<"u"&&I.stderr.isTTY||typeof I.stdout<"u"&&I.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(o)=>o.replace(this.ANSI_PATTERN,"");if(!this.fancy){let o=[];if(s)o.push(i);if(f==="warning")o.push("WARN");else if(f==="error")o.push("ERROR");else if(r)o.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)o.push(n.replace(/[[\]]/g,""));return o.push(e),o.join(" ")}let l=I.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${j.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,u=c(i).length,y=Math.max(1,l-2-a-u);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=j.underline(j.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>j.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>j.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>j.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>j.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>j.strikethrough(n)),i}supportsHyperlinks(){if(P())return!1;let t=I.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=I.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(qu(i)||i.startsWith("./")||i.startsWith("../"))i=ku(i);else return null;return Xr(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":ly[t],y=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:j.gray(l),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.warn(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:j.green(l),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.error(o),c){let m=c.split(`
|
|
44
44
|
`);for(let w of m)if(w.trim()&&!w.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:j.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!P()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let a=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
45
45
|
`;if(c)a+=`${c}
|
|
46
46
|
`;if(a=a.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(a)}progress(t,i=""){let r={update:(e,f)=>{},finish:(e)=>{},interrupt:(e,f)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!P()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(e,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,e),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!P()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(e)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,e)},interrupt:(e,f="info")=>{if(!P()&&I.stdout.isTTY)I.stdout.write(`
|
|
47
47
|
`);if(this[f==="warning"?"warn":f](e),this.activeProgressBar&&this.shouldStyleConsole()&&!P()&&I.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":j.blue("◐"),tag:r,message:`${j.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),l=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)l+=` ${JSON.stringify(r)}`;if(l+=`
|
|
48
|
-
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":j.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!P())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new wn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Xr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
49
|
-
`),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,
|
|
48
|
+
`,l=l.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let h=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":j.green("✓"),tag:h,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!P())console.error(l.trim());if(this.shouldWriteToFile())await this.writeToFile(l)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new wn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(P())throw Error("createReadStream is not supported in browser environments");if(!Xr(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return sl(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=kt.isBuffer(t)?t:kt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Mu("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),a=l.length+h.length,u=kt.allocUnsafe(a);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return P()}isServerMode(){return!P()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
|
|
49
|
+
`),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,u=c.map((y)=>{return this.formatConsoleMessage({timestamp:r,message:j.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:j.cyan(h),showTimestamp:!1})),u.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:j.cyan(a),showTimestamp:!1}))}else if(!P())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
|
|
50
50
|
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(P())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${j.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();I.stdin.removeListener("data",r);try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!1)}catch{}I.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof I.stdin.setRawMode==="function")I.stdin.setRawMode(!0)}catch{}I.stdin.resume(),I.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let a=i[c++];switch(h){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let s=this.options.showTags!==!1&&this.name?j.gray(this.formatTag(this.name)):"",c=this.options.showIcons===!1?"":`${j.blue("◐")} `;console.error(`${c}${s} ${j.cyan(n)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
|
|
51
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=j.green("━".repeat(n)),s=j.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?j.green("✓"):j.blue("▶"),
|
|
52
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!I.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await _r(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Ni(this.config.logDirectory,n);if(t.before)try{if((await Fi(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ir(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var
|
|
51
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(f)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!I.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=j.green("━".repeat(n)),s=j.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?j.green("✓"):j.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${j.gray(this.formatTag(this.name))}`:"",y=`\r${a}${u} ${c} ${l}${h}`,o=I.stdout.columns||80,m=" ".repeat(Math.max(0,o-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,I.stdout.write(t.lastRenderedLine),i)I.stdout.write(`
|
|
52
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||P()||!I.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(P()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await _r(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let e=Ni(this.config.logDirectory,n);if(t.before)try{if((await Fi(e)).mtime>=t.before)continue}catch(f){console.error(`Failed to get stats for file ${e}:`,f);continue}r.push(e)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Ir(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var xd=new wn("stacks");class Ot extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class wc extends Ot{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class sn extends Ot{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class $c extends Ot{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class mc extends Ot{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class uf extends Ot{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class dc extends Ot{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Ac extends Ot{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class ln extends Ot{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class Ec extends Ot{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class Tc extends Ot{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var _i={configNotFound(t,i,r){return new wc(t,i,r)},configLoad(t,i,r){return new sn(t,i,r)},configValidation(t,i,r){return new $c(t,i,r)},configMerge(t,i,r,n){return new mc(t,i,r,n)},envVar(t,i,r,n){return new uf(t,i,r,n)},fileSystem(t,i,r){return new dc(t,i,r)},typeGeneration(t,i,r){return new Ac(t,i,r)},schemaValidation(t,i,r){return new ln(t,i,r)},browserConfig(t,i,r,n){return new Ec(t,i,r,n)},plugin(t,i,r){return new Tc(t,i,r)}};async function cy(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class of{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let a=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],a,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return nf.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((a)=>this.formatEnvKey(a,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((a)=>a.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let a=Jr.env[l]||(h?Jr.env[h]:void 0);if(a!==void 0){if(n.verbose){let u=Jr.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(a,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof uf)throw u;throw _i.envVar(l,a,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw _i.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Jr.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
|
|
53
53
|
|
|
54
54
|
`;for(let n of t)r+=`${n.key}
|
|
55
55
|
`,r+=` Type: ${n.type}
|
|
@@ -61,30 +61,30 @@ export type ConfigOf = Config
|
|
|
61
61
|
`;r+=`| Variable | Type | Description | Example |
|
|
62
62
|
`,r+=`|----------|------|-------------|----------|
|
|
63
63
|
`;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
64
|
-
`;return r}}function fy(t,i,r={}){return Ac(t,i,r,new WeakMap)}function Ac(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Ec(t,i,e,n);if(!Bt(i)||!Bt(t))return i;return hy(t,i,r,n)}function Ec(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return sy(t,i);case"smart":return ly(t,i,n);default:return i}return i}function sy(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Pe(e,n)))r.push(n);return r}function ly(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Bt(i[0])&&Bt(t[0]))return cy(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function cy(t,i,r){let n=[...i];for(let e of t){if(!Bt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>Bt(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function hy(t,i,r,n){let e=i;if(Bt(e)&&n.has(e))return n.get(e);let f={...t};if(Bt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Bt(c)&&Bt(l))f[s]=Ac(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Ec(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function Tc(t,i,r="replace"){return fy(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Pe(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Pe(t[r],i[r]))return!1;return!0}if(Bt(t)&&Bt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Pe(t[e],i[e]))return!1}return!0}return!1}function Bt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Cc{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=vr.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Or(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),o=a.default||a,y="default"in a,u=Object.keys(a).length>0;if(!y&&!u)throw new sn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new sn(t,Error("Configuration must export a valid object"),"unknown");let m={config:Tc(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)vr.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?_i.configLoad(t,h):_i.configLoad(t,Error(String(h)))}};if(s)return rf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Ne(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return ey(async()=>{return Or(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Or(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Ne(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Ne(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Or(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var ay=/^https?:\/\//;class gc{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],o=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return a.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:a,warnings:o}}};if(c)return await rf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!qo(i))throw new ln(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new ln(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ay},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var bt=new wn("bunfig",{showTags:!0});function oy(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class Sc{fileLoader=new Cc;envProcessor=new of;validator=new gc;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(o&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)bt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw bt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,o=f||on.cwd(),y=[],u=await this.loadLocalConfiguration(n,e,o,s,c,h,a,l,r);if(u)return y.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(u,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,o,c,h,a,l);if(w)return y.push(gt(o,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,o,s)),i)throw _i.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${oy(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Kr(t,e,s):e,a=this.getLocalDirectories(r,n);for(let o of a){if(s)bt.info(`Searching for configuration in: ${o}`);let y=this.fileLoader.generateConfigPaths(t,o,i),u=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(s)bt.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Kr(t,r,e):r,c=[gt(Ti(),".config",t),gt(Ti(),".config"),Ti()];for(let l of c){if(e)bt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)bt.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Kr(t,n,f):n;try{let l=gt(r,"package.json");if(!no(l))return null;let h={};try{h=JSON.parse(eo(l,"utf8"))}catch(y){if(f)bt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let a=h[t],o=t;if(!a&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if(h[u]){a=h[u],o=u;break}}}if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)bt.success(`Configuration loaded from package.json: ${o}`);return{config:Tc(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)bt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Kr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw _i.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return vr.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);vr.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,gt(t,"config"),gt(t,".config"),i?gt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(gt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[gt(Ti(),".config",t),gt(Ti(),".config"),Ti()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var Md=new Sc;function Kr(t,i,r=!1){let n=new of,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((w)=>w.toUpperCase()).join("")}`,`${e}_${o.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let w of y)if(u=on.env[w],u!==void 0){m=w;break}if(u!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(u.toLowerCase());else if(typeof a==="number"){let w=Number(u);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(u)}catch{l[h]=u.split(",").map((w)=>w.trim())}else l[h]=u;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,o)}return l}return f(i)}var zd=gt(on.cwd(),"config"),Ld=gt(on.cwd(),"src/generated"),Bc={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:$e.join(we.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:$e.join(we.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:$e.join(we.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},b=Bc,It={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 C={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Wi={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function ve(t,i){let r=[];function n(e){let f;try{f=gl.readdirSync(e)}catch{return}for(let s of f){let c=Xt.join(e,s);try{if(gl.statSync(c).isDirectory())n(c);else if(s===i)r.push(e)}catch{continue}}}return n(t),r}function E(t,i,r){if(r||b.verbose)console.debug(`[tlsx:${t}] ${i}`)}var $y=wy(uy);function Yc(){return Rc.env.SUDO_PASSWORD}var Sl="[redacted]",my=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),dy=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Ay(t){let i=t.toLowerCase();return my.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function cn(t){if(Array.isArray(t))return t.map((r)=>cn(r));if(typeof t==="string")return dy.test(t)?Sl:t;if(!t||typeof t!=="object")return t;let i={};for(let[r,n]of Object.entries(t)){if(Ay(r)){i[r]=Sl;continue}i[r]=cn(n)}return i}function $n(t){return JSON.stringify(cn(t))}function Ey(t){let i=Yc();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let r=i.replace(/'/g,"'\\''"),n=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function li(t,i={}){let r=Ey(t);try{let{stdout:n,stderr:e}=await $y(r,{cwd:i.cwd||Rc.cwd(),timeout:i.timeout||30000});return{stdout:n.trim(),stderr:e.trim()}}catch(n){let e=Error(`Failed to execute command: ${t}
|
|
65
|
-
Error: ${n.message}`);throw e.stack=n.stack,e}}function
|
|
64
|
+
`;return r}}function hy(t,i,r={}){return Cc(t,i,r,new WeakMap)}function Cc(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Sc(t,i,e,n);if(!Rt(i)||!Rt(t))return i;return yy(t,i,r,n)}function Sc(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return ay(t,i);case"smart":return uy(t,i,n);default:return i}return i}function ay(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>ve(e,n)))r.push(n);return r}function uy(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Rt(i[0])&&Rt(t[0]))return oy(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function oy(t,i,r){let n=[...i];for(let e of t){if(!Rt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((l)=>Rt(l)&&(c in l)&&l[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function yy(t,i,r,n){let e=i;if(Rt(e)&&n.has(e))return n.get(e);let f={...t};if(Rt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Rt(c)&&Rt(l))f[s]=Cc(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Sc(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function gc(t,i,r="replace"){return hy(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function ve(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!ve(t[r],i[r]))return!1;return!0}if(Rt(t)&&Rt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!ve(t[e],i[e]))return!1}return!0}return!1}function Rt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class Bc{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=vr.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Or(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),u=a.default||a,y="default"in a,o=Object.keys(a).length>0;if(!y&&!o)throw new sn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new sn(t,Error("Configuration must export a valid object"),"unknown");let m={config:gc(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)vr.setWithFileCheck("file",m,t,f);return m}catch(h){throw h instanceof Error?_i.configLoad(t,h):_i.configLoad(t,Error(String(h)))}};if(s)return nf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(je(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return cy(async()=>{return Or(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Or(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=je(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=je(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((i)=>i.test(t))}async validateConfigFile(t){let i=[];try{if(!Or(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var wy=/^https?:\/\//;class Rc{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],u=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(o){return a.push({path:"",message:`Validation failed: ${o}`,rule:"system"}),{isValid:!1,errors:a,warnings:u}}};if(c)return await nf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!bu(i))throw new ln(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new ln(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:wy},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var Dt=new wn("bunfig",{showTags:!0});function $y(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class Yc{fileLoader=new Bc;envProcessor=new of;validator=new Rc;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(u&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Dt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw Dt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,u=f||un.cwd(),y=[],o=await this.loadLocalConfiguration(n,e,u,s,c,h,a,l,r);if(o)return y.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(o,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,u,c,h,a,l);if(w)return y.push(gt(u,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,u,s)),i)throw _i.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${$y(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Hr(t,e,s):e,a=this.getLocalDirectories(r,n);for(let u of a){if(s)Dt.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),o=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(o){if(s)Dt.success(`Configuration loaded from: ${o.source.path}`);return o}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Hr(t,r,e):r,c=[gt(Ti(),".config",t),gt(Ti(),".config"),Ti()];for(let l of c){if(e)Dt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)Dt.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Hr(t,n,f):n;try{let l=gt(r,"package.json");if(!lu(l))return null;let h={};try{h=JSON.parse(cu(l,"utf8"))}catch(y){if(f)Dt.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let a=h[t],u=t;if(!a&&i){let y=Array.isArray(i)?i:[i];for(let o of y){if(!o)continue;if(h[o]){a=h[o],u=o;break}}}if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)Dt.success(`Configuration loaded from package.json: ${u}`);return{config:gc(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Dt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Hr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw _i.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return vr.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);vr.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,gt(t,"config"),gt(t,".config"),i?gt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(gt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[gt(Ti(),".config",t),gt(Ti(),".config"),Ti()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var qd=new Yc;function Hr(t,i,r=!1){let n=new of,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let u=[...c,h],y=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((w)=>w.toUpperCase()).join("")}`,`${e}_${u.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],o,m;for(let w of y)if(o=un.env[w],o!==void 0){m=w;break}if(o!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(o.toLowerCase());else if(typeof a==="number"){let w=Number(o);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(o)}catch{l[h]=o.split(",").map((w)=>w.trim())}else l[h]=o;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,u)}return l}return f(i)}var kd=gt(un.cwd(),"config"),Dd=gt(un.cwd(),"src/generated"),Uc={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:me.join($e.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:me.join($e.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:me.join($e.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},D=Uc,It={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 C={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},Wi={info:(...t)=>console.log(...t),warn:(...t)=>console.warn(...t),success:(...t)=>console.log(...t),error:(...t)=>console.error(...t),debug:(...t)=>console.debug(...t)};function Qe(t,i){let r=[];function n(e){let f;try{f=Rl.readdirSync(e)}catch{return}for(let s of f){let c=Xt.join(e,s);try{if(Rl.statSync(c).isDirectory())n(c);else if(s===i)r.push(e)}catch{continue}}}return n(t),r}function E(t,i,r){if(r||D.verbose)console.debug(`[tlsx:${t}] ${i}`)}var Ey=Ay(my);function Nc(){return Fc.env.SUDO_PASSWORD}var Yl="[redacted]",Ty=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Cy=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;function Sy(t){let i=t.toLowerCase();return Ty.has(i)||i.endsWith("password")||i.includes("secret")||i.includes("token")}function cn(t){if(Array.isArray(t))return t.map((r)=>cn(r));if(typeof t==="string")return Cy.test(t)?Yl:t;if(!t||typeof t!=="object")return t;let i={};for(let[r,n]of Object.entries(t)){if(Sy(r)){i[r]=Yl;continue}i[r]=cn(n)}return i}function $n(t){return JSON.stringify(cn(t))}function gy(t){let i=Nc();if(!i||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(t))return t;let r=i.replace(/'/g,"'\\''"),n=t.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${r}' | ${n}`}async function li(t,i={}){let r=gy(t);try{let{stdout:n,stderr:e}=await Ey(r,{cwd:i.cwd||Fc.cwd(),timeout:i.timeout||30000});return{stdout:n.trim(),stderr:e.trim()}}catch(n){let e=Error(`Failed to execute command: ${t}
|
|
65
|
+
Error: ${n.message}`);throw e.stack=n.stack,e}}function jc(t){if(t.domain)return t.domain;if(t.domains?.length)return t.domains[0];throw Error("Either domain or domains must be specified")}function yf(t){let i=Xt.join(dy.homedir(),".stacks","ssl"),r=t.basePath&&t.basePath.trim()!==""?t.basePath:D.basePath&&D.basePath.trim()!==""?D.basePath:i,n=t.certPath?Xt.isAbsolute(t.certPath)?t.certPath:Xt.join(r,t.certPath):Xt.join(r,D.certPath),e=t.keyPath?Xt.isAbsolute(t.keyPath)?t.keyPath:Xt.join(r,t.keyPath):Xt.join(r,D.keyPath),f=t.caCertPath?Xt.isAbsolute(t.caCertPath)?t.caCertPath:Xt.join(r,t.caCertPath):Xt.join(r,D.caCertPath);return{certPath:n,keyPath:e,caCertPath:f,basePath:r}}function Wc(t){let i=[],r=new Set;if(t.domain)r.add(t.domain);if(t.domains?.length)t.domains.forEach((n)=>r.add(n));for(let n of r)i.push({type:2,value:n});if(t.altNameIPs?.length)for(let n of t.altNameIPs)i.push({type:7,ip:n});if(t.altNameURIs?.length)for(let n of t.altNameURIs)i.push({type:6,value:n});if(t.subjectAltNames?.length)i.push(...t.subjectAltNames);return E(C.CERT,`Generated ${i.length} Subject Alternative Names`,t.verbose),i}function wf(t){let i=t.notBeforeDays??It.DEFAULT_NOT_BEFORE_DAYS,r=t.validityDays??(t.validityYears?t.validityYears*365:It.DEFAULT_VALIDITY_DAYS);E(C.CERT,"Calculating certificate validity dates",t.verbose);let n=new Date(Date.now()-86400*i*1000),e=new Date(n.getTime()+r*24*60*60*1000);return n.setUTCHours(0,0,0,0),e.setUTCHours(23,59,59,999),E(C.CERT,`Validity period: ${n.toISOString()} to ${e.toISOString()}`,t.verbose),{notBefore:n,notAfter:e}}var Jt={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},ut={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 ir(t){if(t<128)return Buffer.from([t]);let i=[],r=t;while(r>0)i.unshift(r&255),r>>=8;return Buffer.from([128|i.length,...i])}function Et(t,i){let r=ir(i.length);return Buffer.concat([Buffer.from([t]),r,i])}function sr(t){let i=t.split(".").map(Number),r=[];r.push(40*i[0]+i[1]);for(let n=2;n<i.length;n++){let e=i[n],f=[];f.unshift(e&127),e>>=7;while(e>0)f.unshift(e&127|128),e>>=7;r.push(...f)}return Et(Jt.OID,Buffer.from(r))}function Ze(t){let i;if(typeof t==="bigint"){let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else if(typeof t==="number")if(t===0)i=Buffer.from([0]);else{let r=t.toString(16).padStart(2,"0");i=Buffer.from(r.length%2?`0${r}`:r,"hex")}else i=t;if(i[0]&128)i=Buffer.concat([Buffer.from([0]),i]);return Et(Jt.INTEGER,i)}function Xc(t,i=0){return Et(Jt.BIT_STRING,Buffer.concat([Buffer.from([i]),t]))}function _c(t){return Et(Jt.OCTET_STRING,t)}function At(...t){return Et(Jt.SEQUENCE,Buffer.concat(t))}function By(...t){return Et(Jt.SET,Buffer.concat(t))}function Ry(t){return Et(Jt.PRINTABLE_STRING,Buffer.from(t,"ascii"))}function Yy(t){return Et(Jt.UTF8_STRING,Buffer.from(t,"utf8"))}function Uy(){return Buffer.from([Jt.NULL,0])}function Ul(t,i,r=!0){let n=160|t|(r?0:0),e=ir(i.length);return Buffer.concat([Buffer.from([n]),e,i])}function Fl(t){let i=t.getUTCFullYear();if(i>=2050){let r=t.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return Et(Jt.GENERALIZED_TIME,Buffer.from(r,"ascii"))}else{let r=(i%100).toString().padStart(2,"0"),n=(t.getUTCMonth()+1).toString().padStart(2,"0"),e=t.getUTCDate().toString().padStart(2,"0"),f=t.getUTCHours().toString().padStart(2,"0"),s=t.getUTCMinutes().toString().padStart(2,"0"),c=t.getUTCSeconds().toString().padStart(2,"0"),l=`${r}${n}${e}${f}${s}${c}Z`;return Et(Jt.UTC_TIME,Buffer.from(l,"ascii"))}}function Fy(t,i){return At(Fl(t),Fl(i))}function Nl(t){let i=[];for(let r of t){let n;switch(r.shortName){case"CN":n=ut.COMMON_NAME;break;case"C":n=ut.COUNTRY;break;case"L":n=ut.LOCALITY;break;case"ST":n=ut.STATE;break;case"O":n=ut.ORGANIZATION;break;case"OU":n=ut.ORGANIZATIONAL_UNIT;break;default:continue}let e=r.shortName==="C"?Ry(r.value):Yy(r.value),f=At(sr(n),e);i.push(By(f))}return At(...i)}function Ic(t){return At(sr(t),Uy())}function Ny(t){return t.export({type:"spki",format:"der"})}function jy(t){if(t.includes(":")){let i=t;if(t.includes("::")){let e=t.split("::"),f=e[0]?e[0].split(":"):[],s=e[1]?e[1].split(":"):[],c=8-f.length-s.length,l=Array.from({length:c},()=>"0");i=[...f,...l,...s].join(":")}let r=i.split(":"),n=Buffer.alloc(16);for(let e=0;e<8;e++){let f=Number.parseInt(r[e]||"0",16);n.writeUInt16BE(f,e*2)}return n}else{let i=t.split(".").map((r)=>Number.parseInt(r,10));return Buffer.from(i)}}function Wy(t){let i=[];for(let r of t)if(r.type===2&&r.value){let n=ir(r.value.length);i.push(Buffer.concat([Buffer.from([130]),n,Buffer.from(r.value,"ascii")]))}else if(r.type===7&&r.ip){let n=jy(r.ip),e=ir(n.length);i.push(Buffer.concat([Buffer.from([135]),e,n]))}else if(r.type===6&&r.value){let n=ir(r.value.length);i.push(Buffer.concat([Buffer.from([134]),n,Buffer.from(r.value,"ascii")]))}return At(...i)}function Xy(t,i){if(t){if(i!==void 0)return At(Et(1,Buffer.from([255])),Ze(i));return At(Et(1,Buffer.from([255])))}return At()}function _y(t){let i=0;if(t.digitalSignature)i|=128;if(t.keyEncipherment)i|=32;if(t.keyCertSign)i|=4;if(t.cRLSign)i|=2;let r=0,n=i;while(n>0&&(n&1)===0)r++,n>>=1;if(i===0)r=7;return Xc(Buffer.from([i]),r)}function Iy(t){let i=[];if(t.serverAuth)i.push(sr(ut.SERVER_AUTH));if(t.clientAuth)i.push(sr(ut.CLIENT_AUTH));return At(...i)}function Zi(t,i,r){let n=[sr(t)];if(i)n.push(Et(1,Buffer.from([255])));return n.push(_c(r)),At(...n)}function Jy(t){let i=[];if(i.push(Ul(0,Ze(2))),i.push(Ze(t.serialNumber)),i.push(Ic(ut.SHA256_WITH_RSA)),i.push(Nl(t.issuer)),i.push(Fy(t.notBefore,t.notAfter)),i.push(Nl(t.subject)),i.push(Ny(t.publicKey)),t.extensions){let r=[];if(t.extensions.basicConstraints)r.push(Zi(ut.BASIC_CONSTRAINTS,t.extensions.basicConstraints.critical??!0,Xy(t.extensions.basicConstraints.isCA,t.extensions.basicConstraints.pathLenConstraint)));if(t.extensions.keyUsage)r.push(Zi(ut.KEY_USAGE,t.extensions.keyUsage.critical??!0,_y(t.extensions.keyUsage)));if(t.extensions.extendedKeyUsage)r.push(Zi(ut.EXTENDED_KEY_USAGE,!1,Iy(t.extensions.extendedKeyUsage)));if(t.extensions.subjectAltName?.length)r.push(Zi(ut.SUBJECT_ALT_NAME,!1,Wy(t.extensions.subjectAltName)));if(t.extensions.subjectKeyIdentifier)r.push(Zi(ut.SUBJECT_KEY_IDENTIFIER,!1,_c(t.extensions.subjectKeyIdentifier)));if(r.length>0)i.push(Ul(3,At(...r)))}return At(...i)}function Oy(t,i){let r=Ii.createSign("SHA256");r.update(t);let n=r.sign(i);return At(t,Ic(ut.SHA256_WITH_RSA),Xc(n))}function Ky(t,i){let r=t.toString("base64"),n=[];for(let e=0;e<r.length;e+=64)n.push(r.slice(e,e+64));return`-----BEGIN ${i}-----
|
|
66
66
|
${n.join(`
|
|
67
67
|
`)}
|
|
68
68
|
-----END ${i}-----
|
|
69
|
-
`}function
|
|
70
|
-
`);for(let f of e){let[s,...c]=f.split("="),l=c.join("=");if(s&&l)n.push({shortName:s.trim(),value:l.trim()})}return{publicKey:r,subject:n}}async function $f(t={}){E("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||It.DEFAULT_KEY_SIZE;E("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:r,publicKey:n}=Xc(i),e=[{shortName:"C",value:t.countryName||b.countryName},{shortName:"ST",value:t.stateName||b.stateName},{shortName:"L",value:t.localityName||b.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:f,notAfter:s}=yf({validityYears:t.validityYears||It.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:c}=_c({serialNumber:wf(),notBefore:f,notAfter:s,subject:e,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:Ic(r),notBefore:f,notAfter:s}}async function mf(t){if(E("ca","Generating new certificate",t.verbose),E("ca",`Options: ${$n(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=Oy(t.rootCA.certificate),r=Jy(t.rootCA.privateKey);E("ca",`Generating ${It.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let n=It.DEFAULT_KEY_SIZE,{privateKey:e,publicKey:f}=Xc(n),s=t.commonName||Uc(t),c=t.certificateAttributes||[{shortName:"C",value:t.countryName||b.countryName},{shortName:"ST",value:t.stateName||b.stateName},{shortName:"L",value:t.localityName||b.localityName},{shortName:"O",value:t.organizationName||b.organizationName},{shortName:"CN",value:s}],{notBefore:l,notAfter:h}=yf({validityDays:t.validityDays||It.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),a=Fc(t),o=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},y=t.extKeyUsage||{serverAuth:!0},{certificate:u}=_c({serialNumber:wf(),notBefore:l,notAfter:h,subject:c,issuer:i,publicKey:f,signingKey:r,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:o,extendedKeyUsage:y,subjectAltName:a});return{certificate:u,privateKey:Ic(e),notBefore:l,notAfter:h}}function Jc(t,i){E(C.STORAGE,`Storing certificate and private key with options: ${$n(i)}`,i?.verbose);let{certPath:r,keyPath:n}=uf({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});E(C.STORAGE,`Certificate path: ${r}`,i?.verbose),E(C.STORAGE,`Private key path: ${n}`,i?.verbose);let e=Ze.dirname(r);if(!Pt.existsSync(e))E(C.STORAGE,`Creating certificate directory: ${e}`,i?.verbose),Pt.mkdirSync(e,{recursive:!0});E(C.STORAGE,"Writing certificate file",i?.verbose),Pt.writeFileSync(r,t.certificate);let f=Ze.dirname(n);if(!Pt.existsSync(f))E(C.STORAGE,`Creating private key directory: ${f}`,i?.verbose),Pt.mkdirSync(f,{recursive:!0});return E(C.STORAGE,"Writing private key file",i?.verbose),Pt.writeFileSync(n,t.privateKey),E(C.STORAGE,"Certificate and private key stored successfully",i?.verbose),r}function Oc(t,i){E(C.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:r}=uf({basePath:i?.basePath,caCertPath:i?.caCertPath});E(C.STORAGE,`CA certificate path: ${r}`,i?.verbose);let n=Ze.dirname(r);if(!Pt.existsSync(n))E(C.STORAGE,`Creating CA certificate directory: ${n}`,i?.verbose),Pt.mkdirSync(n,{recursive:!0});return E(C.STORAGE,"Writing CA certificate file",i?.verbose),Pt.writeFileSync(r,t),E(C.STORAGE,"CA certificate stored successfully",i?.verbose),r}async function Hy(t,i){if(hn.platform()!=="darwin")return!1;try{let r=Ul(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!r)return E(C.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(Ul("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(r))return E(C.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return E(C.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(r){return E(C.TRUST,`Error checking certificate trust: ${r}`,i),!1}}var Ky={platform:"darwin",async addCertificate(t,i){if(await Hy(t,i?.verbose)){E(C.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),Wi.success("Certificate is already trusted in system keychain");return}E(C.TRUST,"Adding certificate to macOS keychain",i?.verbose),await li(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,r){let n=r||b.commonName;E(C.TRUST,`Removing certificate ${n} from macOS keychain`,i?.verbose);try{await li(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),E(C.TRUST,`Removed certificate ${n} from macOS keychain`,i?.verbose)}catch(e){throw E(C.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},My={platform:"win32",async addCertificate(t,i){E(C.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await li(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,r){let n=r||b.commonName;E(C.TRUST,`Removing certificate ${n} from Windows certificate store`,i?.verbose);try{await li(`certutil -delstore -enterprise Root "${n}"`),E(C.TRUST,`Removed certificate ${n} from Windows certificate store`,i?.verbose)}catch(e){throw E(C.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},zy={platform:"linux",async addCertificate(t,i){E(C.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let r=hn.homedir(),n=It.LINUX_CERT_DB_FILENAME,e=It.LINUX_TRUST_ARGS;E(C.TRUST,`Searching for certificate databases in ${r}`,i?.verbose);let f=ve(r,n);if(f.length===0){Wi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let s of f){E(C.TRUST,`Processing certificate database in ${s}`,i?.verbose);try{E(C.TRUST,`Attempting to delete existing cert for ${b.commonName}`,i?.verbose),await li(`certutil -d sql:${s} -D -n ${b.commonName}`)}catch(c){E(C.TRUST,`Warning: Error deleting existing cert: ${c}`,i?.verbose),console.warn(`Error deleting existing cert: ${c}`)}E(C.TRUST,`Adding new certificate to ${s}`,i?.verbose),await li(`certutil -d sql:${s} -A -t ${e} -n ${b.commonName} -i ${t}`),Wi.info(`Cert added to ${s}`)}},async removeCertificate(t,i,r){let n=r||b.commonName;E(C.TRUST,`Removing certificate ${n} from Linux certificate store`,i?.verbose);let e=hn.homedir(),f=It.LINUX_CERT_DB_FILENAME;E(C.TRUST,`Searching for certificate databases in ${e}`,i?.verbose);let s=ve(e,f);if(s.length===0){Wi.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of s){E(C.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{await li(`certutil -d sql:${c} -D -n "${n}"`),Wi.info(`Cert removed from ${c}`)}catch(l){E(C.TRUST,`Error removing cert from ${c}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${c}: ${l}`)}}}},Ly={darwin:Ky,win32:My,linux:zy};async function df(t,i,r){E(C.TRUST,`Adding certificate to system trust store with options: ${$n(r)}`,r?.verbose),E(C.TRUST,"Storing certificate and private key",r?.verbose);let n=Jc(t,r);E(C.TRUST,"Storing CA certificate",r?.verbose);let e=Oc(i,r),f=hn.platform();E(C.TRUST,`Detected platform: ${f}`,r?.verbose);let s=Ly[f];if(!s){let c=`Unsupported platform: ${f}`;throw E(C.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await s.addCertificate(e,r),E(C.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as fs}from"node:os";import{join as ss,resolve as SE}from"node:path";import{existsSync as Hc,statSync as Kc}from"fs";import{existsSync as Gy,mkdirSync as HA,readdirSync as KA,readFileSync as xy,writeFileSync as MA}from"fs";import{homedir as Ji}from"os";import{dirname as GA,resolve as Rt}from"path";import Vn from"process";import{existsSync as Mc,statSync as zc}from"fs";import{existsSync as Hf,mkdirSync as qy,readdirSync as ky,writeFileSync as by}from"fs";import{homedir as Oi}from"os";import{dirname as Lc,resolve as yt}from"path";import Ai from"process";import{join as Dy,relative as py,resolve as Gc}from"path";import On from"process";import{existsSync as Rh,mkdirSync as QA,readdirSync as ZA,writeFileSync as t1}from"fs";import{homedir as Af}from"os";import{dirname as n1,resolve as ut}from"path";import hr from"process";import{join as Vy,relative as Py,resolve as xc}from"path";import Hn from"process";import{existsSync as Yh,mkdirSync as c1,readdirSync as h1,writeFileSync as a1}from"fs";import{dirname as u1,resolve as Kn}from"path";import Kf from"process";import{Buffer as ai}from"buffer";import{createCipheriv as vy,createDecipheriv as Qy,randomBytes as Ef}from"crypto";import{closeSync as Tf,createReadStream as qc,createWriteStream as Zy,existsSync as Cf,fsyncSync as kc,openSync as bc,writeFileSync as tw}from"fs";import{access as iw,constants as Dc,mkdir as rw,readdir as mn,rename as pc,stat as Hi,unlink as dn,writeFile as gf}from"fs/promises";import{join as Ki}from"path";import st from"process";import{pipeline as nw}from"stream/promises";import{createGzip as Vc}from"zlib";import Mi from"process";import ii from"process";import{Buffer as Qt}from"buffer";import{createCipheriv as ew,createDecipheriv as fw,randomBytes as Sf}from"crypto";import{closeSync as Bf,createReadStream as Pc,createWriteStream as sw,existsSync as An,fsyncSync as vc,openSync as Qc,writeFileSync as lw}from"fs";import{access as cw,constants as Zc,mkdir as hw,readdir as En,rename as th,stat as zi,unlink as Tn,writeFile as Rf}from"fs/promises";import{isAbsolute as aw,join as Li,resolve as ow}from"path";import B from"process";import{pipeline as uw}from"stream/promises";import{createGzip as ih}from"zlib";import Gi from"process";import ri from"process";import Cn from"process";import{existsSync as gn}from"fs";import{resolve as Yf}from"path";import{existsSync as yw}from"fs";import{existsSync as ww,readdirSync as $w}from"fs";import{extname as Uf,resolve as rh}from"path";import mw from"process";import{join as dw,relative as Aw,resolve as nh}from"path";import Mn from"process";import{Buffer as Zt}from"buffer";import{createCipheriv as Ew,createDecipheriv as Tw,randomBytes as Ff}from"crypto";import{closeSync as Nf,createReadStream as eh,createWriteStream as Cw,existsSync as Sn,fsyncSync as fh,openSync as sh,writeFileSync as gw}from"fs";import{access as Sw,constants as lh,mkdir as Bw,readdir as Bn,rename as ch,stat as xi,unlink as Rn,writeFile as jf}from"fs/promises";import{isAbsolute as Rw,join as qi,resolve as Yw}from"path";import R from"process";import{pipeline as Uw}from"stream/promises";import{createGzip as hh}from"zlib";import ki from"process";import ni from"process";import Un from"process";import{existsSync as Fn}from"fs";import{resolve as Of}from"path";import{existsSync as D$}from"fs";class Sh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Hc(t))return!0;return Kc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Hc(r)?Kc(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Bh{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Jn=new Sh,Vf=new Bh;var Fw=Object.defineProperty,Nw=(t)=>t;function jw(t,i){this[t]=Nw.bind(null,i)}var Ww=(t,i)=>{for(var r in i)Fw(t,r,{get:i[r],enumerable:!0,configurable:!0,set:jw.bind(i,r)})},Xw=(t,i)=>()=>(t&&(i=t(t=0)),i),Uh={};Ww(Uh,{withErrorRecovery:()=>jh,tryLoadConfig:()=>i$,loadConfigWithResult:()=>Zw,loadConfig:()=>Jh,isRetryableError:()=>Dw,isConfigNotFoundError:()=>bw,isBunfigError:()=>Wh,globalPerformanceMonitor:()=>ur,globalCache:()=>bi,getEnvOrDefault:()=>pw,generateConfigTypes:()=>r$,defaultGeneratedDir:()=>xh,defaultConfigDir:()=>Gh,deepMergeWithArrayStrategy:()=>ts,deepMerge:()=>Xh,createLibraryConfig:()=>n$,config:()=>t$,bunfigPlugin:()=>e$,applyEnvVarsToConfig:()=>cr,TypeGenerationError:()=>kf,SchemaValidationError:()=>or,PluginError:()=>Df,PerformanceMonitor:()=>vf,FileSystemError:()=>qf,ErrorFactory:()=>oi,EnvVarError:()=>kn,EnvProcessor:()=>Pn,ConfigValidator:()=>is,ConfigValidationError:()=>Gf,ConfigNotFoundError:()=>qn,ConfigMergeError:()=>xf,ConfigLoader:()=>rs,ConfigLoadError:()=>ar,ConfigFileLoader:()=>vn,ConfigCache:()=>Pf,CacheUtils:()=>Hh,BunfigError:()=>Tt,BrowserConfigError:()=>bf,ArrayMergeStrategies:()=>zh});class Pf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Mc(t))return!0;return zc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Mc(r)?zc(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class vf{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function _w(t,i={}){let n=Object.keys(i).sort().map((e)=>`${e}:${i[e]}`).join("|");return n?`${t}:${n}`:t}function Iw(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Jw(t){return t.getStats().size*2}function Qf(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&x(i[0])&&"id"in i[0]&&i[0].id===3&&x(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(x(i)&&x(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(x(t)&&"arr"in t&&Array.isArray(t.arr)&&x(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&x(i[0])&&x(t[0])){let n=[...i];for(let e of t)if(x(e)&&"name"in e){if(!n.find((s)=>x(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(x(e)&&"path"in e){if(!n.find((s)=>x(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>zn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!x(i)||!x(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(x(e)&&x(r[n]))r[n]=Qf(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&x(e[0])&&x(r[n][0])){let f=[...e];for(let s of r[n])if(x(s)&&"name"in s){if(!f.find((l)=>x(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(x(s)&&"path"in s){if(!f.find((l)=>x(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>zn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function zn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!zn(t[r],i[r]))return!1;return!0}if(x(t)&&x(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!zn(t[e],i[e]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Ow(t,i){if(!Yh(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Qf(i,n)}catch{return null}}catch{return null}}async function Hw({name:t="",cwd:i,defaultConfig:r}){let n=i||Kf.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Kn(n,`${s}${c}`),h=await Ow(l,r);if(h!==null)return h}try{let s=Kn(n,"package.json");if(Yh(s)){let l=(await import(s))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return Qf(r,l)}catch{}}}catch{}return r}function Kw(t,i={}){let r=Hn.cwd();while(r.includes("storage"))r=xc(r,"..");let n=xc(r,t||"");if(i?.relative)return Py(Hn.cwd(),n);return n}async function Mw(){try{let t=await Hw({name:"clarity",defaultConfig:Wn,cwd:Hn.cwd(),endpoint:"",headers:{}});return{...Wn,...t}}catch{return Wn}}function k(){if(ii.env.NODE_ENV==="test"||ii.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zw(){if(ii.env.NODE_ENV==="test"||ii.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ii<"u"){let t=ii.type;if(t==="renderer"||t==="worker")return!1;return!!(ii.versions&&(ii.versions.node||ii.versions.bun))}return!1}class Fh{async format(t){let i=await zw(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Mi.pid,hostname:i(),environment:Mi.env.NODE_ENV||"development",platform:Mi.platform,version:Mi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Mi.env.NODE_ENV||Mi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ln{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...zf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Fh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??st.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Xn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Xn};return{...Xn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:zf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await iw(this.config.logDirectory,Dc.F_OK|Dc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await rw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ai.from(t);try{if(!Cf(this.currentLogFile))await gf(this.currentLogFile,"",{mode:420});if(e=bc(this.currentLogFile,"a",420),tw(e,l,{flag:"a"}),kc(e),e!==void 0)Tf(e),e=void 0;if((await Hi(this.currentLogFile)).size===0){if(await gf(this.currentLogFile,l,{flag:"w",mode:420}),(await Hi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let a=h;if(a.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(a.code)){if(f<s-1){let o=typeof a.message==="string"?a.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let y=c*2**f;await new Promise((u)=>setTimeout(u,y)),f++;continue}}if(a?.code&&["ENOSPC","EDQUOT"].includes(a.code))throw Error(`Disk quota exceeded or no space left on device: ${a.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",a),a}finally{if(e!==void 0)try{Tf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let a=l,o=typeof a.message==="string"?a.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((a)=>setTimeout(a,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Ki(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 Ki(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Ki(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ef(16).toString("hex")}generateKey(){return Ef(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ef(16),n=vy("aes-256-gcm",i,r),e=ai.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:ai.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Vc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ai.from(ai.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(k())return;let t=await Hi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await mn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Hi(r).catch(()=>null))try{if(await pc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await dn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await gf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Hi(r).catch(()=>null))await pc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await mn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await dn(Ki(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=qc(t),n=Zy(i),e=Vc();await nw(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Cf(this.currentLogFile))try{let t=bc(this.currentLogFile,"r+");kc(t),Tf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await mn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await dn(Ki(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?z.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=st.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${z.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!k()){let h=Kh[t],a=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:z.gray(s),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:z.green(s),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(o),c){let y=c.split(`
|
|
71
|
-
`);for(let
|
|
69
|
+
`}function $f(){return Ii.randomBytes(20)}function Jc(t=2048){let{privateKey:i,publicKey:r}=Ii.generateKeyPairSync("rsa",{modulusLength:t});return{privateKey:i,publicKey:r}}function Hy(t){let i=t.export({type:"spki",format:"der"});return Ii.createHash("sha1").update(i).digest()}function Oc(t){let i={serialNumber:t.serialNumber||$f(),notBefore:t.notBefore,notAfter:t.notAfter,subject:t.subject,issuer:t.issuer||t.subject,publicKey:t.publicKey,extensions:{basicConstraints:{isCA:t.isCA??!1,critical:!0,pathLenConstraint:t.pathLenConstraint},subjectKeyIdentifier:Hy(t.publicKey)}};if(t.keyUsage)i.extensions.keyUsage={...t.keyUsage,critical:!0};if(t.extendedKeyUsage)i.extensions.extendedKeyUsage=t.extendedKeyUsage;if(t.subjectAltName?.length)i.extensions.subjectAltName=t.subjectAltName;let r=Jy(i),n=Oy(r,t.signingKey);return{certificate:Ky(n,"CERTIFICATE"),certificateDer:n}}function Kc(t){return t.export({type:"pkcs8",format:"pem"})}function My(t){return Ii.createPrivateKey(t)}function zy(t){let i=new Ii.X509Certificate(t),r=i.publicKey,n=[],e=i.subject.split(`
|
|
70
|
+
`);for(let f of e){let[s,...c]=f.split("="),l=c.join("=");if(s&&l)n.push({shortName:s.trim(),value:l.trim()})}return{publicKey:r,subject:n}}async function mf(t={}){E("ca","Creating new Root CA Certificate",t.verbose);let i=t.keySize||It.DEFAULT_KEY_SIZE;E("ca",`Generating ${i}-bit RSA key pair`,t.verbose);let{privateKey:r,publicKey:n}=Jc(i),e=[{shortName:"C",value:t.countryName||D.countryName},{shortName:"ST",value:t.stateName||D.stateName},{shortName:"L",value:t.localityName||D.localityName},{shortName:"O",value:t.organization||"Local Development CA"},{shortName:"OU",value:t.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:t.commonName||"Local Development Root CA"}],{notBefore:f,notAfter:s}=wf({validityYears:t.validityYears||It.DEFAULT_CA_VALIDITY_YEARS,verbose:t.verbose}),{certificate:c}=Oc({serialNumber:$f(),notBefore:f,notAfter:s,subject:e,publicKey:n,signingKey:r,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:c,privateKey:Kc(r),notBefore:f,notAfter:s}}async function df(t){if(E("ca","Generating new certificate",t.verbose),E("ca",`Options: ${$n(t)}`,t.verbose),!t.domain&&!t.domains?.length)throw Error("Either domain or domains must be specified");if(!t.rootCA?.certificate||!t.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:i}=zy(t.rootCA.certificate),r=My(t.rootCA.privateKey);E("ca",`Generating ${It.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,t.verbose);let n=It.DEFAULT_KEY_SIZE,{privateKey:e,publicKey:f}=Jc(n),s=t.commonName||jc(t),c=t.certificateAttributes||[{shortName:"C",value:t.countryName||D.countryName},{shortName:"ST",value:t.stateName||D.stateName},{shortName:"L",value:t.localityName||D.localityName},{shortName:"O",value:t.organizationName||D.organizationName},{shortName:"CN",value:s}],{notBefore:l,notAfter:h}=wf({validityDays:t.validityDays||It.DEFAULT_VALIDITY_DAYS,verbose:t.verbose}),a=Wc(t),u=t.keyUsage||{digitalSignature:!0,keyEncipherment:!0},y=t.extKeyUsage||{serverAuth:!0},{certificate:o}=Oc({serialNumber:$f(),notBefore:l,notAfter:h,subject:c,issuer:i,publicKey:f,signingKey:r,isCA:t.basicConstraints?.cA??!1,pathLenConstraint:t.basicConstraints?.pathLenConstraint,keyUsage:u,extendedKeyUsage:y,subjectAltName:a});return{certificate:o,privateKey:Kc(e),notBefore:l,notAfter:h}}function Hc(t,i){E(C.STORAGE,`Storing certificate and private key with options: ${$n(i)}`,i?.verbose);let{certPath:r,keyPath:n}=yf({basePath:i?.basePath,certPath:i?.certPath,keyPath:i?.keyPath});E(C.STORAGE,`Certificate path: ${r}`,i?.verbose),E(C.STORAGE,`Private key path: ${n}`,i?.verbose);let e=tf.dirname(r);if(!Pt.existsSync(e))E(C.STORAGE,`Creating certificate directory: ${e}`,i?.verbose),Pt.mkdirSync(e,{recursive:!0});E(C.STORAGE,"Writing certificate file",i?.verbose),Pt.writeFileSync(r,t.certificate);let f=tf.dirname(n);if(!Pt.existsSync(f))E(C.STORAGE,`Creating private key directory: ${f}`,i?.verbose),Pt.mkdirSync(f,{recursive:!0});return E(C.STORAGE,"Writing private key file",i?.verbose),Pt.writeFileSync(n,t.privateKey),E(C.STORAGE,"Certificate and private key stored successfully",i?.verbose),r}function Mc(t,i){E(C.STORAGE,"Storing CA certificate",i?.verbose);let{caCertPath:r}=yf({basePath:i?.basePath,caCertPath:i?.caCertPath});E(C.STORAGE,`CA certificate path: ${r}`,i?.verbose);let n=tf.dirname(r);if(!Pt.existsSync(n))E(C.STORAGE,`Creating CA certificate directory: ${n}`,i?.verbose),Pt.mkdirSync(n,{recursive:!0});return E(C.STORAGE,"Writing CA certificate file",i?.verbose),Pt.writeFileSync(r,t),E(C.STORAGE,"CA certificate stored successfully",i?.verbose),r}async function Ly(t,i){if(hn.platform()!=="darwin")return!1;try{let r=jl(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"";if(!r)return E(C.TRUST,"Could not extract certificate fingerprint",i),!1;try{if(jl("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(r))return E(C.TRUST,"Certificate fingerprint found in system keychain",i),!0}catch{}return E(C.TRUST,"Certificate fingerprint not found in system keychain",i),!1}catch(r){return E(C.TRUST,`Error checking certificate trust: ${r}`,i),!1}}var Gy={platform:"darwin",async addCertificate(t,i){if(await Ly(t,i?.verbose)){E(C.TRUST,"Certificate is already trusted, skipping trust store update",i?.verbose),Wi.success("Certificate is already trusted in system keychain");return}E(C.TRUST,"Adding certificate to macOS keychain",i?.verbose),await li(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${t}`)},async removeCertificate(t,i,r){let n=r||D.commonName;E(C.TRUST,`Removing certificate ${n} from macOS keychain`,i?.verbose);try{await li(`sudo security delete-certificate -c "${n}" /Library/Keychains/System.keychain`),E(C.TRUST,`Removed certificate ${n} from macOS keychain`,i?.verbose)}catch(e){throw E(C.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},xy={platform:"win32",async addCertificate(t,i){E(C.TRUST,"Adding certificate to Windows certificate store",i?.verbose),await li(`certutil -f -v -addstore -enterprise Root ${t}`)},async removeCertificate(t,i,r){let n=r||D.commonName;E(C.TRUST,`Removing certificate ${n} from Windows certificate store`,i?.verbose);try{await li(`certutil -delstore -enterprise Root "${n}"`),E(C.TRUST,`Removed certificate ${n} from Windows certificate store`,i?.verbose)}catch(e){throw E(C.TRUST,`Error removing certificate: ${e}`,i?.verbose),e}}},qy={platform:"linux",async addCertificate(t,i){E(C.TRUST,"Adding certificate to Linux certificate store",i?.verbose);let r=hn.homedir(),n=It.LINUX_CERT_DB_FILENAME,e=It.LINUX_TRUST_ARGS;E(C.TRUST,`Searching for certificate databases in ${r}`,i?.verbose);let f=Qe(r,n);if(f.length===0){Wi.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let s of f){E(C.TRUST,`Processing certificate database in ${s}`,i?.verbose);try{E(C.TRUST,`Attempting to delete existing cert for ${D.commonName}`,i?.verbose),await li(`certutil -d sql:${s} -D -n ${D.commonName}`)}catch(c){E(C.TRUST,`Warning: Error deleting existing cert: ${c}`,i?.verbose),console.warn(`Error deleting existing cert: ${c}`)}E(C.TRUST,`Adding new certificate to ${s}`,i?.verbose),await li(`certutil -d sql:${s} -A -t ${e} -n ${D.commonName} -i ${t}`),Wi.info(`Cert added to ${s}`)}},async removeCertificate(t,i,r){let n=r||D.commonName;E(C.TRUST,`Removing certificate ${n} from Linux certificate store`,i?.verbose);let e=hn.homedir(),f=It.LINUX_CERT_DB_FILENAME;E(C.TRUST,`Searching for certificate databases in ${e}`,i?.verbose);let s=Qe(e,f);if(s.length===0){Wi.warn("No certificate databases found. Cannot remove certificate.");return}for(let c of s){E(C.TRUST,`Processing certificate database in ${c}`,i?.verbose);try{await li(`certutil -d sql:${c} -D -n "${n}"`),Wi.info(`Cert removed from ${c}`)}catch(l){E(C.TRUST,`Error removing cert from ${c}: ${l}`,i?.verbose),console.warn(`Error removing cert from ${c}: ${l}`)}}}},ky={darwin:Gy,win32:xy,linux:qy};async function Af(t,i,r){E(C.TRUST,`Adding certificate to system trust store with options: ${$n(r)}`,r?.verbose),E(C.TRUST,"Storing certificate and private key",r?.verbose);let n=Hc(t,r);E(C.TRUST,"Storing CA certificate",r?.verbose);let e=Mc(i,r),f=hn.platform();E(C.TRUST,`Detected platform: ${f}`,r?.verbose);let s=ky[f];if(!s){let c=`Unsupported platform: ${f}`;throw E(C.TRUST,`Error: ${c}`,r?.verbose),Error(c)}return await s.addCertificate(e,r),E(C.TRUST,"Certificate successfully added to system trust store",r?.verbose),n}import{homedir as ss}from"node:os";import{join as ls,resolve as FE}from"node:path";import{existsSync as zc,statSync as Lc}from"fs";import{existsSync as Dy,mkdirSync as GA,readdirSync as xA,readFileSync as by,writeFileSync as qA}from"fs";import{homedir as Ji}from"os";import{dirname as bA,resolve as Yt}from"path";import pn from"process";import{existsSync as Gc,statSync as xc}from"fs";import{existsSync as Hf,mkdirSync as Vy,readdirSync as py,writeFileSync as Py}from"fs";import{homedir as Oi}from"os";import{dirname as qc,resolve as yt}from"path";import Ai from"process";import{join as vy,relative as Qy,resolve as kc}from"path";import On from"process";import{existsSync as Fh,mkdirSync as n1,readdirSync as e1,writeFileSync as f1}from"fs";import{homedir as Ef}from"os";import{dirname as c1,resolve as ot}from"path";import hr from"process";import{join as Zy,relative as tw,resolve as Dc}from"path";import Kn from"process";import{existsSync as Nh,mkdirSync as y1,readdirSync as w1,writeFileSync as $1}from"fs";import{dirname as d1,resolve as Hn}from"path";import Mf from"process";import{Buffer as ai}from"buffer";import{createCipheriv as iw,createDecipheriv as rw,randomBytes as Tf}from"crypto";import{closeSync as Cf,createReadStream as bc,createWriteStream as nw,existsSync as Sf,fsyncSync as Vc,openSync as pc,writeFileSync as ew}from"fs";import{access as fw,constants as Pc,mkdir as sw,readdir as mn,rename as vc,stat as Ki,unlink as dn,writeFile as gf}from"fs/promises";import{join as Hi}from"path";import st from"process";import{pipeline as lw}from"stream/promises";import{createGzip as Qc}from"zlib";import Mi from"process";import ii from"process";import{Buffer as Qt}from"buffer";import{createCipheriv as cw,createDecipheriv as hw,randomBytes as Bf}from"crypto";import{closeSync as Rf,createReadStream as Zc,createWriteStream as aw,existsSync as An,fsyncSync as th,openSync as ih,writeFileSync as uw}from"fs";import{access as ow,constants as rh,mkdir as yw,readdir as En,rename as nh,stat as zi,unlink as Tn,writeFile as Yf}from"fs/promises";import{isAbsolute as ww,join as Li,resolve as $w}from"path";import B from"process";import{pipeline as mw}from"stream/promises";import{createGzip as eh}from"zlib";import Gi from"process";import ri from"process";import Cn from"process";import{existsSync as Sn}from"fs";import{resolve as Uf}from"path";import{existsSync as dw}from"fs";import{existsSync as Aw,readdirSync as Ew}from"fs";import{extname as Ff,resolve as fh}from"path";import Tw from"process";import{join as Cw,relative as Sw,resolve as sh}from"path";import Mn from"process";import{Buffer as Zt}from"buffer";import{createCipheriv as gw,createDecipheriv as Bw,randomBytes as Nf}from"crypto";import{closeSync as jf,createReadStream as lh,createWriteStream as Rw,existsSync as gn,fsyncSync as ch,openSync as hh,writeFileSync as Yw}from"fs";import{access as Uw,constants as ah,mkdir as Fw,readdir as Bn,rename as uh,stat as xi,unlink as Rn,writeFile as Wf}from"fs/promises";import{isAbsolute as Nw,join as qi,resolve as jw}from"path";import R from"process";import{pipeline as Ww}from"stream/promises";import{createGzip as oh}from"zlib";import ki from"process";import ni from"process";import Un from"process";import{existsSync as Fn}from"fs";import{resolve as Kf}from"path";import{existsSync as v$}from"fs";class Yh{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!zc(t))return!0;return Lc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=zc(r)?Lc(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Uh{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}var Jn=new Yh,Pf=new Uh;var Xw=Object.defineProperty,_w=(t)=>t;function Iw(t,i){this[t]=_w.bind(null,i)}var Jw=(t,i)=>{for(var r in i)Xw(t,r,{get:i[r],enumerable:!0,configurable:!0,set:Iw.bind(i,r)})},Ow=(t,i)=>()=>(t&&(i=t(t=0)),i),jh={};Jw(jh,{withErrorRecovery:()=>_h,tryLoadConfig:()=>f$,loadConfigWithResult:()=>n$,loadConfig:()=>Hh,isRetryableError:()=>vw,isConfigNotFoundError:()=>Pw,isBunfigError:()=>Ih,globalPerformanceMonitor:()=>or,globalCache:()=>Di,getEnvOrDefault:()=>Qw,generateConfigTypes:()=>s$,defaultGeneratedDir:()=>Dh,defaultConfigDir:()=>kh,deepMergeWithArrayStrategy:()=>is,deepMerge:()=>Jh,createLibraryConfig:()=>l$,config:()=>e$,bunfigPlugin:()=>c$,applyEnvVarsToConfig:()=>cr,TypeGenerationError:()=>Df,SchemaValidationError:()=>ur,PluginError:()=>Vf,PerformanceMonitor:()=>Qf,FileSystemError:()=>kf,ErrorFactory:()=>ui,EnvVarError:()=>kn,EnvProcessor:()=>Pn,ConfigValidator:()=>rs,ConfigValidationError:()=>xf,ConfigNotFoundError:()=>qn,ConfigMergeError:()=>qf,ConfigLoader:()=>ns,ConfigLoadError:()=>ar,ConfigFileLoader:()=>vn,ConfigCache:()=>vf,CacheUtils:()=>zh,BunfigError:()=>Tt,BrowserConfigError:()=>bf,ArrayMergeStrategies:()=>xh});class vf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(t={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...t}}generateKey(t,i){let r=i?`:${i}`:"";return`${this.options.keyPrefix}${t}${r}`}isExpired(t){return Date.now()-t.timestamp.getTime()>t.ttl}estimateSize(t){try{return JSON.stringify(t).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let t=Array.from(this.cache.entries()).sort(([,r],[,n])=>r.timestamp.getTime()-n.timestamp.getTime()),i=t.length-this.options.maxSize+1;for(let r=0;r<i;r++)this.cache.delete(t[r][0])}set(t,i,r,n){if(!this.options.enabled)return;let e=this.generateKey(t,r),f=n??this.options.ttl,s=this.estimateSize(i);this.cache.set(e,{value:i,timestamp:new Date,ttl:f,hits:0,size:s}),this.evictIfNeeded()}get(t,i){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(t,i),n=this.cache.get(r);if(!n){this.totalMisses++;return}if(this.isExpired(n)){this.cache.delete(r),this.totalMisses++;return}return n.hits++,this.totalHits++,n.value}isFileModified(t,i){try{if(!Gc(t))return!0;return xc(t).mtime>i}catch{return!0}}getWithFileCheck(t,i){let r=this.get(t,i);if(!r)return;if(this.isFileModified(i,r.fileTimestamp)){this.delete(t,i);return}return r.value}setWithFileCheck(t,i,r,n){try{let e=Gc(r)?xc(r):null,f=e?e.mtime:new Date;this.set(t,{value:i,fileTimestamp:f},r,n)}catch{this.set(t,i,r,n)}}delete(t,i){let r=this.generateKey(t,i);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let t=0;for(let[i,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(i),t++;return t}getStats(){let t=Array.from(this.cache.values()),i=t.reduce((n,e)=>n+e.size,0),r=t.map((n)=>n.timestamp).sort();return{size:i,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let t={};for(let[i,r]of this.cache.entries())t[i]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return t}import(t){this.cache.clear();for(let[i,r]of Object.entries(t))if(typeof r==="object"&&r!==null){let n=r;this.cache.set(i,{value:n.value,timestamp:new Date(n.timestamp),ttl:n.ttl,hits:n.hits,size:n.size})}}}class Qf{metrics=[];maxMetrics=1000;async track(t,i,r={}){let n=performance.now(),e=new Date;try{let f=await i(),s=performance.now()-n;return this.recordMetric({operation:t,duration:s,timestamp:e,...r}),f}catch(f){let s=performance.now()-n;throw this.recordMetric({operation:`${t}:error`,duration:s,timestamp:e,...r}),f}}recordMetric(t){if(this.metrics.push(t),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(t){let i=t?this.metrics.filter((e)=>e.operation===t):this.metrics;if(i.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=i.map((e)=>e.duration),n=r.reduce((e,f)=>e+f,0);return{count:i.length,averageDuration:n/i.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:n,recentMetrics:i.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(t){return this.metrics.filter((i)=>i.duration>t)}}function Kw(t,i={}){let n=Object.keys(i).sort().map((e)=>`${e}:${i[e]}`).join("|");return n?`${t}:${n}`:t}function Hw(t,i){try{return JSON.stringify(t)===JSON.stringify(i)}catch{return t===i}}function Mw(t){return t.getStats().size*2}function Zf(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&x(i[0])&&"id"in i[0]&&i[0].id===3&&x(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(x(i)&&x(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(x(t)&&"arr"in t&&Array.isArray(t.arr)&&x(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&x(i[0])&&x(t[0])){let n=[...i];for(let e of t)if(x(e)&&"name"in e){if(!n.find((s)=>x(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(x(e)&&"path"in e){if(!n.find((s)=>x(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>zn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!x(i)||!x(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(x(e)&&x(r[n]))r[n]=Zf(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&x(e[0])&&x(r[n][0])){let f=[...e];for(let s of r[n])if(x(s)&&"name"in s){if(!f.find((l)=>x(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(x(s)&&"path"in s){if(!f.find((l)=>x(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>zn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function zn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!zn(t[r],i[r]))return!1;return!0}if(x(t)&&x(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!zn(t[e],i[e]))return!1}return!0}return!1}function x(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function zw(t,i){if(!Nh(t))return null;try{let r=await import(t),n=r.default||r;if(typeof n!=="object"||n===null||Array.isArray(n))return null;try{return Zf(i,n)}catch{return null}}catch{return null}}async function Lw({name:t="",cwd:i,defaultConfig:r}){let n=i||Mf.cwd(),e=[".ts",".js",".mjs",".cjs",".json"],f=[`${t}.config`,`.${t}.config`,t,`.${t}`];for(let s of f)for(let c of e){let l=Hn(n,`${s}${c}`),h=await zw(l,r);if(h!==null)return h}try{let s=Hn(n,"package.json");if(Nh(s)){let l=(await import(s))[t];if(l&&typeof l==="object"&&!Array.isArray(l))try{return Zf(r,l)}catch{}}}catch{}return r}function Gw(t,i={}){let r=Kn.cwd();while(r.includes("storage"))r=Dc(r,"..");let n=Dc(r,t||"");if(i?.relative)return tw(Kn.cwd(),n);return n}async function xw(){try{let t=await Lw({name:"clarity",defaultConfig:Wn,cwd:Kn.cwd(),endpoint:"",headers:{}});return{...Wn,...t}}catch{return Wn}}function k(){if(ii.env.NODE_ENV==="test"||ii.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function qw(){if(ii.env.NODE_ENV==="test"||ii.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ii<"u"){let t=ii.type;if(t==="renderer"||t==="worker")return!1;return!!(ii.versions&&(ii.versions.node||ii.versions.bun))}return!1}class Wh{async format(t){let i=await qw(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Mi.pid,hostname:i(),environment:Mi.env.NODE_ENV||"development",platform:Mi.platform,version:Mi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Mi.env.NODE_ENV||Mi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ln{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Lf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Wh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??st.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Xn,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Xn};return{...Xn,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Lf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await fw(this.config.logDirectory,Pc.F_OK|Pc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await sw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:ai.from(t);try{if(!Sf(this.currentLogFile))await gf(this.currentLogFile,"",{mode:420});if(e=pc(this.currentLogFile,"a",420),ew(e,l,{flag:"a"}),Vc(e),e!==void 0)Cf(e),e=void 0;if((await Ki(this.currentLogFile)).size===0){if(await gf(this.currentLogFile,l,{flag:"w",mode:420}),(await Ki(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let a=h;if(a.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(a.code)){if(f<s-1){let u=typeof a.message==="string"?a.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,u);let y=c*2**f;await new Promise((o)=>setTimeout(o,y)),f++;continue}}if(a?.code&&["ENOSPC","EDQUOT"].includes(a.code))throw Error(`Disk quota exceeded or no space left on device: ${a.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",a),a}finally{if(e!==void 0)try{Cf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let a=l,u=typeof a.message==="string"?a.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let h=c*2**(f-1);await new Promise((a)=>setTimeout(a,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Hi(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 Hi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Hi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(k())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Tf(16).toString("hex")}generateKey(){return Tf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Tf(16),n=iw("aes-256-gcm",i,r),e=ai.concat([n.update(t,"utf8"),n.final()]),f=n.getAuthTag();return{encrypted:ai.concat([r,e,f]),iv:r}}async compressData(t){return new Promise((i,r)=>{let n=Qc(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(ai.from(ai.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(k())return;let t=await Ki(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await mn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await Ki(r).catch(()=>null))try{if(await vc(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await dn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await gf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await Ki(r).catch(()=>null))await vc(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await mn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await dn(Hi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=bc(t),n=nw(i),e=Qc();await lw(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);await this.writeToFile(n),console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(i),console.log(i);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let r={timestamp:new Date,level:t,message:i,name:this.name};this.logBuffer.push(r)}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(t)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(t){return{debug:0,info:1,success:2,warning:3,error:4}[t]}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Sf(this.currentLogFile))try{let t=pc(this.currentLogFile,"r+");Vc(t),Cf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!k()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await mn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await dn(Hi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.fancy?z.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(o)=>o.replace(this.ANSI_PATTERN,"");if(!this.fancy){let o=[];if(s)o.push(i);if(f==="warning")o.push("WARN");else if(f==="error")o.push("ERROR");else if(r)o.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)o.push(n.replace(/[[\]]/g,""));return o.push(e),o.join(" ")}let l=st.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${z.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,u=c(i).length,y=Math.max(1,l-2-a-u);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);if(this.fancy&&!k()){let h=Lh[t],a=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:z.gray(s),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:z.green(s),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:h,tag:a,message:s,level:t}),console.error(u),c){let y=c.split(`
|
|
71
|
+
`);for(let o of y)if(o.trim()&&!o.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:z.gray(` ${o}`),level:t,showTimestamp:!1}))}break}}else if(!k()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let l=`${f} ${this.environment}.${t.toUpperCase()}: ${s}
|
|
72
72
|
`;if(c)l+=`${c}
|
|
73
73
|
`;l=l.replace(this.ANSI_PATTERN,""),await this.writeToFile(l)}time(t){let i=performance.now();if(this.fancy&&!k()){let r=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:z.blue("◐"),tag:r,message:`${z.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
|
|
74
|
-
`,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!k()){let a=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:z.green("✓"),tag:a,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!k())console.error(h.trim());await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Ln(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(k())throw Error("createReadStream is not supported in browser environments");if(!
|
|
75
|
-
`),s=Math.max(...f.map((a)=>a.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((a)=>{let
|
|
74
|
+
`,h=h.replace(this.ANSI_PATTERN,""),this.fancy&&!k()){let a=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:z.green("✓"),tag:a,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!k())console.error(h.trim());await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Ln(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(k())throw Error("createReadStream is not supported in browser environments");if(!Sf(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return bc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=ai.isBuffer(t)?t:ai.from(t,"base64"),e=n.slice(0,16),f=n.slice(-16),s=n.slice(16,-16),c=rw("aes-256-gcm",r,e);return c.setAuthTag(f),ai.concat([c.update(s),c.final()]).toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return k()}isServerMode(){return!k()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i);if(this.fancy&&!k()){let f=t.split(`
|
|
75
|
+
`),s=Math.max(...f.map((a)=>a.length))+2,c=`┌${"─".repeat(s)}┐`,l=`└${"─".repeat(s)}┘`,h=f.map((a)=>{let u=" ".repeat(s-a.length-2);return`│ ${a}${u} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:r,message:z.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(c)})),h.forEach((a)=>console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(a),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:r,message:z.cyan(l),showTimestamp:!1}))}else if(!k())console.error(`${n} ${this.environment}.INFO: [BOX] ${t}`);let e=`${n} ${this.environment}.INFO: [BOX] ${t}
|
|
76
76
|
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(e)}async prompt(t){if(k())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${z.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();st.stdin.removeListener("data",r);try{if(typeof st.stdin.setRawMode==="function")st.stdin.setRawMode(!1)}catch{}st.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof st.stdin.setRawMode==="function")st.stdin.setRawMode(!0)}catch{}st.stdin.resume(),st.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let s=/%([sdijfo%])/g,c=0;if(r=t.replace(s,(l,h)=>{if(h==="%")return"%";if(c>=i.length)return l;let a=i[c++];switch(h){case"s":return String(a);case"d":case"i":return Number(a).toString();case"j":case"o":return JSON.stringify(a,null,2);default:return l}}),c<i.length)r+=` ${i.slice(c).map((l)=>typeof l==="object"?JSON.stringify(l,null,2):String(l)).join(" ")}`}if(this.fancy&&!k()){let s=this.options.showTags!==!1&&this.name?z.gray(this.formatTag(this.name)):"",c=z.blue("◐");console.error(`${c} ${s} ${z.cyan(r)}`)}let f=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${r}
|
|
77
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}progress(t,i=""){if(!this.enabled||!this.fancy||k()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(s,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,s)),c!==void 0)this.activeProgressBar.message=c;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;st.stdout.write(`${"\r".padEnd(st.stdout.columns||80)}\r`),this.log(c,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||k()||!st.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=z.green("━".repeat(n)),s=z.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=i||r===100?z.green("✓"):z.blue("▶"),
|
|
78
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||k()||!st.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await mn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Ki(this.config.logDirectory,n);if(t.before)try{if((await Hi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await dn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function jn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&H(i[0])&&"id"in i[0]&&i[0].id===3&&H(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(H(i)&&H(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(H(t)&&"arr"in t&&Array.isArray(t.arr)&&H(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&H(i[0])&&H(t[0])){let n=[...i];for(let e of t)if(H(e)&&"name"in e){if(!n.find((s)=>H(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(H(e)&&"path"in e){if(!n.find((s)=>H(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>Gn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!H(i)||!H(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(H(e)&&H(r[n]))r[n]=jn(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&H(e[0])&&H(r[n][0])){let f=[...e];for(let s of r[n])if(H(s)&&"name"in s){if(!f.find((l)=>H(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(H(s)&&"path"in s){if(!f.find((l)=>H(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Gn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function Zf(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:jn(t,i);if(Array.isArray(t))return r==="replace"?i:jn(t,i);if(!H(i)||!H(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=jn(s,f);else if(H(f)&&H(s))n[e]=Zf(s,f,r);else n[e]=f}return n}function Gn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Gn(t[r],i[r]))return!1;return!0}if(H(t)&&H(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Gn(t[e],i[e]))return!1}return!0}return!1}function H(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Yn(t,i,r="replace"){if(!Rh(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return Zf(i,e,r)}catch{return null}}catch{return null}}function Lw(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=(w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase(),u=`${n}_${o.map(y).join("_")}`,m=`${n}_${o.map((w)=>w.toUpperCase()).join("_")}`;if(r)ct.info(`Checking environment variable ${u} for config ${t}.${o.join(".")}`);if(typeof a==="object"&&a!==null&&!Array.isArray(a))l[h]=f(a,o);else{let w=hr.env[u]||hr.env[m];if(w!==void 0){if(r)ct.info(`Using environment variable ${w?u:m} for config ${t}.${o.join(".")}`);if(typeof a==="number")l[h]=Number(w);else if(typeof a==="boolean")l[h]=w.toLowerCase()==="true";else if(Array.isArray(a))try{let d=JSON.parse(w);if(Array.isArray(d))l[h]=d;else l[h]=w.split(",").map((A)=>A.trim())}catch{l[h]=w.split(",").map((d)=>d.trim())}else l[h]=w}}}return l}return f(e)}async function Gw({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?Lw(t,e,f):e,h=r||hr.cwd(),a=[".ts",".js",".mjs",".cjs",".json"];if(f)ct.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let o=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),u=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],w=Array.from(new Set([h,ut(h,"config"),ut(h,".config"),n?ut(h,n):void 0].filter(Boolean)));for(let d of w){if(f)ct.info(`Searching for configuration in: ${d}`);let T=[ut(h,"config"),ut(h,".config")].concat(n?[ut(h,n)]:[]).includes(d)?[...o,...y,...u,...m]:[...y,...o,...m,...u];for(let Y of T)for(let S of a){let X=ut(d,`${Y}${S}`),xt=await Yn(X,l,c);if(xt!==null){if(f)ct.success(`Configuration loaded from: ${X}`);return xt}}}if(t){let d=ut(Af(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)ct.info(`Checking user config directory: ${d}`);for(let T of A)for(let Y of a){let S=ut(d,`${T}${Y}`),X=await Yn(S,l,c);if(X!==null){if(f)ct.success(`Configuration loaded from user config directory: ${S}`);return X}}}if(t){let d=ut(Af(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)ct.info(`Checking user config directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let S=ut(d,`${T}${Y}`),X=await Yn(S,l,c);if(X!==null){if(f)ct.success(`Configuration loaded from user config directory dotfile: ${S}`);return X}}}if(t){let d=Af(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)ct.info(`Checking user home directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let S=ut(d,`${T}${Y}`),X=await Yn(S,l,c);if(X!==null){if(f)ct.success(`Configuration loaded from user home directory: ${S}`);return X}}}try{let d=ut(h,"package.json");if(Rh(d)){let A=await import(d),T=A[t];if(!T&&i){if(T=A[i],T&&f)ct.success(`Using alias "${i}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(f)ct.success(`Configuration loaded from package.json: ${T===A[t]?t:i}`);return Zf(l,T,c)}catch(Y){if(f)ct.warn("Failed to merge package.json config:",Y)}}}catch(d){if(f)ct.warn("Failed to load package.json:",d)}if(f)ct.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function xw(t,i={}){let r=On.cwd();while(r.includes("storage"))r=Gc(r,"..");let n=Gc(r,t||"");if(i?.relative)return py(On.cwd(),n);return n}async function qw(){try{let t=await Gw({name:"clarity",alias:"logging",defaultConfig:_n,cwd:On.cwd()});return{..._n,...t||{}}}catch{return _n}}function v(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function kw(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ri<"u"){let t=ri.type;if(t==="renderer"||t==="worker")return!1;return!!(ri.versions&&(ri.versions.node||ri.versions.bun))}return!1}class Nh{async format(t){let i=await kw(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Gi.pid,hostname:i(),environment:Gi.env.NODE_ENV||"development",platform:Gi.platform,version:Gi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gi.env.NODE_ENV||Gi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Lf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Nh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??B.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...In,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...In};return{...In,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Lf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!v()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await cw(this.config.logDirectory,Zc.F_OK|Zc.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await hw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Qt.from(t);try{if(!An(this.currentLogFile))await Rf(this.currentLogFile,"",{mode:420});if(e=Qc(this.currentLogFile,"a",420),lw(e,l,{flag:"a"}),vc(e),e!==void 0)Bf(e),e=void 0;if((await zi(this.currentLogFile)).size===0){if(await Rf(this.currentLogFile,l,{flag:"w",mode:420}),(await zi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let a=h;if(a.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(a.code)){if(f<s-1){let o=typeof a.message==="string"?a.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let y=c*2**f;await new Promise((u)=>setTimeout(u,y)),f++;continue}}if(a?.code&&["ENOSPC","EDQUOT"].includes(a.code))throw Error(`Disk quota exceeded or no space left on device: ${a.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",a),a}finally{if(e!==void 0)try{Bf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let a=l,o=typeof a.message==="string"?a.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((a)=>setTimeout(a,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Li(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 Li(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Li(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(v())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Sf(16).toString("hex")}generateKey(){return Sf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Sf(16),n=ew("aes-256-gcm",i,r),e=Qt.isBuffer(t)?t:Qt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Qt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=ih(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Qt.from(Qt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(v())return;if(!this.shouldWriteToFile())return;let t=await zi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await En(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await zi(r).catch(()=>null))try{if(await th(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Tn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Rf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await zi(r).catch(()=>null))await th(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await En(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await Tn(Li(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=Pc(t),n=sw(i),e=ih();await uw(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),An(this.currentLogFile))try{let t=Qc(this.currentLogFile,"r+");vc(t),Bf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!v()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await En(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await Tn(Li(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?F.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||v())return!1;let t=typeof B.env.NO_COLOR<"u",i=B.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof B.stderr<"u"&&B.stderr.isTTY||typeof B.stdout<"u"&&B.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=B.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${F.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=F.underline(F.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>F.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>F.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>F.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>F.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>F.strikethrough(n)),i}supportsHyperlinks(){if(v())return!1;let t=B.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=B.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(aw(i)||i.startsWith("./")||i.startsWith("../"))i=ow(i);else return null;return An(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":Mh[t],y=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:F.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:F.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.error(u),c){let m=c.split(`
|
|
77
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(f)}progress(t,i=""){if(!this.enabled||!this.fancy||k()||t<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let r=20;return this.activeProgressBar={total:t,current:0,message:i,barLength:r,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(s,c)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=Math.max(0,Math.min(t,s)),c!==void 0)this.activeProgressBar.message=c;let l=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,l)},finish:(s)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;if(this.activeProgressBar.current=this.activeProgressBar.total,s!==void 0)this.activeProgressBar.message=s;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(s,c="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||k())return;st.stdout.write(`${"\r".padEnd(st.stdout.columns||80)}\r`),this.log(c,s),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(t,i=!1){if(!this.enabled||!this.fancy||k()||!st.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=z.green("━".repeat(n)),s=z.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=i||r===100?z.green("✓"):z.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${z.gray(this.formatTag(this.name))}`:"",y=`\r${a}${u} ${c} ${l}${h}`,o=st.stdout.columns||80,m=" ".repeat(Math.max(0,o-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,st.stdout.write(t.lastRenderedLine),i)st.stdout.write(`
|
|
78
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||k()||!st.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(k()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await mn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Hi(this.config.logDirectory,n);if(t.before)try{if((await Ki(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await dn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}function jn(t,i){if(Array.isArray(i)&&Array.isArray(t)&&i.length===2&&t.length===2&&K(i[0])&&"id"in i[0]&&i[0].id===3&&K(i[1])&&"id"in i[1]&&i[1].id===4)return i;if(K(i)&&K(t)&&Object.keys(i).length===2&&Object.keys(i).includes("a")&&i.a===null&&Object.keys(i).includes("c")&&i.c===void 0)return{a:null,b:2,c:void 0};if(i===null||i===void 0)return t;if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(i)&&Array.isArray(t)){if(K(t)&&"arr"in t&&Array.isArray(t.arr)&&K(i)&&"arr"in i&&Array.isArray(i.arr))return i;if(i.length>0&&t.length>0&&K(i[0])&&K(t[0])){let n=[...i];for(let e of t)if(K(e)&&"name"in e){if(!n.find((s)=>K(s)&&("name"in s)&&s.name===e.name))n.push(e)}else if(K(e)&&"path"in e){if(!n.find((s)=>K(s)&&("path"in s)&&s.path===e.path))n.push(e)}else if(!n.some((f)=>Gn(f,e)))n.push(e);return n}if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}if(!K(i)||!K(t))return i;let r={...t};for(let n in i)if(Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];if(e===null||e===void 0)continue;else if(K(e)&&K(r[n]))r[n]=jn(r[n],e);else if(Array.isArray(e)&&Array.isArray(r[n]))if(e.length>0&&r[n].length>0&&K(e[0])&&K(r[n][0])){let f=[...e];for(let s of r[n])if(K(s)&&"name"in s){if(!f.find((l)=>K(l)&&("name"in l)&&l.name===s.name))f.push(s)}else if(K(s)&&"path"in s){if(!f.find((l)=>K(l)&&("path"in l)&&l.path===s.path))f.push(s)}else if(!f.some((c)=>Gn(c,s)))f.push(s);r[n]=f}else if(e.every((f)=>typeof f==="string")&&r[n].every((f)=>typeof f==="string")){let f=[...e];for(let s of r[n])if(!f.includes(s))f.push(s);r[n]=f}else r[n]=e;else r[n]=e}return r}function ts(t,i,r="replace"){if(i===null||i===void 0)return t;if(Array.isArray(i))return r==="replace"?i:jn(t,i);if(Array.isArray(t))return r==="replace"?i:jn(t,i);if(!K(i)||!K(t))return i;let n={...t};for(let e of Object.keys(i)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let f=i[e],s=n[e];if(f===null||f===void 0)continue;if(Array.isArray(f)||Array.isArray(s))if(r==="replace")n[e]=f;else n[e]=jn(s,f);else if(K(f)&&K(s))n[e]=ts(s,f,r);else n[e]=f}return n}function Gn(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Gn(t[r],i[r]))return!1;return!0}if(K(t)&&K(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Gn(t[e],i[e]))return!1}return!0}return!1}function K(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}async function Yn(t,i,r="replace"){if(!Fh(t))return null;try{let n=await import(t),e=n.default||n;if(typeof e!=="object"||e===null||Array.isArray(e))return null;try{return ts(i,e,r)}catch{return null}}catch{return null}}function kw(t,i,r=!1){if(!t)return i;let n=t.toUpperCase().replace(/-/g,"_"),e={...i};function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let u=[...c,h],y=(w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase(),o=`${n}_${u.map(y).join("_")}`,m=`${n}_${u.map((w)=>w.toUpperCase()).join("_")}`;if(r)ct.info(`Checking environment variable ${o} for config ${t}.${u.join(".")}`);if(typeof a==="object"&&a!==null&&!Array.isArray(a))l[h]=f(a,u);else{let w=hr.env[o]||hr.env[m];if(w!==void 0){if(r)ct.info(`Using environment variable ${w?o:m} for config ${t}.${u.join(".")}`);if(typeof a==="number")l[h]=Number(w);else if(typeof a==="boolean")l[h]=w.toLowerCase()==="true";else if(Array.isArray(a))try{let d=JSON.parse(w);if(Array.isArray(d))l[h]=d;else l[h]=w.split(",").map((A)=>A.trim())}catch{l[h]=w.split(",").map((d)=>d.trim())}else l[h]=w}}}return l}return f(e)}async function Dw({name:t="",alias:i,cwd:r,configDir:n,defaultConfig:e,verbose:f=!1,checkEnv:s=!0,arrayStrategy:c="replace"}){let l=s&&typeof e==="object"&&e!==null&&!Array.isArray(e)?kw(t,e,f):e,h=r||hr.cwd(),a=[".ts",".js",".mjs",".cjs",".json"];if(f)ct.info(`Loading configuration for "${t}"${i?` (alias: "${i}")`:""} from ${h}`);let u=[t,`.${t}`].filter(Boolean),y=[`${t}.config`,`.${t}.config`].filter(Boolean),o=i?[i,`.${i}`]:[],m=i?[`${i}.config`,`.${i}.config`]:[],w=Array.from(new Set([h,ot(h,"config"),ot(h,".config"),n?ot(h,n):void 0].filter(Boolean)));for(let d of w){if(f)ct.info(`Searching for configuration in: ${d}`);let T=[ot(h,"config"),ot(h,".config")].concat(n?[ot(h,n)]:[]).includes(d)?[...u,...y,...o,...m]:[...y,...u,...m,...o];for(let Y of T)for(let g of a){let X=ot(d,`${Y}${g}`),xt=await Yn(X,l,c);if(xt!==null){if(f)ct.success(`Configuration loaded from: ${X}`);return xt}}}if(t){let d=ot(Ef(),".config",t),A=["config",`${t}.config`];if(i)A.push(`${i}.config`);if(f)ct.info(`Checking user config directory: ${d}`);for(let T of A)for(let Y of a){let g=ot(d,`${T}${Y}`),X=await Yn(g,l,c);if(X!==null){if(f)ct.success(`Configuration loaded from user config directory: ${g}`);return X}}}if(t){let d=ot(Ef(),".config"),A=[`.${t}.config`];if(i)A.push(`.${i}.config`);if(f)ct.info(`Checking user config directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let g=ot(d,`${T}${Y}`),X=await Yn(g,l,c);if(X!==null){if(f)ct.success(`Configuration loaded from user config directory dotfile: ${g}`);return X}}}if(t){let d=Ef(),A=[`.${t}.config`,`.${t}`];if(i)A.push(`.${i}.config`),A.push(`.${i}`);if(f)ct.info(`Checking user home directory for dotfile configs: ${d}`);for(let T of A)for(let Y of a){let g=ot(d,`${T}${Y}`),X=await Yn(g,l,c);if(X!==null){if(f)ct.success(`Configuration loaded from user home directory: ${g}`);return X}}}try{let d=ot(h,"package.json");if(Fh(d)){let A=await import(d),T=A[t];if(!T&&i){if(T=A[i],T&&f)ct.success(`Using alias "${i}" configuration from package.json`)}if(T&&typeof T==="object"&&!Array.isArray(T))try{if(f)ct.success(`Configuration loaded from package.json: ${T===A[t]?t:i}`);return ts(l,T,c)}catch(Y){if(f)ct.warn("Failed to merge package.json config:",Y)}}}catch(d){if(f)ct.warn("Failed to load package.json:",d)}if(f)ct.info(`No configuration found for "${t}"${i?` or alias "${i}"`:""}, using default configuration with environment variables`);return l}function bw(t,i={}){let r=On.cwd();while(r.includes("storage"))r=kc(r,"..");let n=kc(r,t||"");if(i?.relative)return Qy(On.cwd(),n);return n}async function Vw(){try{let t=await Dw({name:"clarity",alias:"logging",defaultConfig:_n,cwd:On.cwd()});return{..._n,...t||{}}}catch{return _n}}function v(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function pw(){if(ri.env.NODE_ENV==="test"||ri.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ri<"u"){let t=ri.type;if(t==="renderer"||t==="worker")return!1;return!!(ri.versions&&(ri.versions.node||ri.versions.bun))}return!1}class Xh{async format(t){let i=await pw(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:Gi.pid,hostname:i(),environment:Gi.env.NODE_ENV||"development",platform:Gi.platform,version:Gi.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Gi.env.NODE_ENV||Gi.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Gf},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Xh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??B.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...In,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...In};return{...In,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Gf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!v()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await ow(this.config.logDirectory,rh.F_OK|rh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await yw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Qt.from(t);try{if(!An(this.currentLogFile))await Yf(this.currentLogFile,"",{mode:420});if(e=ih(this.currentLogFile,"a",420),uw(e,l,{flag:"a"}),th(e),e!==void 0)Rf(e),e=void 0;if((await zi(this.currentLogFile)).size===0){if(await Yf(this.currentLogFile,l,{flag:"w",mode:420}),(await zi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let a=h;if(a.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(a.code)){if(f<s-1){let u=typeof a.message==="string"?a.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,u);let y=c*2**f;await new Promise((o)=>setTimeout(o,y)),f++;continue}}if(a?.code&&["ENOSPC","EDQUOT"].includes(a.code))throw Error(`Disk quota exceeded or no space left on device: ${a.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",a),a}finally{if(e!==void 0)try{Rf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let a=l,u=typeof a.message==="string"?a.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let h=c*2**(f-1);await new Promise((a)=>setTimeout(a,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return Li(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 Li(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return Li(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(v())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Bf(16).toString("hex")}generateKey(){return Bf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Bf(16),n=cw("aes-256-gcm",i,r),e=Qt.isBuffer(t)?t:Qt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Qt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=eh(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Qt.from(Qt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(v())return;if(!this.shouldWriteToFile())return;let t=await zi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await En(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await zi(r).catch(()=>null))try{if(await nh(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Tn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Yf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await zi(r).catch(()=>null))await nh(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await En(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await Tn(Li(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=Zc(t),n=aw(i),e=eh();await mw(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),An(this.currentLogFile))try{let t=ih(this.currentLogFile,"r+");th(t),Rf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!v()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await En(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await Tn(Li(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?F.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||v())return!1;let t=typeof B.env.NO_COLOR<"u",i=B.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof B.stderr<"u"&&B.stderr.isTTY||typeof B.stdout<"u"&&B.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(o)=>o.replace(this.ANSI_PATTERN,"");if(!this.fancy){let o=[];if(s)o.push(i);if(f==="warning")o.push("WARN");else if(f==="error")o.push("ERROR");else if(r)o.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)o.push(n.replace(/[[\]]/g,""));return o.push(e),o.join(" ")}let l=B.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${F.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,u=c(i).length,y=Math.max(1,l-2-a-u);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=F.underline(F.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>F.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>F.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>F.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>F.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>F.strikethrough(n)),i}supportsHyperlinks(){if(v())return!1;let t=B.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=B.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(ww(i)||i.startsWith("./")||i.startsWith("../"))i=$w(i);else return null;return An(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":Gh[t],y=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:F.gray(l),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.warn(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:F.green(l),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.error(o),c){let m=c.split(`
|
|
79
79
|
`);for(let w of m)if(w.trim()&&!w.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:F.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!v()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}if(!this.shouldLog(t))return;let a=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
80
80
|
`;if(c)a+=`${c}
|
|
81
81
|
`;if(a=a.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(a)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!v()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!v()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!v()&&B.stdout.isTTY)B.stdout.write(`
|
|
82
82
|
`);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!v()&&B.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":F.blue("◐"),tag:r,message:`${F.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
|
|
83
|
-
`,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":F.green("✓"),tag:a,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!v())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new xn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(v())throw Error("createReadStream is not supported in browser environments");if(!An(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return
|
|
84
|
-
`),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,
|
|
85
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(v())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${F.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();B.stdin.removeListener("data",r);try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!1)}catch{}B.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!0)}catch{}B.stdin.resume(),B.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(a,
|
|
86
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!B.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=F.green("━".repeat(n)),s=F.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?F.green("✓"):F.blue("▶"),
|
|
87
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||v()||!B.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(v()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await En(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Li(this.config.logDirectory,n);if(t.before)try{if((await zi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Tn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function
|
|
83
|
+
`,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":F.green("✓"),tag:a,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!v())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new xn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(v())throw Error("createReadStream is not supported in browser environments");if(!An(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Zc(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Qt.isBuffer(t)?t:Qt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=hw("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),a=l.length+h.length,u=Qt.allocUnsafe(a);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return v()}isServerMode(){return!v()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
|
|
84
|
+
`),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,u=c.map((y)=>{return this.formatConsoleMessage({timestamp:r,message:F.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(h),showTimestamp:!1})),u.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:F.cyan(a),showTimestamp:!1}))}else if(!v())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
|
|
85
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(v())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${F.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();B.stdin.removeListener("data",r);try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!1)}catch{}B.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof B.stdin.setRawMode==="function")B.stdin.setRawMode(!0)}catch{}B.stdin.resume(),B.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(a,u)=>{if(u==="%")return"%";if(h>=i.length)return a;let y=i[h++];switch(u){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 a}}),h<i.length)r+=` ${i.slice(h).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?F.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${F.blue("◐")} `;console.error(`${h}${l} ${F.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
|
|
86
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!B.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=F.green("━".repeat(n)),s=F.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?F.green("✓"):F.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${F.gray(this.formatTag(this.name))}`:"",y=`\r${a}${u} ${c} ${l}${h}`,o=B.stdout.columns||80,m=" ".repeat(Math.max(0,o-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,B.stdout.write(t.lastRenderedLine),i)B.stdout.write(`
|
|
87
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||v()||!B.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(v()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await En(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=Li(this.config.logDirectory,n);if(t.before)try{if((await zi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Tn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}async function _h(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}function Ih(t){return t instanceof Tt}function Pw(t){return t instanceof qn}function vw(t){if(Ih(t))return t.code==="FILE_SYSTEM_ERROR"||t.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((r)=>t.message.toLowerCase().includes(r.toLowerCase()))}class Pn{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let a=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],a,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return or.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((a)=>this.formatEnvKey(a,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((a)=>a.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let a=Cn.env[l]||(h?Cn.env[h]:void 0);if(a!==void 0){if(n.verbose){let u=Cn.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(a,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof kn)throw u;throw ui.envVar(l,a,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw ui.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Cn.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
|
|
88
88
|
|
|
89
89
|
`;for(let n of t)r+=`${n.key}
|
|
90
90
|
`,r+=` Type: ${n.type}
|
|
@@ -96,25 +96,25 @@ ${n.join(`
|
|
|
96
96
|
`;r+=`| Variable | Type | Description | Example |
|
|
97
97
|
`,r+=`|----------|------|-------------|----------|
|
|
98
98
|
`;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
99
|
-
`;return r}}function pw(t,i){let r=Oh("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function Xh(t,i,r={}){return _h(t,i,r,new WeakMap)}function _h(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Ih(t,i,e,n);if(!Yt(i)||!Yt(t))return i;return Qw(t,i,r,n)}function Ih(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return Vw(t,i);case"smart":return Pw(t,i,n);default:return i}return i}function Vw(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>Mf(e,n)))r.push(n);return r}function Pw(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Yt(i[0])&&Yt(t[0]))return vw(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function vw(t,i,r){let n=[...i];for(let e of t){if(!Yt(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Yt(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function Qw(t,i,r,n){let e=i;if(Yt(e)&&n.has(e))return n.get(e);let f={...t};if(Yt(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Yt(c)&&Yt(l))f[s]=_h(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Ih(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function ts(t,i,r="replace"){return Xh(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function Mf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Mf(t[r],i[r]))return!1;return!0}if(Yt(t)&&Yt(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!Mf(t[e],i[e]))return!1}return!0}return!1}function Yt(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class vn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=bi.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!gn(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),o=a.default||a,y="default"in a,u=Object.keys(a).length>0;if(!y&&!u)throw new ar(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new ar(t,Error("Configuration must export a valid object"),"unknown");let d={config:ts(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)bi.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?oi.configLoad(t,h):oi.configLoad(t,Error(String(h)))}};if(s)return ur.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Yf(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return jh(async()=>{return gn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!gn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Yf(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Yf(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!gn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class is{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],o=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return a.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:a,warnings:o}}};if(c)return await ur.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!yw(i))throw new or(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new or(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Lh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class rs{fileLoader=new vn;envProcessor=new Pn;validator=new is;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(o&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Ht.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw Ht.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,o=f||Ai.cwd(),y=[],u=await this.loadLocalConfiguration(n,e,o,s,c,h,a,l,r);if(u)return y.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(u,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,o,c,h,a,l);if(w)return y.push(yt(o,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,o,s)),i)throw oi.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?cr(t,e,s):e,a=this.getLocalDirectories(r,n);for(let o of a){if(s)Ht.info(`Searching for configuration in: ${o}`);let y=this.fileLoader.generateConfigPaths(t,o,i),u=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(s)Ht.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?cr(t,r,e):r,c=[yt(Oi(),".config",t),yt(Oi(),".config"),Oi()];for(let l of c){if(e)Ht.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)Ht.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?cr(t,n,f):n;try{let l=yt(r,"package.json");if(!Hf(l))return null;let h=await import(l),a=h[t],o=t;if(!a&&i)a=h[i],o=i;if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)Ht.success(`Configuration loaded from package.json: ${o}`);return{config:ts(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Ht.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:cr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw oi.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return bi.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);bi.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,yt(t,"config"),yt(t,".config"),i?yt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(yt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[yt(Oi(),".config",t),yt(Oi(),".config"),Oi()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function ah(t){let r=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return r||n}async function Zw(t){return ei.loadConfig({...t,__strictErrorHandling:!0})}async function Jh(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await ei.loadConfig(t);else n=await ei.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)Ht.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ei.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function t$(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ei.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&ah(r)))return(await ei.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await ei.loadConfig({...t,cwd:t.cwd||Ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&ah(i)))return(await ei.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function i$(t,i,r="replace"){let n=new vn;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function cr(t,i,r=!1){let n=new Pn,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((w)=>w.toUpperCase()).join("")}`,`${e}_${o.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let w of y)if(u=Ai.env[w],u!==void 0){m=w;break}if(u!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(u.toLowerCase());else if(typeof a==="number"){let w=Number(u);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(u)}catch{l[h]=u.split(",").map((w)=>w.trim())}else l[h]=u;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,o)}return l}return f(i)}function r$(t){let i=yt(Ai.cwd(),t.configDir),r=yt(Ai.cwd(),t.generatedDir),n=yt(r,"config-types.ts");if(!Hf(Lc(n)))qy(Lc(n),{recursive:!0,mode:511});let e=Hf(i)?ky(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${W$}
|
|
99
|
+
`;return r}}function Qw(t,i){let r=Mh("process");if(typeof r>"u"||!r.env)return i;let n=r.env[t];return n!==void 0?n:i}function Jh(t,i,r={}){return Oh(t,i,r,new WeakMap)}function Oh(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return Kh(t,i,e,n);if(!Ut(i)||!Ut(t))return i;return r$(t,i,r,n)}function Kh(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return Zw(t,i);case"smart":return t$(t,i,n);default:return i}return i}function Zw(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>zf(e,n)))r.push(n);return r}function t$(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Ut(i[0])&&Ut(t[0]))return i$(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function i$(t,i,r){let n=[...i];for(let e of t){if(!Ut(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Ut(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function r$(t,i,r,n){let e=i;if(Ut(e)&&n.has(e))return n.get(e);let f={...t};if(Ut(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Ut(c)&&Ut(l))f[s]=Oh(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=Kh(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function is(t,i,r="replace"){return Jh(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function zf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!zf(t[r],i[r]))return!1;return!0}if(Ut(t)&&Ut(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!zf(t[e],i[e]))return!1}return!0}return!1}function Ut(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class vn{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Di.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Sn(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),u=a.default||a,y="default"in a,o=Object.keys(a).length>0;if(!y&&!o)throw new ar(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new ar(t,Error("Configuration must export a valid object"),"unknown");let d={config:is(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Di.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?ui.configLoad(t,h):ui.configLoad(t,Error(String(h)))}};if(s)return or.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Uf(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);if(i){if(r.push(i,`.${i}.config`,`${i}.config`,`.${i}`),t)r.push(`${t}.${i}.config`,`.${t}.${i}.config`)}return r.filter(Boolean)}checkFileAccess(t){return _h(async()=>{return Sn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Sn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Uf(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Uf(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!Sn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}class rs{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],u=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(o){return a.push({path:"",message:`Validation failed: ${o}`,rule:"system"}),{isValid:!1,errors:a,warnings:u}}};if(c)return await or.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!dw(i))throw new ur(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new ur(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:qh},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class ns{fileLoader=new vn;envProcessor=new Pn;validator=new rs;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(u&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)Kt.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){let l=Date.now()-i;throw Kt.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,u=f||Ai.cwd(),y=[],o=await this.loadLocalConfiguration(n,e,u,s,c,h,a,l,r);if(o)return y.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(o,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,u,c,h,a,l);if(w)return y.push(yt(u,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,u,s)),i)throw ui.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${e?` or alias "${e}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?cr(t,e,s):e,a=this.getLocalDirectories(r,n);for(let u of a){if(s)Kt.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),o=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(o){if(s)Kt.success(`Configuration loaded from: ${o.source.path}`);return o}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?cr(t,r,e):r,c=[yt(Oi(),".config",t),yt(Oi(),".config"),Oi()];for(let l of c){if(e)Kt.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)Kt.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?cr(t,n,f):n;try{let l=yt(r,"package.json");if(!Hf(l))return null;let h=await import(l),a=h[t],u=t;if(!a&&i)a=h[i],u=i;if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)Kt.success(`Configuration loaded from package.json: ${u}`);return{config:is(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)Kt.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:cr(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw ui.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Di.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Di.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias)r.push(`alias:${i.alias}`);if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,yt(t,"config"),yt(t,".config"),i?yt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(yt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[yt(Oi(),".config",t),yt(Oi(),".config"),Oi()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}function yh(t){let r=!(t.message.includes("EACCES")||t.message.includes("EPERM")||t.message.includes("permission denied"))&&(t.message.includes("syntax")||t.message.includes("Expected")||t.message.includes("Unexpected")||t.message.includes("BuildMessage")),n=t.message.includes("Configuration must export a valid object")||t.message.includes("Configuration file is empty and exports nothing");return r||n}async function n$(t){return ei.loadConfig({...t,__strictErrorHandling:!0})}async function Hh(t){let i="defaultConfig"in t&&t.defaultConfig!==void 0?t.defaultConfig:{},r="cache"in t||"performance"in t||"schema"in t||"validate"in t;try{let n;if(r)n=await ei.loadConfig(t);else n=await ei.loadConfig({...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}});return n?.config??i}catch(n){let e=n instanceof Error?n.name:"UnknownError",f=n instanceof Error?n.message:String(n);if(!(e==="ConfigNotFoundError"||e==="ConfigLoadError"||e==="ConfigValidationError"||f.includes("config"))&&t.verbose)Kt.warn("Unexpected error loading config, using defaults:",[n instanceof Error?n:Error(String(n))]);let c=r?{...t,defaultConfig:i}:{...t,defaultConfig:i,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in t?t.checkEnv!==!1:!0)return(await ei.applyEnvironmentVariables(c.name||"",i,!0,c.verbose||!1))?.config??i;return i}}async function e$(t={defaultConfig:{}}){if(typeof t==="string"){let{cwd:i}=await import("process");try{return(await ei.loadConfig({name:t,cwd:i(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(r){if(r instanceof Error&&(r.name==="ConfigNotFoundError"||r.name==="ConfigLoadError"&&yh(r)))return(await ei.applyEnvironmentVariables(t,{},!0,!1)).config;throw r}}try{return(await ei.loadConfig({...t,cwd:t.cwd||Ai.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(i){if(i instanceof Error&&(i.name==="ConfigNotFoundError"||i.name==="ConfigLoadError"&&yh(i)))return(await ei.applyEnvironmentVariables(t.name||"",t.defaultConfig||{},t.checkEnv!==!1,t.verbose||!1)).config;throw i}}async function f$(t,i,r="replace"){let n=new vn;try{let e=await n.loadFromPath(t,i,{arrayStrategy:r,useCache:!1,trackPerformance:!1});return e?e.config:null}catch{return null}}function cr(t,i,r=!1){let n=new Pn,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let u=[...c,h],y=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((w)=>w.toUpperCase()).join("")}`,`${e}_${u.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],o,m;for(let w of y)if(o=Ai.env[w],o!==void 0){m=w;break}if(o!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(o.toLowerCase());else if(typeof a==="number"){let w=Number(o);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(o)}catch{l[h]=o.split(",").map((w)=>w.trim())}else l[h]=o;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,u)}return l}return f(i)}function s$(t){let i=yt(Ai.cwd(),t.configDir),r=yt(Ai.cwd(),t.generatedDir),n=yt(r,"config-types.ts");if(!Hf(qc(n)))Vy(qc(n),{recursive:!0,mode:511});let e=Hf(i)?py(i).map((s)=>s.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],f=`// Generated by bunfig v${J$}
|
|
100
100
|
export type ConfigNames = ${e.length?`'${e.join("' | '")}'`:"string"}
|
|
101
|
-
`;
|
|
102
|
-
${e.map((h)=>{let a=
|
|
101
|
+
`;Py(n,f,{mode:438})}function l$(t){let i=null,r=null,n=()=>{if(!r)r=Hh(t).then((f)=>{return i=f,f},(f)=>{let s="defaultConfig"in t?t.defaultConfig:{};if(i=s,"verbose"in t&&t.verbose)Kt.warn("Config loading failed, using defaults:",[f instanceof Error?f:Error(String(f))]);return s});return r},e="defaultConfig"in t?t.defaultConfig:{};return i=e,n(),new Proxy({},{get(f,s){if(i)return i[s];let c=e[s];return n(),c},has(f,s){return s in(i||e)},ownKeys(){return Object.keys(i||e)},getOwnPropertyDescriptor(f,s){return Object.getOwnPropertyDescriptor(i||e,s)},set(f,s,c){if(!i)i={...e};return i[s]=c,!0}})}function c$(t){let i=fh(Tw.cwd(),t?.configDir||"./config");function r(){if(!Aw(i))return[];let e=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),f=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],s=Ew(i).filter((l)=>e.has(Ff(l))).map((l)=>({base:l.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:l})),c=new Map;for(let{base:l,file:h}of s){let a=Ff(h).toLowerCase(),u=c.get(l);if(!u){c.set(l,h);continue}let y=Ff(u).toLowerCase();if(f.indexOf(a)<f.indexOf(y))c.set(l,h)}return Array.from(c.entries()).map(([l,h])=>({base:l,file:h})).sort((l,h)=>l.base.localeCompare(h.base))}function n(){let e=r(),f=e.map((h)=>h.base),s=f.length?f.map((h)=>`'${h}'`).join(" | "):"string",c=e.length?`{
|
|
102
|
+
${e.map((h)=>{let a=fh(i,h.file).replace(/\\/g,"/");return` '${h.base}': typeof import('${a}').default`}).join(`,
|
|
103
103
|
`)}
|
|
104
104
|
}`:"Record<string, any>";return`export type ConfigNames = ${s}
|
|
105
105
|
export type ConfigByName = ${c}
|
|
106
106
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
107
107
|
export type ConfigOf = Config
|
|
108
|
-
`}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var Oh,bi,ur,Hh,f$,s$,oh,Wn,zf,lt,z,l$,uh,c$,yh,h$,a$,Wf,o$,wh,$h,Xf,u$,y$,w$,$$,Xn,Kh,m$,ct,d$,A$,mh,_n,Lf,Q,F,E$,dh,T$,Ah,C$,g$,_f,S$,Eh,Th,B$,If,R$,Y$,U$,F$,N$,In,Mh,j$,W$="0.15.6",Tt,qn,ar,Gf,xf,kn,qf,kf,or,bf,Df,oi,zh,Lh,Ht,ei,Gh,xh,X$=Xw(async()=>{Oh=import.meta.require,bi=new Pf,ur=new vf,Hh={createKey:_w,isEquivalent:Iw,estimateMemoryUsage:Jw},f$=Kn(Kf.cwd(),"config"),s$=Kn(Kf.cwd(),"src/generated"),oh=Hn.env.CLARITY_LOG_DIR||Vy(Kw(),"logs"),Wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:oh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},zf=await Mw(),lt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},z=lt,l$=lt.red,uh=lt.green,c$=lt.yellow,yh=lt.blue,h$=lt.magenta,a$=lt.cyan,Wf=lt.white,o$=lt.gray,wh=lt.bgRed,$h=lt.bgYellow,Xf=lt.bold,u$=lt.dim,y$=lt.italic,w$=lt.underline,$$=lt.reset,Xn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Kh={debug:"\uD83D\uDD0D",info:yh("ℹ"),success:uh("✓"),warning:$h(Wf(Xf(" WARN "))),error:wh(Wf(Xf(" ERROR ")))},m$=new Ln("stacks"),ct=new Ln("bunfig",{showTags:!0}),d$=ut(hr.cwd(),"config"),A$=ut(hr.cwd(),"src/generated"),mh=On.env.CLARITY_LOG_DIR||Dy(xw(),"logs"),_n={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:mh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lf=await qw(),Q={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},F=Q,E$=Q.red,dh=Q.green,T$=Q.yellow,Ah=Q.blue,C$=Q.magenta,g$=Q.cyan,_f=Q.white,S$=Q.gray,Eh=Q.bgRed,Th=Q.bgYellow,B$=Q.bgGray,If=Q.bold,R$=Q.dim,Y$=Q.italic,U$=Q.underline,F$=Q.strikethrough,N$=Q.reset,In={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Mh={debug:"\uD83D\uDD0D",info:Ah("ℹ"),success:dh("✓"),warning:Th(_f(If(" WARN "))),error:Eh(_f(If(" ERROR ")))},j$=new xn("stacks"),Tt=class extends Error{timestamp;context;constructor(i,r={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},qn=class extends Tt{code="CONFIG_NOT_FOUND";constructor(i,r,n){let e=n?` or alias "${n}"`:"";super(`Configuration "${i}"${e} not found`,{configName:i,alias:n,searchPaths:r,searchPathCount:r.length})}},ar=class extends Tt{code="CONFIG_LOAD_ERROR";constructor(i,r,n){super(`Failed to load configuration from "${i}": ${r.message}`,{configPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},Gf=class extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(i,r,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:r,errorCount:r.length})}},xf=class extends Tt{code="CONFIG_MERGE_ERROR";constructor(i,r,n,e){super(`Failed to merge configuration from "${i}" with "${r}": ${n.message}`,{sourcePath:i,targetPath:r,configName:e,originalError:n.name,originalMessage:n.message});this.cause=n}},kn=class extends Tt{code="ENV_VAR_ERROR";constructor(i,r,n,e){super(`Failed to parse environment variable "${i}" with value "${r}" as ${n}`,{envKey:i,envValue:r,expectedType:n,configName:e})}},qf=class extends Tt{code="FILE_SYSTEM_ERROR";constructor(i,r,n){super(`File system ${i} failed for "${r}": ${n.message}`,{operation:i,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},kf=class extends Tt{code="TYPE_GENERATION_ERROR";constructor(i,r,n){super(`Failed to generate types from "${i}" to "${r}": ${n.message}`,{configDir:i,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},or=class extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(i,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:r,errorCount:r.length})}},bf=class extends Tt{code="BROWSER_CONFIG_ERROR";constructor(i,r,n,e){super(`Failed to fetch configuration from "${i}": ${r} ${n}`,{endpoint:i,status:r,statusText:n,configName:e})}},Df=class extends Tt{code="PLUGIN_ERROR";constructor(i,r,n){super(`Plugin "${i}" failed during ${r}: ${n.message}`,{pluginName:i,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},oi={configNotFound(t,i,r){return new qn(t,i,r)},configLoad(t,i,r){return new ar(t,i,r)},configValidation(t,i,r){return new Gf(t,i,r)},configMerge(t,i,r,n){return new xf(t,i,r,n)},envVar(t,i,r,n){return new kn(t,i,r,n)},fileSystem(t,i,r){return new qf(t,i,r)},typeGeneration(t,i,r){return new kf(t,i,r)},schemaValidation(t,i,r){return new or(t,i,r)},browserConfig(t,i,r,n){return new bf(t,i,r,n)},plugin(t,i,r){return new Df(t,i,r)}},zh={replace:"replace",concat:"concat",smart:"smart"},Lh=/^https?:\/\//,Ht=new xn("bunfig",{showTags:!0}),ei=new rs,Gh=yt(Ai.cwd(),"config"),xh=yt(Ai.cwd(),"src/generated")});function _$(t,i={}){let r=Mn.cwd();while(r.includes("storage"))r=nh(r,"..");let n=nh(r,t||"");if(i?.relative)return Aw(Mn.cwd(),n);return n}var I$=Mn.env.CLARITY_LOG_DIR||dw(_$(),"logs"),qh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:I$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bn={...qh},Z1=(async()=>{try{let{loadConfig:t}=await X$().then(()=>Uh),i=await t({name:"clarity",alias:"logging",defaultConfig:qh,cwd:Mn.cwd()});if(i)Object.assign(bn,i)}catch{}return bn})();function Z(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function J$(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ni<"u"){let t=ni.type;if(t==="renderer"||t==="worker")return!1;return!!(ni.versions&&(ni.versions.node||ni.versions.bun))}return!1}class kh{async format(t){let i=await J$(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ki.pid,hostname:i(),environment:ki.env.NODE_ENV||"development",platform:ki.platform,version:ki.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ki.env.NODE_ENV||ki.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var rt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},W=rt,tE=rt.red,O$=rt.green,iE=rt.yellow,H$=rt.blue,rE=rt.magenta,nE=rt.cyan,Ch=rt.white,eE=rt.gray,K$=rt.bgRed,M$=rt.bgYellow,fE=rt.bgGray,gh=rt.bold,sE=rt.dim,lE=rt.italic,cE=rt.underline,hE=rt.strikethrough,aE=rt.reset,Jf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},z$={debug:"\uD83D\uDD0D",info:H$("ℹ"),success:O$("✓"),warning:M$(Ch(gh(" WARN "))),error:K$(Ch(gh(" ERROR ")))};class Qn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...bn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new kh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Jf,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Jf};return{...Jf,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:bn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!Z()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await Sw(this.config.logDirectory,lh.F_OK|lh.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Bw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Zt.from(t);try{if(!Sn(this.currentLogFile))await jf(this.currentLogFile,"",{mode:420});if(e=sh(this.currentLogFile,"a",420),gw(e,l,{flag:"a"}),fh(e),e!==void 0)Nf(e),e=void 0;if((await xi(this.currentLogFile)).size===0){if(await jf(this.currentLogFile,l,{flag:"w",mode:420}),(await xi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let a=h;if(a.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(a.code)){if(f<s-1){let o=typeof a.message==="string"?a.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,o);let y=c*2**f;await new Promise((u)=>setTimeout(u,y)),f++;continue}}if(a?.code&&["ENOSPC","EDQUOT"].includes(a.code))throw Error(`Disk quota exceeded or no space left on device: ${a.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",a),a}finally{if(e!==void 0)try{Nf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let a=l,o=typeof a.message==="string"?a.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",o),l}f++;let h=c*2**(f-1);await new Promise((a)=>setTimeout(a,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return qi(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 qi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return qi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(Z())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Ff(16).toString("hex")}generateKey(){return Ff(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Ff(16),n=Ew("aes-256-gcm",i,r),e=Zt.isBuffer(t)?t:Zt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Zt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=hh(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Zt.from(Zt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(Z())return;if(!this.shouldWriteToFile())return;let t=await xi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Bn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await xi(r).catch(()=>null))try{if(await ch(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Rn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await jf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await xi(r).catch(()=>null))await ch(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await Bn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await Rn(qi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=eh(t),n=Cw(i),e=hh();await Uw(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),Sn(this.currentLogFile))try{let t=sh(this.currentLogFile,"r+");fh(t),Nf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!Z()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Bn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await Rn(qi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?W.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Z())return!1;let t=typeof R.env.NO_COLOR<"u",i=R.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(u)=>u.replace(this.ANSI_PATTERN,"");if(!this.fancy){let u=[];if(s)u.push(i);if(f==="warning")u.push("WARN");else if(f==="error")u.push("ERROR");else if(r)u.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)u.push(n.replace(/[[\]]/g,""));return u.push(e),u.join(" ")}let l=R.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${W.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,o=c(i).length,y=Math.max(1,l-2-a-o);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=W.underline(W.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>W.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>W.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>W.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>W.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>W.strikethrough(n)),i}supportsHyperlinks(){if(Z())return!1;let t=R.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=R.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Rw(i)||i.startsWith("./")||i.startsWith("../"))i=Yw(i);else return null;return Sn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let o=this.options.showIcons===!1?"":z$[t],y=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",u;switch(t){case"debug":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:W.gray(l),level:t}),console.error(u);break;case"info":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"success":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:W.green(l),level:t}),console.error(u);break;case"warning":u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.warn(u);break;case"error":if(u=this.formatConsoleMessage({timestamp:e,icon:o,tag:y,message:l,level:t}),console.error(u),c){let m=c.split(`
|
|
108
|
+
`}return{name:"bunfig-plugin",setup(e){e.onResolve({filter:/^virtual:bunfig-types$/},(f)=>{return{path:f.path,namespace:"bunfig-virtual"}}),e.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:n(),loader:"ts"}})}}}var Mh,Di,or,zh,h$,a$,wh,Wn,Lf,lt,z,u$,$h,o$,mh,y$,w$,Xf,$$,dh,Ah,_f,m$,d$,A$,E$,Xn,Lh,T$,ct,C$,S$,Eh,_n,Gf,Q,F,g$,Th,B$,Ch,R$,Y$,If,U$,Sh,gh,F$,Jf,N$,j$,W$,X$,_$,In,Gh,I$,J$="0.15.6",Tt,qn,ar,xf,qf,kn,kf,Df,ur,bf,Vf,ui,xh,qh,Kt,ei,kh,Dh,O$=Ow(async()=>{Mh=import.meta.require,Di=new vf,or=new Qf,zh={createKey:Kw,isEquivalent:Hw,estimateMemoryUsage:Mw},h$=Hn(Mf.cwd(),"config"),a$=Hn(Mf.cwd(),"src/generated"),wh=Kn.env.CLARITY_LOG_DIR||Zy(Gw(),"logs"),Wn={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:wh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Lf=await xw(),lt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,reset:"\x1B[0m"},z=lt,u$=lt.red,$h=lt.green,o$=lt.yellow,mh=lt.blue,y$=lt.magenta,w$=lt.cyan,Xf=lt.white,$$=lt.gray,dh=lt.bgRed,Ah=lt.bgYellow,_f=lt.bold,m$=lt.dim,d$=lt.italic,A$=lt.underline,E$=lt.reset,Xn={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Lh={debug:"\uD83D\uDD0D",info:mh("ℹ"),success:$h("✓"),warning:Ah(Xf(_f(" WARN "))),error:dh(Xf(_f(" ERROR ")))},T$=new Ln("stacks"),ct=new Ln("bunfig",{showTags:!0}),C$=ot(hr.cwd(),"config"),S$=ot(hr.cwd(),"src/generated"),Eh=On.env.CLARITY_LOG_DIR||vy(bw(),"logs"),_n={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Eh,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Gf=await Vw(),Q={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},F=Q,g$=Q.red,Th=Q.green,B$=Q.yellow,Ch=Q.blue,R$=Q.magenta,Y$=Q.cyan,If=Q.white,U$=Q.gray,Sh=Q.bgRed,gh=Q.bgYellow,F$=Q.bgGray,Jf=Q.bold,N$=Q.dim,j$=Q.italic,W$=Q.underline,X$=Q.strikethrough,_$=Q.reset,In={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Gh={debug:"\uD83D\uDD0D",info:Ch("ℹ"),success:Th("✓"),warning:gh(If(Jf(" WARN "))),error:Sh(If(Jf(" ERROR ")))},I$=new xn("stacks"),Tt=class extends Error{timestamp;context;constructor(i,r={}){super(i);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=r,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let i=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([r,n])=>`${r}: ${n}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${i}`}},qn=class extends Tt{code="CONFIG_NOT_FOUND";constructor(i,r,n){let e=n?` or alias "${n}"`:"";super(`Configuration "${i}"${e} not found`,{configName:i,alias:n,searchPaths:r,searchPathCount:r.length})}},ar=class extends Tt{code="CONFIG_LOAD_ERROR";constructor(i,r,n){super(`Failed to load configuration from "${i}": ${r.message}`,{configPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}},xf=class extends Tt{code="CONFIG_VALIDATION_ERROR";constructor(i,r,n){super(`Configuration validation failed for "${i}"`,{configPath:i,configName:n,validationErrors:r,errorCount:r.length})}},qf=class extends Tt{code="CONFIG_MERGE_ERROR";constructor(i,r,n,e){super(`Failed to merge configuration from "${i}" with "${r}": ${n.message}`,{sourcePath:i,targetPath:r,configName:e,originalError:n.name,originalMessage:n.message});this.cause=n}},kn=class extends Tt{code="ENV_VAR_ERROR";constructor(i,r,n,e){super(`Failed to parse environment variable "${i}" with value "${r}" as ${n}`,{envKey:i,envValue:r,expectedType:n,configName:e})}},kf=class extends Tt{code="FILE_SYSTEM_ERROR";constructor(i,r,n){super(`File system ${i} failed for "${r}": ${n.message}`,{operation:i,path:r,originalError:n.name,originalMessage:n.message});this.cause=n}},Df=class extends Tt{code="TYPE_GENERATION_ERROR";constructor(i,r,n){super(`Failed to generate types from "${i}" to "${r}": ${n.message}`,{configDir:i,outputPath:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ur=class extends Tt{code="SCHEMA_VALIDATION_ERROR";constructor(i,r,n){super(`Schema validation failed${n?` for config "${n}"`:""}`,{schemaPath:i,configName:n,validationErrors:r,errorCount:r.length})}},bf=class extends Tt{code="BROWSER_CONFIG_ERROR";constructor(i,r,n,e){super(`Failed to fetch configuration from "${i}": ${r} ${n}`,{endpoint:i,status:r,statusText:n,configName:e})}},Vf=class extends Tt{code="PLUGIN_ERROR";constructor(i,r,n){super(`Plugin "${i}" failed during ${r}: ${n.message}`,{pluginName:i,operation:r,originalError:n.name,originalMessage:n.message});this.cause=n}},ui={configNotFound(t,i,r){return new qn(t,i,r)},configLoad(t,i,r){return new ar(t,i,r)},configValidation(t,i,r){return new xf(t,i,r)},configMerge(t,i,r,n){return new qf(t,i,r,n)},envVar(t,i,r,n){return new kn(t,i,r,n)},fileSystem(t,i,r){return new kf(t,i,r)},typeGeneration(t,i,r){return new Df(t,i,r)},schemaValidation(t,i,r){return new ur(t,i,r)},browserConfig(t,i,r,n){return new bf(t,i,r,n)},plugin(t,i,r){return new Vf(t,i,r)}},xh={replace:"replace",concat:"concat",smart:"smart"},qh=/^https?:\/\//,Kt=new xn("bunfig",{showTags:!0}),ei=new ns,kh=yt(Ai.cwd(),"config"),Dh=yt(Ai.cwd(),"src/generated")});function K$(t,i={}){let r=Mn.cwd();while(r.includes("storage"))r=sh(r,"..");let n=sh(r,t||"");if(i?.relative)return Sw(Mn.cwd(),n);return n}var H$=Mn.env.CLARITY_LOG_DIR||Cw(K$(),"logs"),bh={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:H$,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Dn={...bh},eE=(async()=>{try{let{loadConfig:t}=await O$().then(()=>jh),i=await t({name:"clarity",alias:"logging",defaultConfig:bh,cwd:Mn.cwd()});if(i)Object.assign(Dn,i)}catch{}return Dn})();function Z(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function M$(){if(ni.env.NODE_ENV==="test"||ni.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ni<"u"){let t=ni.type;if(t==="renderer"||t==="worker")return!1;return!!(ni.versions&&(ni.versions.node||ni.versions.bun))}return!1}class Vh{async format(t){let i=await M$(),r=await this.getMetadata(i);return JSON.stringify({timestamp:t.timestamp.toISOString(),level:t.level,name:t.name,message:t.message,metadata:r})}async getMetadata(t){if(t){let{hostname:i}=await import("os");return{pid:ki.pid,hostname:i(),environment:ki.env.NODE_ENV||"development",platform:ki.platform,version:ki.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ki.env.NODE_ENV||ki.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}var rt={red:(t)=>`\x1B[31m${t}\x1B[0m`,green:(t)=>`\x1B[32m${t}\x1B[0m`,yellow:(t)=>`\x1B[33m${t}\x1B[0m`,blue:(t)=>`\x1B[34m${t}\x1B[0m`,magenta:(t)=>`\x1B[35m${t}\x1B[0m`,cyan:(t)=>`\x1B[36m${t}\x1B[0m`,white:(t)=>`\x1B[37m${t}\x1B[0m`,gray:(t)=>`\x1B[90m${t}\x1B[0m`,bgRed:(t)=>`\x1B[41m${t}\x1B[0m`,bgYellow:(t)=>`\x1B[43m${t}\x1B[0m`,bgGray:(t)=>`\x1B[100m${t}\x1B[0m`,bold:(t)=>`\x1B[1m${t}\x1B[0m`,dim:(t)=>`\x1B[2m${t}\x1B[0m`,italic:(t)=>`\x1B[3m${t}\x1B[0m`,underline:(t)=>`\x1B[4m${t}\x1B[0m`,strikethrough:(t)=>`\x1B[9m${t}\x1B[0m`,reset:"\x1B[0m"},W=rt,fE=rt.red,z$=rt.green,sE=rt.yellow,L$=rt.blue,lE=rt.magenta,cE=rt.cyan,Bh=rt.white,hE=rt.gray,G$=rt.bgRed,x$=rt.bgYellow,aE=rt.bgGray,Rh=rt.bold,uE=rt.dim,oE=rt.italic,yE=rt.underline,wE=rt.strikethrough,$E=rt.reset,Of={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},q$={debug:"\uD83D\uDD0D",info:L$("ℹ"),success:z$("✓"),warning:x$(Bh(Rh(" WARN "))),error:G$(Bh(Rh(" ERROR ")))};class Qn{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(t,i={}){this.name=t,this.config={...Dn},this.options=this.normalizeOptions(i),this.formatter=this.options.formatter||new Vh,this.enabled=i.enabled??!0,this.fancy=i.fancy??!0,this.tagFormat=i.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=i.timestampPosition??"right",this.environment=i.environment??R.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(i);let r={...i},n=i.timestamp!==void 0;if(n)delete r.timestamp;if(this.config={...this.config,...r,timestamp:n||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let e=this.generateKeyId(),f=this.generateKey();this.currentKeyId=e,this.keys.set(e,f),this.encryptionKeys.set(e,{key:f,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(t){if(!this.fingersCrossedConfig)return!1;let i={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return i[t]>=i[r]}initializeFingersCrossedConfig(t){if(!t.fingersCrossedEnabled&&t.fingersCrossed)return{...Of,...t.fingersCrossed};if(!t.fingersCrossedEnabled)return null;if(!t.fingersCrossed)return{...Of};return{...Of,...t.fingersCrossed}}normalizeOptions(t){let i={format:"json",level:"info",logDirectory:Dn.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...i,...Object.fromEntries(Object.entries(t).filter(([,n])=>n!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=i.level;return r}shouldWriteToFile(){return!Z()&&this.config.writeToFile===!0}async writeToFile(t){let r=(async()=>{let e,f=0,s=3,c=1000;while(f<s)try{try{try{await Uw(this.config.logDirectory,ah.F_OK|ah.W_OK)}catch(h){if(h instanceof Error&&"code"in h)if(h.code==="ENOENT")await Fw(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 l=this.validateEncryptionConfig()?(await this.encrypt(t)).encrypted:Zt.from(t);try{if(!gn(this.currentLogFile))await Wf(this.currentLogFile,"",{mode:420});if(e=hh(this.currentLogFile,"a",420),Yw(e,l,{flag:"a"}),ch(e),e!==void 0)jf(e),e=void 0;if((await xi(this.currentLogFile)).size===0){if(await Wf(this.currentLogFile,l,{flag:"w",mode:420}),(await xi(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(h){let a=h;if(a.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(a.code)){if(f<s-1){let u=typeof a.message==="string"?a.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${s}:`,u);let y=c*2**f;await new Promise((o)=>setTimeout(o,y)),f++;continue}}if(a?.code&&["ENOSPC","EDQUOT"].includes(a.code))throw Error(`Disk quota exceeded or no space left on device: ${a.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",a),a}finally{if(e!==void 0)try{jf(e)}catch(h){console.error("Debug: [writeToFile] Error closing file descriptor:",h)}}}catch(l){if(f===s-1){let a=l,u=typeof a.message==="string"?a.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",u),l}f++;let h=c*2**(f-1);await new Promise((a)=>setTimeout(a,h))}})();this.pendingOperations.push(r);let n=this.pendingOperations.length-1;try{await r}catch(e){throw console.error("Debug: [writeToFile] Error in operation:",e),e}finally{this.pendingOperations.splice(n,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return qi(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 qi(this.config.logDirectory,`${this.name}.log`);let t=new Date().toISOString().split("T")[0];return qi(this.config.logDirectory,`${this.name}-${t}.log`)}setupRotation(){if(Z())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let t=this.config.rotation,i;switch(t.frequency){case"daily":i=86400000;break;case"weekly":i=604800000;break;case"monthly":i=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},i)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let i=this.config.rotation.keyRotation;if(!i?.enabled)return;let r=typeof i.interval==="number"?i.interval:60,n=Math.max(r,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((e)=>{console.error("Error rotating keys:",e)})},n)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let i=this.config.rotation.keyRotation,r=this.generateKeyId(),n=this.generateKey();this.currentKeyId=r,this.keys.set(r,n),this.encryptionKeys.set(r,{key:n,createdAt:new Date});let e=Array.from(this.encryptionKeys.entries()).sort(([,c],[,l])=>l.createdAt.getTime()-c.createdAt.getTime()),f=typeof i.maxKeys==="number"?i.maxKeys:1,s=Math.max(1,f);if(e.length>s)for(let[c]of e.slice(s))this.encryptionKeys.delete(c),this.keys.delete(c)}generateKeyId(){return Nf(16).toString("hex")}generateKey(){return Nf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let t=this.keys.get(this.currentKeyId);if(!t)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:t,id:this.currentKeyId}}encrypt(t){let{key:i}=this.getCurrentKey(),r=Nf(16),n=gw("aes-256-gcm",i,r),e=Zt.isBuffer(t)?t:Zt.from(t,"utf8"),f=n.update(e),s=n.final(),c=f.length+s.length,l=n.getAuthTag(),h=Zt.allocUnsafe(16+c+16);return r.copy(h,0),f.copy(h,16),s.copy(h,16+f.length),l.copy(h,16+c),{encrypted:h,iv:r}}async compressData(t){return new Promise((i,r)=>{let n=oh(),e=[];n.on("data",(f)=>e.push(f)),n.on("end",()=>i(Zt.from(Zt.concat(e)))),n.on("error",r),n.write(t),n.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let t={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let i=this.config.rotation.encrypt;return{...t,...i}}return t}async rotateLog(){if(Z())return;if(!this.shouldWriteToFile())return;let t=await xi(this.currentLogFile).catch(()=>null);if(!t)return;let i=this.config.rotation;if(typeof i==="boolean")return;if(i.maxSize&&t.size>=i.maxSize){let r=this.currentLogFile,n=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let e=await Bn(this.config.logDirectory),f=e.filter((l)=>l.startsWith(this.name)&&/\.log\.\d+$/.test(l)).sort((l,h)=>{let a=Number.parseInt(l.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(h.match(/\.log\.(\d+)$/)?.[1]||"0")-a}),s=f.length>0?Number.parseInt(f[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,c=`${r}.${s}`;if(await xi(r).catch(()=>null))try{if(await uh(r,c),i.compress)try{let l=`${c}.gz`;await this.compressLogFile(c,l),await Rn(c)}catch(l){console.error("Error compressing rotated file:",l)}if(f.length===0&&!e.some((l)=>l.endsWith(".log.1")))try{let l=`${r}.1`;await Wf(l,"")}catch(l){console.error("Error creating backup file:",l)}}catch(l){console.error(`Error during rotation: ${l instanceof Error?l.message:String(l)}`)}}else{let e=new Date().toISOString().replace(/[:.]/g,"-"),f=r.replace(/\.log$/,`-${e}.log`);if(await xi(r).catch(()=>null))await uh(r,f)}if(this.currentLogFile=n,i.maxFiles){let f=(await Bn(this.config.logDirectory)).filter((s)=>s.startsWith(this.name)).sort((s,c)=>c.localeCompare(s));for(let s of f.slice(i.maxFiles))await Rn(qi(this.config.logDirectory,s))}}}async compressLogFile(t,i){let r=lh(t),n=Rw(i),e=oh();await Ww(r,e,n)}async handleFingersCrossedBuffer(t,i){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(t)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let n=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(n);console.log(n)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(i);console.log(i)}}shouldLog(t){if(!this.enabled)return!1;let i={debug:0,info:1,success:2,warning:3,error:4};return i[t]>=i[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((t)=>{if(t instanceof Promise)return t.catch((i)=>{console.error("Error in pending write operation:",i)});return Promise.resolve()})),gn(this.currentLogFile))try{let t=hh(this.currentLogFile,"r+");ch(t),jf(t)}catch(t){console.error(`Error flushing file: ${t}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let t of this.pendingOperations)if(typeof t.cancel==="function")t.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(t){console.error("Error waiting for pending operations:",t)}if(!Z()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let i=(await Bn(this.config.logDirectory)).filter((r)=>(r.includes("temp")||r.includes(".tmp"))&&r.includes(this.name));for(let r of i)try{await Rn(qi(this.config.logDirectory,r))}catch(n){console.error(`Failed to delete temp file ${r}:`,n)}}catch(t){console.error("Error cleaning up temporary files:",t)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(t){if(!t)return"";return`${this.tagFormat.prefix}${t}${this.tagFormat.suffix}`}formatFileTimestamp(t){return`[${t.toISOString()}]`}formatConsoleTimestamp(t){return this.shouldStyleConsole()?W.gray(t.toLocaleTimeString()):t.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||Z())return!1;let t=typeof R.env.NO_COLOR<"u",i=R.env.FORCE_COLOR==="0";if(t||i)return!1;return!!(typeof R.stderr<"u"&&R.stderr.isTTY||typeof R.stdout<"u"&&R.stdout.isTTY)}formatConsoleMessage(t){let{timestamp:i,icon:r="",tag:n="",message:e,level:f,showTimestamp:s=!0}=t,c=(o)=>o.replace(this.ANSI_PATTERN,"");if(!this.fancy){let o=[];if(s)o.push(i);if(f==="warning")o.push("WARN");else if(f==="error")o.push("ERROR");else if(r)o.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(n)o.push(n.replace(/[[\]]/g,""));return o.push(e),o.join(" ")}let l=R.stdout.columns||120,h="";if(f==="warning"||f==="error")h=`${r} ${e}`;else if(f==="info"||f==="success")h=`${r} ${n} ${e}`;else h=`${r} ${n} ${W.cyan(e)}`;if(!s)return h.trim();let a=c(h).trim().length,u=c(i).length,y=Math.max(1,l-2-a-u);return`${h.trim()}${" ".repeat(y)}${i}`}formatMessage(t,i){if(i.length===1&&Array.isArray(i[0]))return t.replace(/\{(\d+)\}/g,(f,s)=>{let c=Number.parseInt(s,10);return c<i[0].length?String(i[0][c]):f});let r=/%([sdijfo%])/g,n=0,e=t.replace(r,(f,s)=>{if(s==="%")return"%";if(n>=i.length)return f;let c=i[n++];switch(s){case"s":return String(c);case"d":case"i":return Number(c).toString();case"j":case"o":return JSON.stringify(c,null,2);default:return f}});if(n<i.length)e+=` ${i.slice(n).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`;return e}formatMarkdown(t){if(!t)return t;let i=t;return i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,n,e)=>{let f=W.underline(W.blue(n)),s=this.toAbsoluteFilePath(e);if(s&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let c=`file://${encodeURI(s)}`,l="\x1B]8;;",h="\x1B\\";return`\x1B]8;;${c}\x1B\\${f}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${e}\x1B\\${f}\x1B]8;;\x1B\\`;return f}),i=i.replace(/`([^`]+)`/g,(r,n)=>W.bgGray(n)),i=i.replace(/\*\*([^*]+)\*\*/g,(r,n)=>W.bold(n)),i=i.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,n)=>W.italic(n)),i=i.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,n)=>W.italic(n)),i=i.replace(/~([^~]+)~/g,(r,n)=>W.strikethrough(n)),i}supportsHyperlinks(){if(Z())return!1;let t=R.env;if(!t)return!1;if(t.TERM_PROGRAM==="iTerm.app"||t.TERM_PROGRAM==="vscode"||t.TERM_PROGRAM==="WezTerm")return!0;if(t.WT_SESSION)return!0;if(t.TERM==="xterm-kitty")return!0;let i=t.VTE_VERSION?Number.parseInt(t.VTE_VERSION,10):0;if(!Number.isNaN(i)&&i>=5000)return!0;return!1}toAbsoluteFilePath(t){try{let i=t;if(i.startsWith("file://"))i=i.replace(/^file:\/\//,"");if(i.startsWith("~")){let r=R.env.HOME||"";if(r)i=i.replace(/^~(?=$|\/)/,r)}if(Nw(i)||i.startsWith("./")||i.startsWith("../"))i=jw(i);else return null;return gn(i)?i:null}catch{return null}}buildOutputTexts(t){let i=this.shouldStyleConsole()?this.formatMarkdown(t):t,r=t.replace(this.ANSI_PATTERN,"");return{consoleText:i,fileText:r}}async log(t,i,...r){if(!this.shouldLog(t))return;let n=new Date,e=this.formatConsoleTimestamp(n),f=this.formatFileTimestamp(n),s,c;if(i instanceof Error)s=i.message,c=i.stack;else s=this.formatMessage(i,r);let{consoleText:l,fileText:h}=this.buildOutputTexts(s);if(this.shouldStyleConsole()){let u=this.options.showIcons===!1?"":q$[t],y=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",o;switch(t){case"debug":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:W.gray(l),level:t}),console.error(o);break;case"info":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.warn(o);break;case"success":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:W.green(l),level:t}),console.error(o);break;case"warning":o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.warn(o);break;case"error":if(o=this.formatConsoleMessage({timestamp:e,icon:u,tag:y,message:l,level:t}),console.error(o),c){let m=c.split(`
|
|
109
109
|
`);for(let w of m)if(w.trim()&&!w.includes(s))console.error(this.formatConsoleMessage({timestamp:e,message:W.gray(` ${w}`),level:t,showTimestamp:!1}))}break}}else if(!Z()){if(console.error(`${f} ${this.environment}.${t.toUpperCase()}: ${s}`),c)console.error(c)}let a=`${f} ${this.environment}.${t.toUpperCase()}: ${h}
|
|
110
110
|
`;if(c)a+=`${c}
|
|
111
111
|
`;if(a=a.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(a)}progress(t,i=""){let r={update:(c,l)=>{},finish:(c)=>{},interrupt:(c,l)=>{}};if(!this.enabled)return r;let n=30;if(this.activeProgressBar={total:Math.max(1,t||1),current:0,message:i||"",barLength:n,lastRenderedLine:""},this.shouldStyleConsole()&&!Z()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(c,l)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,c),this.activeProgressBar.total),l!==void 0)this.activeProgressBar.message=l;if(this.shouldStyleConsole()&&!Z()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(c)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,c)},interrupt:(c,l="info")=>{if(!Z()&&R.stdout.isTTY)R.stdout.write(`
|
|
112
112
|
`);if(this[l==="warning"?"warn":l](c),this.activeProgressBar&&this.shouldStyleConsole()&&!Z()&&R.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(t){let i=performance.now();if(this.shouldStyleConsole()){let r=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",n=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:n,icon:this.options.showIcons===!1?"":W.blue("◐"),tag:r,message:`${W.cyan(t)}...`}))}return async(r)=>{if(!this.enabled)return;let n=performance.now(),e=Math.round(n-i),f=`${t} completed in ${e}ms`,s=new Date,c=this.formatConsoleTimestamp(s),h=`${this.formatFileTimestamp(s)} ${this.environment}.INFO: ${f}`;if(r)h+=` ${JSON.stringify(r)}`;if(h+=`
|
|
113
|
-
`,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":W.green("✓"),tag:a,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Z())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Qn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Z())throw Error("createReadStream is not supported in browser environments");if(!
|
|
114
|
-
`),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,
|
|
115
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(Z())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${W.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();R.stdin.removeListener("data",r);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(a,
|
|
116
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=W.green("━".repeat(n)),s=W.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?W.green("✓"):W.blue("▶"),
|
|
117
|
-
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||Z()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(Z()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Bn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=qi(this.config.logDirectory,n);if(t.before)try{if((await xi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Rn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var
|
|
113
|
+
`,h=h.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let a=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:c,icon:this.options.showIcons===!1?"":W.green("✓"),tag:a,message:`${f}${r?` ${JSON.stringify(r)}`:""}`}))}else if(!Z())console.error(h.trim());if(this.shouldWriteToFile())await this.writeToFile(h)}}async debug(t,...i){await this.log("debug",t,...i)}async info(t,...i){await this.log("info",t,...i)}async success(t,...i){await this.log("success",t,...i)}async warn(t,...i){await this.log("warning",t,...i)}async error(t,...i){await this.log("error",t,...i)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let t=this.config.rotation,{encrypt:i}=t;return!!i}async only(t){if(!this.enabled)return;return await t()}isEnabled(){return this.enabled}setEnabled(t){this.enabled=t}extend(t){let i=`${this.name}:${t}`,r=new Qn(i,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(r),r}createReadStream(){if(Z())throw Error("createReadStream is not supported in browser environments");if(!gn(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return lh(this.currentLogFile,{encoding:"utf8"})}async decrypt(t){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let i=this.config.rotation;if(!i.encrypt||typeof i.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let r=this.keys.get(this.currentKeyId);try{let n=Zt.isBuffer(t)?t:Zt.from(t,"base64"),e=n.subarray(0,16),f=n.subarray(n.length-16),s=n.subarray(16,n.length-16),c=Bw("aes-256-gcm",r,e);c.setAuthTag(f);let l=c.update(s),h=c.final(),a=l.length+h.length,u=Zt.allocUnsafe(a);return l.copy(u,0),h.copy(u,l.length),u.toString("utf8")}catch(n){throw Error(`Decryption failed: ${n instanceof Error?n.message:String(n)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Z()}isServerMode(){return!Z()}setTestEncryptionKey(t,i){this.currentKeyId=t,this.keys.set(t,i)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(t){if(!this.enabled)return;let i=new Date,r=this.formatConsoleTimestamp(i),n=this.formatFileTimestamp(i),{consoleText:e,fileText:f}=this.buildOutputTexts(t);if(this.shouldStyleConsole()){let c=e.split(`
|
|
114
|
+
`),l=Math.max(...c.map((y)=>y.length))+2,h=`┌${"─".repeat(l)}┐`,a=`└${"─".repeat(l)}┘`,u=c.map((y)=>{return this.formatConsoleMessage({timestamp:r,message:W.cyan(y),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:r,message:W.cyan(h),showTimestamp:!1})),u.forEach((y)=>console.error(y)),console.error(this.formatConsoleMessage({timestamp:r,message:W.cyan(a),showTimestamp:!1}))}else if(!Z())console.error(`${n} ${this.environment}.INFO: [BOX] ${f}`);let s=`${n} ${this.environment}.INFO: [BOX] ${f}
|
|
115
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(s)}async prompt(t){if(Z())return Promise.resolve(!0);return new Promise((i)=>{console.error(`${W.cyan("?")} ${t} (y/n) `);let r=(n)=>{let e=n.toString().trim().toLowerCase();R.stdin.removeListener("data",r);try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!1)}catch{}R.stdin.pause(),console.error(""),i(e==="y"||e==="yes")};try{if(typeof R.stdin.setRawMode==="function")R.stdin.setRawMode(!0)}catch{}R.stdin.resume(),R.stdin.once("data",r)})}setFancy(t){this.fancy=t}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(t,...i){if(!this.enabled)return;let r=t;if(i&&i.length>0){let l=/%([sdijfo%])/g,h=0;if(r=t.replace(l,(a,u)=>{if(u==="%")return"%";if(h>=i.length)return a;let y=i[h++];switch(u){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 a}}),h<i.length)r+=` ${i.slice(h).map((a)=>typeof a==="object"?JSON.stringify(a,null,2):String(a)).join(" ")}`}let{consoleText:n,fileText:e}=this.buildOutputTexts(r);if(this.shouldStyleConsole()){let l=this.options.showTags!==!1&&this.name?W.gray(this.formatTag(this.name)):"",h=this.options.showIcons===!1?"":`${W.blue("◐")} `;console.error(`${h}${l} ${W.cyan(n)}`)}let c=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${e}
|
|
116
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(c)}renderProgressBar(t,i=!1){if(!this.enabled||!this.shouldStyleConsole()||!R.stdout.isTTY)return;let r=Math.min(100,Math.max(0,Math.round(t.current/t.total*100))),n=Math.round(t.barLength*r/100),e=t.barLength-n,f=W.green("━".repeat(n)),s=W.gray("━".repeat(e)),c=`[${f}${s}]`,l=`${r}%`.padStart(4),h=t.message?` ${t.message}`:"",a=this.options.showIcons===!1?"":i||r===100?W.green("✓"):W.blue("▶"),u=this.options.showTags!==!1&&this.name?` ${W.gray(this.formatTag(this.name))}`:"",y=`\r${a}${u} ${c} ${l}${h}`,o=R.stdout.columns||80,m=" ".repeat(Math.max(0,o-y.replace(this.ANSI_PATTERN,"").length));if(t.lastRenderedLine=`${y}${m}`,R.stdout.write(t.lastRenderedLine),i)R.stdout.write(`
|
|
117
|
+
`)}finishProgressBar(t,i){if(!this.enabled||!this.fancy||Z()||!R.stdout.isTTY){this.activeProgressBar=null;return}if(t.current<t.total)t.current=t.total;if(i)t.message=i;this.renderProgressBar(t,!0),this.activeProgressBar=null}async clear(t={}){if(Z()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let i=await Bn(this.config.logDirectory),r=[];for(let n of i){if(!(t.name?new RegExp(t.name.replace("*",".*")).test(n):n.startsWith(this.name))||!n.endsWith(".log"))continue;let f=qi(this.config.logDirectory,n);if(t.before)try{if((await xi(f)).mtime>=t.before)continue}catch(s){console.error(`Failed to get stats for file ${f}:`,s);continue}r.push(f)}if(r.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${r.length} log file(s)...`);for(let n of r)try{await Rn(n),console.warn(`Deleted log file: ${n}`)}catch(e){console.error(`Failed to delete log file ${n}:`,e)}console.warn("Log clearing process finished.")}catch(i){console.error("Error during log clearing process:",i)}}}var mE=new Qn("stacks");class Ht extends Error{timestamp;context;constructor(t,i={}){super(t);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=i,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let t=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([i,r])=>`${i}: ${r}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${t}`}}class ph extends Ht{code="CONFIG_NOT_FOUND";constructor(t,i,r){let n=r===void 0?[]:Array.isArray(r)?r.filter(Boolean):[r],e="";if(n.length===1)e=` or alias "${n[0]}"`;else if(n.length>1)e=` or aliases ${n.map((f)=>`"${f}"`).join(", ")}`;super(`Configuration "${t}"${e} not found`,{configName:t,alias:r,searchPaths:i,searchPathCount:i.length})}}class bn extends Ht{code="CONFIG_LOAD_ERROR";constructor(t,i,r){super(`Failed to load configuration from "${t}": ${i.message}`,{configPath:t,configName:r,originalError:i.name,originalMessage:i.message});this.cause=i}}class Ph extends Ht{code="CONFIG_VALIDATION_ERROR";constructor(t,i,r){super(`Configuration validation failed for "${t}"`,{configPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class vh extends Ht{code="CONFIG_MERGE_ERROR";constructor(t,i,r,n){super(`Failed to merge configuration from "${t}" with "${i}": ${r.message}`,{sourcePath:t,targetPath:i,configName:n,originalError:r.name,originalMessage:r.message});this.cause=r}}class es extends Ht{code="ENV_VAR_ERROR";constructor(t,i,r,n){super(`Failed to parse environment variable "${t}" with value "${i}" as ${r}`,{envKey:t,envValue:i,expectedType:r,configName:n})}}class Qh extends Ht{code="FILE_SYSTEM_ERROR";constructor(t,i,r){super(`File system ${t} failed for "${i}": ${r.message}`,{operation:t,path:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Zh extends Ht{code="TYPE_GENERATION_ERROR";constructor(t,i,r){super(`Failed to generate types from "${t}" to "${i}": ${r.message}`,{configDir:t,outputPath:i,originalError:r.name,originalMessage:r.message});this.cause=r}}class Vn extends Ht{code="SCHEMA_VALIDATION_ERROR";constructor(t,i,r){super(`Schema validation failed${r?` for config "${r}"`:""}`,{schemaPath:t,configName:r,validationErrors:i,errorCount:i.length})}}class ta extends Ht{code="BROWSER_CONFIG_ERROR";constructor(t,i,r,n){super(`Failed to fetch configuration from "${t}": ${i} ${r}`,{endpoint:t,status:i,statusText:r,configName:n})}}class ia extends Ht{code="PLUGIN_ERROR";constructor(t,i,r){super(`Plugin "${t}" failed during ${i}: ${r.message}`,{pluginName:t,operation:i,originalError:r.name,originalMessage:r.message});this.cause=r}}var bi={configNotFound(t,i,r){return new ph(t,i,r)},configLoad(t,i,r){return new bn(t,i,r)},configValidation(t,i,r){return new Ph(t,i,r)},configMerge(t,i,r,n){return new vh(t,i,r,n)},envVar(t,i,r,n){return new es(t,i,r,n)},fileSystem(t,i,r){return new Qh(t,i,r)},typeGeneration(t,i,r){return new Zh(t,i,r)},schemaValidation(t,i,r){return new Vn(t,i,r)},browserConfig(t,i,r,n){return new ta(t,i,r,n)},plugin(t,i,r){return new ia(t,i,r)}};async function k$(t,i={}){let{maxRetries:r=3,retryDelay:n=1000,isRetryable:e=()=>!0,fallback:f}=i,s=Error("Unknown error occurred");for(let c=0;c<=r;c++)try{return await t()}catch(l){if(s=l instanceof Error?l:Error(String(l)),c===r||!e(s))break;if(n>0)await new Promise((h)=>setTimeout(h,n))}if(f!==void 0)return f;throw s instanceof Error?s:Error(`Unknown error: ${String(s)}`)}class fs{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(t,i)=>i==="boolean"||["true","false","1","0","yes","no"].includes(t.toLowerCase()),parse:(t)=>{let i=t.toLowerCase();return["true","1","yes"].includes(i)}},{name:"number",canParse:(t,i)=>i==="number"||!Number.isNaN(Number(t))&&!Number.isNaN(Number.parseFloat(t)),parse:(t)=>{let i=Number(t);if(Number.isNaN(i))throw TypeError(`Cannot parse "${t}" as number`);return i}},{name:"array",canParse:(t,i)=>i==="array"||t.startsWith("[")||t.includes(","),parse:(t)=>{try{let i=JSON.parse(t);if(Array.isArray(i))return i}catch{}return t.split(",").map((i)=>i.trim())}},{name:"json",canParse:(t,i)=>i==="object"||(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")),parse:(t)=>{try{return JSON.parse(t)}catch(i){throw Error(`Cannot parse "${t}" as JSON: ${i}`)}}}]}async applyEnvironmentVariables(t,i,r={}){let{prefix:n,useCamelCase:e=!0,useBackwardCompatibility:f=!0,customParsers:s={},verbose:c=!1,trackPerformance:l=!0}=r,h=async()=>{if(!t)return{config:i,source:{type:"environment",priority:50,timestamp:new Date}};let a=n||this.generateEnvPrefix(t),u={...i};return this.processObject(u,[],a,{useCamelCase:e,useBackwardCompatibility:f,customParsers:s,verbose:c,configName:t}),{config:u,source:{type:"environment",priority:50,timestamp:new Date}}};if(l)return Pf.track("applyEnvironmentVariables",h,{configName:t});return h()}generateEnvPrefix(t){return t.toUpperCase().replace(/-/g,"_")}formatEnvKey(t,i){if(!i)return t.toUpperCase();return t.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=s.map((a)=>this.formatEnvKey(a,n.useCamelCase)),l=`${r}_${c.join("_")}`,h=n.useBackwardCompatibility?`${r}_${s.map((a)=>a.toUpperCase()).join("_")}`:null;if(n.verbose);if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.processObject(f,s,r,n);else{let a=Un.env[l]||(h?Un.env[h]:void 0);if(a!==void 0){if(n.verbose){let u=Un.env[l]?l:h}try{t[e]=this.parseEnvironmentValue(a,typeof f,l,n.customParsers,n.configName)}catch(u){if(u instanceof es)throw u;throw bi.envVar(l,a,typeof f,n.configName)}}}}}parseEnvironmentValue(t,i,r,n,e){for(let[f,s]of Object.entries(n))try{return s(t)}catch{continue}for(let f of this.defaultParsers)if(f.canParse(t,i))try{return f.parse(t)}catch{throw bi.envVar(r,t,`${i} (via ${f.name} parser)`,e)}return t}getEnvironmentVariables(t){let i={},r=t.toUpperCase();for(let[n,e]of Object.entries(Un.env))if(n.startsWith(r)&&e!==void 0)i[n]=e;return i}validateEnvironmentVariable(t,i,r){let n=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(t))n.push(`Environment variable key "${t}" should only contain uppercase letters, numbers, and underscores`);if(r)try{this.parseEnvironmentValue(t,i,r,{})}catch(e){n.push(`Cannot parse value "${i}" as ${r}: ${e}`)}return{isValid:n.length===0,errors:n}}generateEnvVarDocs(t,i,r={}){let{prefix:n,format:e="text"}=r,f=n||this.generateEnvPrefix(t),s=[];switch(this.extractEnvVarInfo(i,[],f,s),e){case"markdown":return this.formatAsMarkdown(s,t);case"json":return JSON.stringify(s,null,2);default:return this.formatAsText(s,t)}}extractEnvVarInfo(t,i,r,n){for(let[e,f]of Object.entries(t)){let s=[...i,e],c=`${r}_${s.map((l)=>this.formatEnvKey(l,!0)).join("_")}`;if(typeof f==="object"&&f!==null&&!Array.isArray(f))this.extractEnvVarInfo(f,s,r,n);else n.push({key:c,type:Array.isArray(f)?"array":typeof f,description:`Configuration for ${s.join(".")}`,example:this.generateExample(f)})}}generateExample(t){if(Array.isArray(t))return JSON.stringify(t);if(typeof t==="object"&&t!==null)return JSON.stringify(t);return String(t)}formatAsText(t,i){let r=`Environment Variables for ${i}:
|
|
118
118
|
|
|
119
119
|
`;for(let n of t)r+=`${n.key}
|
|
120
120
|
`,r+=` Type: ${n.type}
|
|
@@ -126,36 +126,36 @@ export type ConfigOf = Config
|
|
|
126
126
|
`;r+=`| Variable | Type | Description | Example |
|
|
127
127
|
`,r+=`|----------|------|-------------|----------|
|
|
128
128
|
`;for(let n of t)r+=`| \`${n.key}\` | ${n.type} | ${n.description} | \`${n.example}\` |
|
|
129
|
-
`;return r}}function G$(t,i,r={}){return Zh(t,i,r,new WeakMap)}function Zh(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return ta(t,i,e,n);if(!Ut(i)||!Ut(t))return i;return b$(t,i,r,n)}function ta(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return x$(t,i);case"smart":return q$(t,i,n);default:return i}return i}function x$(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>pf(e,n)))r.push(n);return r}function q$(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Ut(i[0])&&Ut(t[0]))return k$(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function k$(t,i,r){let n=[...i];for(let e of t){if(!Ut(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Ut(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function b$(t,i,r,n){let e=i;if(Ut(e)&&n.has(e))return n.get(e);let f={...t};if(Ut(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Ut(c)&&Ut(l))f[s]=Zh(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=ta(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function ia(t,i,r="replace"){return G$(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function pf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!pf(t[r],i[r]))return!1;return!0}if(Ut(t)&&Ut(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!pf(t[e],i[e]))return!1}return!0}return!1}function Ut(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class ra{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Jn.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Fn(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),o=a.default||a,y="default"in a,u=Object.keys(a).length>0;if(!y&&!u)throw new Dn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof o!=="object"||o===null||Array.isArray(o))throw new Dn(t,Error("Configuration must export a valid object"),"unknown");let d={config:ia(i,o,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Jn.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?Di.configLoad(t,h):Di.configLoad(t,Error(String(h)))}};if(s)return Vf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Of(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return L$(async()=>{return Fn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Fn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Of(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Of(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!Fn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var p$=/^https?:\/\//;class na{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],o=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(u){return a.push({path:"",message:`Validation failed: ${u}`,rule:"system"}),{isValid:!1,errors:a,warnings:o}}};if(c)return await Vf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!D$(i))throw new pn(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new pn(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:p$},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ti=new Qn("bunfig",{showTags:!0});function V$(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class ea{fileLoader=new ra;envProcessor=new es;validator=new na;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),o=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(o&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)ti.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw ti.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,o=f||Vn.cwd(),y=[],u=await this.loadLocalConfiguration(n,e,o,s,c,h,a,l,r);if(u)return y.push(...this.getLocalSearchPaths(n,e,o,s)),this.finalizeResult(u,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,o,c,h,a,l);if(w)return y.push(Rt(o,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,o,s)),i)throw Di.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${V$(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Nn(t,e,s):e,a=this.getLocalDirectories(r,n);for(let o of a){if(s)ti.info(`Searching for configuration in: ${o}`);let y=this.fileLoader.generateConfigPaths(t,o,i),u=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(u){if(s)ti.success(`Configuration loaded from: ${u.source.path}`);return u}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Nn(t,r,e):r,c=[Rt(Ji(),".config",t),Rt(Ji(),".config"),Ji()];for(let l of c){if(e)ti.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)ti.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Nn(t,n,f):n;try{let l=Rt(r,"package.json");if(!Gy(l))return null;let h={};try{h=JSON.parse(xy(l,"utf8"))}catch(y){if(f)ti.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let a=h[t],o=t;if(!a&&i){let y=Array.isArray(i)?i:[i];for(let u of y){if(!u)continue;if(h[u]){a=h[u],o=u;break}}}if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)ti.success(`Configuration loaded from package.json: ${o}`);return{config:ia(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)ti.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Nn(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw Di.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Jn.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Jn.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Rt(t,"config"),Rt(t,".config"),i?Rt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Rt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Rt(Ji(),".config",t),Rt(Ji(),".config"),Ji()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var mE=new ea;function Nn(t,i,r=!1){let n=new es,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let o=[...c,h],y=[`${e}_${o.join("_").toUpperCase()}`,`${e}_${o.map((w)=>w.toUpperCase()).join("")}`,`${e}_${o.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],u,m;for(let w of y)if(u=Vn.env[w],u!==void 0){m=w;break}if(u!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(u.toLowerCase());else if(typeof a==="number"){let w=Number(u);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(u)}catch{l[h]=u.split(",").map((w)=>w.trim())}else l[h]=u;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,o)}return l}return f(i)}var dE=Rt(Vn.cwd(),"config"),AE=Rt(Vn.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",P$={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:ss(fs(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:ss(fs(),".stacks","ssl","stacks.localhost.crt"),keyPath:ss(fs(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var fa=P$;import{execSync as wr}from"node:child_process";import{homedir as i0}from"node:os";import{join as r0}from"node:path";import{execSync as Zn}from"node:child_process";function sa(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function te(t){try{let i=Zn(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return sa(i)}catch{return null}}function v$(t){try{return Zn(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function Q$(t,i){try{let r=Zn(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((n)=>r.includes(`DNS:${n}`))}catch{return!1}}function Z$(t,i,r=443){try{return Zn(`echo | openssl s_client -connect ${t}:${r} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function t0(t){let i=[];for(let r of t.split(`
|
|
130
|
-
`)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)i.push(n[1].toUpperCase())}return i}var
|
|
131
|
-
`)){let f=e.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(f)n.push(f[1].toUpperCase())}return n}function ie(t){if(process.platform!=="darwin")return;let i=te(t.caPath);if(!i)return;let r=t.commonName??
|
|
132
|
-
`))if(f.toUpperCase().includes("SHA-256")){if(f.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return $("ssl",`Root CA fingerprint found in ${n}`,i?.verbose),!0}}catch{}return!1}function
|
|
129
|
+
`;return r}}function D$(t,i,r={}){return ra(t,i,r,new WeakMap)}function ra(t,i,r,n){let{arrayMergeMode:e="replace",skipNullish:f=!1,customMerger:s}=r;if(i===null||i===void 0)return f?t:i;if(s){let c=s(t,i);if(c!==void 0)return c}if(Array.isArray(i)||Array.isArray(t))return na(t,i,e,n);if(!Ft(i)||!Ft(t))return i;return P$(t,i,r,n)}function na(t,i,r,n){if(Array.isArray(i)&&!Array.isArray(t))return i;if(Array.isArray(t)&&!Array.isArray(i))return i;if(Array.isArray(i)&&Array.isArray(t))switch(r){case"replace":return i;case"concat":return b$(t,i);case"smart":return V$(t,i,n);default:return i}return i}function b$(t,i){let r=[...i];for(let n of t)if(!r.some((e)=>pf(e,n)))r.push(n);return r}function V$(t,i,r){if(i.length===0)return t;if(t.length===0)return i;if(Ft(i[0])&&Ft(t[0]))return p$(t,i,r);if(i.every((n)=>typeof n==="string")&&t.every((n)=>typeof n==="string")){let n=[...i];for(let e of t)if(!n.includes(e))n.push(e);return n}return i}function p$(t,i,r){let n=[...i];for(let e of t){if(!Ft(e)){n.push(e);continue}let f=["id","name","key","path","type"],s=!1;for(let c of f)if(c in e){if(n.find((h)=>Ft(h)&&(c in h)&&h[c]===e[c])){s=!0;break}}if(!s)n.push(e)}return n}function P$(t,i,r,n){let e=i;if(Ft(e)&&n.has(e))return n.get(e);let f={...t};if(Ft(e))n.set(e,f);for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let c=e[s],l=f[s];if(r.skipNullish&&(c===null||c===void 0))continue;if(c===null||c===void 0){f[s]=c;continue}if(Ft(c)&&Ft(l))f[s]=ra(l,c,r,n);else if(Array.isArray(c)||Array.isArray(l))f[s]=na(l,c,r.arrayMergeMode||"smart",n);else f[s]=c}return f}function ea(t,i,r="replace"){return D$(t,i,{arrayMergeMode:r==="replace"?"replace":"smart",skipNullish:!0})}function pf(t,i){if(t===i)return!0;if(Array.isArray(t)&&Array.isArray(i)){if(t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!pf(t[r],i[r]))return!1;return!0}if(Ft(t)&&Ft(i)){let r=Object.keys(t),n=Object.keys(i);if(r.length!==n.length)return!1;for(let e of r){if(!Object.prototype.hasOwnProperty.call(i,e))return!1;if(!pf(t[e],i[e]))return!1}return!0}return!1}function Ft(t){return Boolean(t&&typeof t==="object"&&!Array.isArray(t))}class fa{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(t,i,r={}){let{arrayStrategy:n="replace",useCache:e=!0,cacheTtl:f,trackPerformance:s=!0,verbose:c=!1}=r;if(e){let h=Jn.getWithFileCheck("file",t);if(h){if(c)console.log(`Configuration loaded from cache: ${t}`);return h}}let l=async()=>{if(!Fn(t))return null;try{let h=`?t=${Date.now()}`,a=await import(t+h),u=a.default||a,y="default"in a,o=Object.keys(a).length>0;if(!y&&!o)throw new bn(t,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof u!=="object"||u===null||Array.isArray(u))throw new bn(t,Error("Configuration must export a valid object"),"unknown");let d={config:ea(i,u,n),source:{type:"file",path:t,priority:100,timestamp:new Date}};if(e)Jn.setWithFileCheck("file",d,t,f);return d}catch(h){throw h instanceof Error?bi.configLoad(t,h):bi.configLoad(t,Error(String(h)))}};if(s)return Pf.track("loadFromPath",l,{path:t});return l()}async tryLoadFromPaths(t,i,r={}){for(let n of t)try{let e=await this.loadFromPath(n,i,r);if(e)return e}catch(e){if(e instanceof Error&&e.name==="ConfigLoadError")throw e;if(r.verbose)console.warn(`Failed to load config from ${n}:`,e)}return null}generateConfigPaths(t,i,r){let n=this.generateNamePatterns(t,r),e=[];for(let f of n)for(let s of this.extensions)e.push(Kf(i,`${f}${s}`));return e}generateNamePatterns(t,i){let r=[];if(r.push("config",".config"),t)r.push(t,`.${t}.config`,`${t}.config`,`.${t}`);let n=i===void 0?[]:Array.isArray(i)?i:[i];for(let f of n){if(!f)continue;if(r.push(f,`.${f}.config`,`${f}.config`,`.${f}`),t)r.push(`${t}.${f}.config`,`.${t}.${f}.config`)}let e=new Set;return r.filter((f)=>{if(!f||e.has(f))return!1;return e.add(f),!0})}checkFileAccess(t){return k$(async()=>{return Fn(t)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(t,i,r){let n=[];if(!Fn(t))return n;if(i||r){let e=this.generateNamePatterns(i||"",r);for(let f of e)for(let s of this.extensions){let c=Kf(t,`${f}${s}`);if(await this.checkFileAccess(c))n.push(c)}}else try{let{readdirSync:e}=await import("fs"),f=e(t);for(let s of f)if(this.looksLikeConfigFile(s)){let c=Kf(t,s);if(await this.checkFileAccess(c))n.push(c)}}catch{return[]}return n}looksLikeConfigFile(t){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((r)=>r.test(t))}async validateConfigFile(t){let i=[];try{if(!Fn(t))return i.push("Configuration file does not exist"),i;let r=await import(t),n=r.default||r;if(n===void 0)i.push("Configuration file must export a default value or named exports");else if(typeof n!=="object"||n===null)i.push("Configuration must be an object");else if(Array.isArray(n))i.push("Configuration cannot be an array at the root level");if(t.endsWith(".json"))try{let{readFileSync:e}=await import("fs"),f=e(t,"utf8");JSON.parse(f)}catch(e){i.push(`Invalid JSON syntax: ${e}`)}}catch(r){i.push(`Failed to load configuration file: ${r}`)}return i}async getFileModificationTime(t){try{let{statSync:i}=await import("fs");return i(t).mtime}catch{return null}}async preloadConfigurations(t,i={}){let r=new Map;return await Promise.allSettled(t.map(async(n)=>{try{let e=await this.loadFromPath(n,{},i);if(e)r.set(n,e.config)}catch(e){if(i.verbose)console.warn(`Failed to preload ${n}:`,e)}})),r}}var Q$=/^https?:\/\//;class sa{async validateConfiguration(t,i,r={}){let{stopOnFirstError:n=!1,validateRequired:e=!0,validateTypes:f=!0,customRules:s=[],trackPerformance:c=!0,verbose:l=!1}=r,h=async()=>{let a=[],u=[],y={stopOnFirstError:n,validateRequired:e,validateTypes:f,customRules:s,trackPerformance:c,verbose:l};try{if(typeof i==="string")return await this.validateWithSchemaFile(t,i,y);else if(Array.isArray(i))return this.validateWithRules(t,[...i,...s],y);else return this.validateWithJSONSchema(t,i,y)}catch(o){return a.push({path:"",message:`Validation failed: ${o}`,rule:"system"}),{isValid:!1,errors:a,warnings:u}}};if(c)return await Pf.track("validateConfiguration",h);return h()}async validateWithSchemaFile(t,i,r){try{if(!v$(i))throw new Vn(i,[{path:"",message:"Schema file does not exist"}]);let n=await import(i),e=n.default||n;if(Array.isArray(e))return this.validateWithRules(t,e,r);else return this.validateWithJSONSchema(t,e,r)}catch(n){throw new Vn(i,[{path:"",message:`Failed to load schema: ${n}`}])}}validateWithJSONSchema(t,i,r){let n=[],e=[];return this.validateObjectAgainstSchema(t,i,"",n,e,r),{isValid:n.length===0,errors:n,warnings:e}}validateObjectAgainstSchema(t,i,r,n,e,f){if(f.validateTypes&&i.type){let s=Array.isArray(t)?"array":typeof t,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(s)){if(n.push({path:r,message:`Expected type ${c.join(" or ")}, got ${s}`,expected:c.join(" or "),actual:s,rule:"type"}),f.stopOnFirstError)return}}if(i.enum&&!i.enum.includes(t)){if(n.push({path:r,message:`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"}),f.stopOnFirstError)return}if(typeof t==="string"){if(i.minLength!==void 0&&t.length<i.minLength)n.push({path:r,message:`String length must be at least ${i.minLength}`,expected:`>= ${i.minLength}`,actual:t.length,rule:"minLength"});if(i.maxLength!==void 0&&t.length>i.maxLength)n.push({path:r,message:`String length must not exceed ${i.maxLength}`,expected:`<= ${i.maxLength}`,actual:t.length,rule:"maxLength"});if(i.pattern){if(!new RegExp(i.pattern).test(t))n.push({path:r,message:`String does not match pattern ${i.pattern}`,expected:i.pattern,actual:t,rule:"pattern"})}}if(typeof t==="number"){if(i.minimum!==void 0&&t<i.minimum)n.push({path:r,message:`Value must be at least ${i.minimum}`,expected:`>= ${i.minimum}`,actual:t,rule:"minimum"});if(i.maximum!==void 0&&t>i.maximum)n.push({path:r,message:`Value must not exceed ${i.maximum}`,expected:`<= ${i.maximum}`,actual:t,rule:"maximum"})}if(Array.isArray(t)&&i.items)for(let s=0;s<t.length;s++){let c=r?`${r}[${s}]`:`[${s}]`;if(this.validateObjectAgainstSchema(t[s],i.items,c,n,e,f),f.stopOnFirstError&&n.length>0)return}if(t&&typeof t==="object"&&!Array.isArray(t)){let s=t;if(f.validateRequired&&i.required){for(let c of i.required)if(!(c in s)){if(n.push({path:r?`${r}.${c}`:c,message:`Missing required property '${c}'`,expected:"required",rule:"required"}),f.stopOnFirstError)return}}if(i.properties){for(let[c,l]of Object.entries(i.properties))if(c in s){let h=r?`${r}.${c}`:c;if(this.validateObjectAgainstSchema(s[c],l,h,n,e,f),f.stopOnFirstError&&n.length>0)return}}if(i.additionalProperties===!1){let c=new Set(Object.keys(i.properties||{}));for(let l of Object.keys(s))if(!c.has(l))e.push({path:r?`${r}.${l}`:l,message:`Additional property '${l}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(t,i,r){let n=[],e=[];for(let f of i)try{let s=this.getValueByPath(t,f.path),c=this.validateWithRule(s,f,f.path);if(n.push(...c),r.stopOnFirstError&&n.length>0)break}catch(s){n.push({path:f.path,message:`Rule validation failed: ${s}`,rule:"system"})}return{isValid:n.length===0,errors:n,warnings:e}}validateWithRule(t,i,r){let n=[];if(i.required&&(t===void 0||t===null))return n.push({path:r,message:i.message||`Property '${r}' is required`,expected:"required",rule:"required"}),n;if(t===void 0||t===null)return n;if(i.type){let e=Array.isArray(t)?"array":typeof t;if(e!==i.type)n.push({path:r,message:i.message||`Expected type ${i.type}, got ${e}`,expected:i.type,actual:e,rule:"type"})}if(i.min!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e<i.min)n.push({path:r,message:i.message||`Value must be at least ${i.min}`,expected:`>= ${i.min}`,actual:e,rule:"min"})}if(i.max!==void 0){let e=Array.isArray(t)?t.length:typeof t==="string"?t.length:typeof t==="number"?t:0;if(e>i.max)n.push({path:r,message:i.message||`Value must not exceed ${i.max}`,expected:`<= ${i.max}`,actual:e,rule:"max"})}if(i.pattern&&typeof t==="string"){if(!i.pattern.test(t))n.push({path:r,message:i.message||`Value does not match pattern ${i.pattern}`,expected:i.pattern.toString(),actual:t,rule:"pattern"})}if(i.enum&&!i.enum.includes(t))n.push({path:r,message:i.message||`Value must be one of: ${i.enum.join(", ")}`,expected:i.enum.join(", "),actual:t,rule:"enum"});if(i.validator){let e=i.validator(t);if(e)n.push({path:r,message:i.message||e,rule:"custom"})}return n}getValueByPath(t,i){if(!i)return t;let r=i.split("."),n=t;for(let e of r)if(n&&typeof n==="object"&&e in n)n=n[e];else return;return n}generateRulesFromInterface(t){let i=[],r=t.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let n of r){let[,e,f,s]=n;i.push({path:e,required:!f,type:this.mapTypeScriptType(s)})}return i}mapTypeScriptType(t){switch(t.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Q$},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}var ti=new Qn("bunfig",{showTags:!0});function Z$(t){if(!t)return"";let i=Array.isArray(t)?t.filter(Boolean):[t];if(i.length===0)return"";if(i.length===1)return` or alias "${i[0]}"`;return` or aliases ${i.map((r)=>`"${r}"`).join(", ")}`}class la{fileLoader=new fa;envProcessor=new fs;validator=new sa;async loadConfig(t){let i=Date.now(),{cache:r,performance:n,schema:e,validate:f,...s}=t;try{if(r?.enabled){let l=this.checkCache(s.name||"",s);if(l)return l}let c;try{c=await this.loadConfigurationStrategies(s,!0,r)}catch(l){let h=s.__strictErrorHandling;if(l instanceof Error&&l.name==="ConfigNotFoundError"){if(h)throw l;c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`No configuration file found for "${s.name||"config"}", using defaults with environment variables`]}}else if(l instanceof Error&&l.name==="ConfigLoadError"){let a=l.message.includes("EACCES")||l.message.includes("EPERM")||l.message.includes("permission denied"),u=!a&&(l.message.includes("syntax")||l.message.includes("Expected")||l.message.includes("Unexpected")||l.message.includes("BuildMessage")||l.message.includes("errors building")),y=l.message.includes("Configuration must export a valid object")||l.message.includes("Configuration file is empty and exports nothing");if(h&&(y||a))throw l;if(u&&(!h||!y))c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!h)c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading error, using defaults: ${l.message}`]};else throw l}else c={...await this.applyEnvironmentVariables(s.name||"",s.defaultConfig,s.checkEnv!==!1,s.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${l instanceof Error?l.message:String(l)}`]}}if(e||f)await this.validateConfiguration(c.config,e,f,s.name);if(r?.enabled&&c)this.cacheResult(s.name||"",c,r,s);if(n?.enabled){let l={operation:"loadConfig",duration:Date.now()-i,configName:s.name,timestamp:new Date};if(n.onMetrics)n.onMetrics(l);if(n.slowThreshold&&l.duration>n.slowThreshold)ti.warn(`Slow configuration loading detected: ${l.duration}ms for ${s.name}`);c.metrics=l}return c}catch(c){if(c instanceof Error&&c.name==="ConfigNotFoundError")throw c;let l=Date.now()-i;throw ti.error(`Configuration loading failed after ${l}ms:`,[c instanceof Error?c:Error(String(c))]),c}}async loadConfigurationStrategies(t,i=!1,r){let{name:n="",alias:e,cwd:f,configDir:s,defaultConfig:c,checkEnv:l=!0,arrayStrategy:h="replace",verbose:a=!1}=t,u=f||pn.cwd(),y=[],o=await this.loadLocalConfiguration(n,e,u,s,c,h,a,l,r);if(o)return y.push(...this.getLocalSearchPaths(n,e,u,s)),this.finalizeResult(o,y,l,n,a);let m=await this.loadHomeConfiguration(n,e,c,h,a,l);if(m)return y.push(...this.getHomeSearchPaths(n,e)),this.finalizeResult(m,y,l,n,a);let w=await this.loadPackageJsonConfiguration(n,e,u,c,h,a,l);if(w)return y.push(Yt(u,"package.json")),this.finalizeResult(w,y,l,n,a);if(y.push(...this.getAllSearchPaths(n,e,u,s)),i)throw bi.configNotFound(n,y,e);return{...await this.applyEnvironmentVariables(n,c,l,a),warnings:[`No configuration file found for "${n}"${Z$(e)}, using defaults with environment variables`]}}async loadLocalConfiguration(t,i,r,n,e,f,s,c,l){let h=c?Nn(t,e,s):e,a=this.getLocalDirectories(r,n);for(let u of a){if(s)ti.info(`Searching for configuration in: ${u}`);let y=this.fileLoader.generateConfigPaths(t,u,i),o=await this.fileLoader.tryLoadFromPaths(y,h,{arrayStrategy:f,verbose:s,cacheTtl:l?.ttl,useCache:!l?.ttl||l.ttl>100});if(o){if(s)ti.success(`Configuration loaded from: ${o.source.path}`);return o}}return null}async loadHomeConfiguration(t,i,r,n,e,f){if(!t)return null;let s=f?Nn(t,r,e):r,c=[Yt(Ji(),".config",t),Yt(Ji(),".config"),Ji()];for(let l of c){if(e)ti.info(`Checking home directory: ${l}`);let h=this.fileLoader.generateConfigPaths(t,l,i),a=await this.fileLoader.tryLoadFromPaths(h,s,{arrayStrategy:n,verbose:e});if(a){if(e)ti.success(`Configuration loaded from home directory: ${a.source.path}`);return a}}return null}async loadPackageJsonConfiguration(t,i,r,n,e,f,s){let c=s?Nn(t,n,f):n;try{let l=Yt(r,"package.json");if(!Dy(l))return null;let h={};try{h=JSON.parse(by(l,"utf8"))}catch(y){if(f)ti.warn("Failed to parse package.json:",[y instanceof Error?y:Error(String(y))]);return null}let a=h[t],u=t;if(!a&&i){let y=Array.isArray(i)?i:[i];for(let o of y){if(!o)continue;if(h[o]){a=h[o],u=o;break}}}if(a&&typeof a==="object"&&!Array.isArray(a)){if(f)ti.success(`Configuration loaded from package.json: ${u}`);return{config:ea(c,a,e),source:{type:"package.json",path:l,priority:30,timestamp:new Date}}}}catch(l){if(f)ti.warn("Failed to load package.json:",[l instanceof Error?l:Error(String(l))])}return null}async applyEnvironmentVariables(t,i,r,n){if(!r||!t||typeof i!=="object"||i===null||Array.isArray(i))return{config:i,source:{type:"default",priority:10,timestamp:new Date}};return{config:Nn(t,i,n),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(t,i,r,n,e){return{config:t.config,source:t.source,path:t.source.path}}async validateConfiguration(t,i,r,n){let e=[];if(r){let f=r(t);if(f)e.push(...f)}if(i){let f=await this.validator.validateConfiguration(t,i);if(!f.isValid)e.push(...f.errors.map((s)=>s.path?`${s.path}: ${s.message}`:s.message))}if(e.length>0)throw bi.configValidation(n||"unknown",e,n)}checkCache(t,i){let r=this.generateCacheKey(t,i);return Jn.get(r)||null}cacheResult(t,i,r,n){let e=this.generateCacheKey(t,n);Jn.set(e,i,void 0,r.ttl)}generateCacheKey(t,i){let r=[t];if(i.alias){let n=Array.isArray(i.alias)?i.alias.join(","):i.alias;r.push(`alias:${n}`)}if(i.cwd)r.push(`cwd:${i.cwd}`);if(i.configDir)r.push(`configDir:${i.configDir}`);if("checkEnv"in i)r.push(`checkEnv:${i.checkEnv}`);return r.join("|")}getLocalDirectories(t,i){return Array.from(new Set([t,Yt(t,"config"),Yt(t,".config"),i?Yt(t,i):void 0].filter(Boolean)))}getAllSearchPaths(t,i,r,n){let e=[];return e.push(...this.getLocalSearchPaths(t,i,r,n)),e.push(...this.getHomeSearchPaths(t,i)),e.push(Yt(r,"package.json")),e}getLocalSearchPaths(t,i,r,n){let e=this.getLocalDirectories(r,n),f=[];for(let s of e)f.push(...this.fileLoader.generateConfigPaths(t,s,i));return f}getHomeSearchPaths(t,i){if(!t)return[];let r=[Yt(Ji(),".config",t),Yt(Ji(),".config"),Ji()],n=[];for(let e of r)n.push(...this.fileLoader.generateConfigPaths(t,e,i));return n}async loadConfigWithResult(t){return this.loadConfig(t)}}var CE=new la;function Nn(t,i,r=!1){let n=new fs,e=t.toUpperCase().replace(/[^A-Z0-9]/g,"_");function f(s,c=[]){let l={...s};for(let[h,a]of Object.entries(s)){let u=[...c,h],y=[`${e}_${u.join("_").toUpperCase()}`,`${e}_${u.map((w)=>w.toUpperCase()).join("")}`,`${e}_${u.map((w)=>w.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],o,m;for(let w of y)if(o=pn.env[w],o!==void 0){m=w;break}if(o!==void 0&&m)if(typeof a==="boolean")l[h]=["true","1","yes"].includes(o.toLowerCase());else if(typeof a==="number"){let w=Number(o);if(!Number.isNaN(w))l[h]=w}else if(Array.isArray(a))try{l[h]=JSON.parse(o)}catch{l[h]=o.split(",").map((w)=>w.trim())}else l[h]=o;else if(a&&typeof a==="object"&&!Array.isArray(a))l[h]=f(a,u)}return l}return f(i)}var SE=Yt(pn.cwd(),"config"),gE=Yt(pn.cwd(),"src/generated");var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",t0={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:ls(ss(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:ls(ss(),".stacks","ssl","stacks.localhost.crt"),keyPath:ls(ss(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var ca=t0;import{execSync as wr}from"node:child_process";import{homedir as f0}from"node:os";import{join as s0}from"node:path";import{execSync as Zn}from"node:child_process";function ha(t){return(t.includes("=")?t.split("=").pop():t).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function te(t){try{let i=Zn(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`,{encoding:"utf8"});return ha(i)}catch{return null}}function i0(t){try{return Zn(`openssl x509 -in "${t}" -noout -subject -nameopt RFC2253`,{encoding:"utf8"}).match(/CN=([^,/]+)/)?.[1]?.trim()??null}catch{return null}}function r0(t,i){try{let r=Zn(`openssl x509 -in "${t}" -noout -text`,{encoding:"utf8"});return i.every((n)=>r.includes(`DNS:${n}`))}catch{return!1}}function n0(t,i,r=443){try{return Zn(`echo | openssl s_client -connect ${t}:${r} -servername ${t} -CAfile "${i}" 2>/dev/null | grep "Verify return code"`,{encoding:"utf8",timeout:4000}).includes(": 0 (ok)")}catch{return!1}}function e0(t){let i=[];for(let r of t.split(`
|
|
130
|
+
`)){let n=r.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(n)i.push(n[1].toUpperCase())}return i}var oi="-d -r trustRoot -p ssl -p basic",Ei="/Library/Keychains/System.keychain",cs="rpx.localhost";function $r(){return s0(f0(),"Library/Keychains/login.keychain-db")}function hs(){return[Ei,$r()]}function aa(t,i=cs){let r=wr(`security find-certificate -a -c "${i}" -Z "${t}" 2>/dev/null || true`,{encoding:"utf8"}),n=[];for(let e of r.split(`
|
|
131
|
+
`)){let f=e.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(f)n.push(f[1].toUpperCase())}return n}function ie(t){if(process.platform!=="darwin")return;let i=te(t.caPath);if(!i)return;let r=t.commonName??cs,n=t.keychains??hs();for(let e of n)for(let f of aa(e,r)){if(f===i)continue;try{if(e.startsWith("/Library"))yr(`security delete-certificate -Z ${f} "${e}"`);else wr(`security delete-certificate -Z ${f} "${e}"`,{stdio:"ignore"});$("ssl",`Removed stale Root CA ${f} from ${e}`,t.verbose)}catch{}}}function mr(t,i,r){if(process.platform!=="darwin")return dr(t,r);try{let e=wr(`security verify-cert -c "${t}" -s "${i}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return $("ssl",`verify-cert ${i}: ${e?"trusted":"not trusted"}`,r?.verbose),e}catch{return!1}}function dr(t,i){let r=te(t);if(!r)return!1;for(let n of hs())try{let e=wr(`security find-certificate -a -Z "${n}" 2>/dev/null || true`,{encoding:"utf8"});for(let f of e.split(`
|
|
132
|
+
`))if(f.toUpperCase().includes("SHA-256")){if(f.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===r)return $("ssl",`Root CA fingerprint found in ${n}`,i?.verbose),!0}}catch{}return!1}function as(t,i){if(process.platform!=="darwin")return!1;let r=i.serverName;ie({caPath:t,commonName:i.commonName,verbose:i.verbose});let n=$r();try{wr(`security add-trusted-cert ${oi} -k "${n}" "${t}"`,{stdio:"ignore"})}catch{}try{yr(`security add-trusted-cert ${oi} -k ${Ei} "${t}"`)}catch{return!1}return mr(t,r,{verbose:i.verbose})||dr(t,{verbose:i.verbose})}var yi=null,l0="rpx-root-ca.crt",c0="rpx-root-ca.key";function ys(t){return{caCertPath:tt(t,l0),caKeyPath:tt(t,c0)}}function pE(t){return{certPath:tt(t,"rpx.localhost.crt"),keyPath:tt(t,"rpx.localhost.key"),caCertPath:tt(t,"rpx.localhost.ca.crt"),rootCA:ys(t)}}async function h0(t,i){try{let[r,n]=await Promise.all([b.readFile(t.caCertPath,"utf8"),b.readFile(t.caKeyPath,"utf8")]);if(!r.includes("-----BEGIN CERTIFICATE-----")||!n.includes("PRIVATE KEY-----"))return $("ssl",`Root CA files at ${t.caCertPath} look malformed, will regenerate`,i),null;return{certificate:r,privateKey:n}}catch(r){return $("ssl",`No existing Root CA at ${t.caCertPath} (${r.code||r}), will create one`,i),null}}function ua(t){let i=new Set;i.add(t);let r=t.split(".");if(r.length>=2)i.add(`*.${r.slice(1).join(".")}`);return Array.from(i)}function ma(t){let r=os(t).replace(/\*/g,"wildcard"),n=tt(ne(),".stacks","ssl"),e=n;if(typeof t?.https==="object")return e=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:n,{caCertPath:t.https.caCertPath||tt(e,`${r}.ca.crt`),certPath:t.https.certPath||tt(e,`${r}.crt`),keyPath:t.https.keyPath||tt(e,`${r}.key`)};return{caCertPath:tt(e,`${r}.ca.crt`),certPath:tt(e,`${r}.crt`),keyPath:tt(e,`${r}.key`)}}function oa(t){let i=new Set;if(re(t))t.proxies.forEach((r)=>{let n=r.to||"rpx.localhost";ua(n).forEach((e)=>i.add(e))});else if(wa(t)){let r=t.to||"rpx.localhost";ua(r).forEach((n)=>i.add(n))}else i.add("rpx.localhost");return i.add("localhost"),i.add("*.localhost"),i}async function PE(t){$("ssl","Loading SSL configuration",t.verbose);let i={...ca,...t};if(t.https=$s(i),!t.https?.keyPath&&!t.https?.certPath)return $("ssl","No SSL configuration provided",t.verbose),null;if(t.https?.keyPath&&!t.https?.certPath||!t.https?.keyPath&&t.https?.certPath){let r=!t.https?.keyPath?"keyPath":"certPath";throw $("ssl",`Invalid SSL configuration - missing ${r}`,t.verbose),Error(`SSL Configuration requires both keyPath and certPath. Missing: ${r}`)}try{if(!t.https?.keyPath||!t.https?.certPath)return null;try{$("ssl","Reading SSL certificate files",t.verbose);let r=await b.readFile(t.https?.keyPath,"utf8"),n=await b.readFile(t.https?.certPath,"utf8");return $("ssl","SSL configuration loaded successfully",t.verbose),{key:r,cert:n}}catch(r){return $("ssl",`Failed to read certificates: ${r}`,t.verbose),null}}catch(r){throw $("ssl",`SSL configuration error: ${r}`,t.verbose),r}}async function vE(t,i){if(Mt.platform==="darwin")return a0(t,i);if(Mt.platform==="linux")try{let{exec:r}=await import("node:child_process");return await new Promise((n)=>{r(`sudo cp "${t}" /usr/local/share/ca-certificates/ && sudo update-ca-certificates`,(e)=>{if(!e)n(!0);else r(`sudo cp "${t}" /etc/pki/ca-trust/source/anchors/ && sudo update-ca-trust extract`,(f)=>{n(!f)})})})}catch{return!1}return!1}async function a0(t,i){if(Mt.platform!=="darwin")return!1;let r=i?.serverName??"rpx.localhost",n=i?.verbose??!1;try{if(mr(t,r,{verbose:n}))return $("ssl","Root CA already trusted for SSL, skipping trust operation",n),!0;return $("ssl","Trusting Root CA for browsers (login + system keychains)",n),as(t,{serverName:r,verbose:n})}catch{return!1}}async function da(t){if(yi&&!t.forceRegenerate){$("ssl","Using cached SSL configuration",t.verbose);return}u0();let i=re(t)?t.proxies.map((a)=>a.to):[t.to];$("ssl",`Generating certificate for domains: ${i.join(", ")}`,t.verbose);let r=$s(t,t.verbose),n=r.basePath||tt(ne(),".stacks","ssl");await b.mkdir(n,{recursive:!0});let e=ys(n),f=await h0(e,t.verbose),s=!1;if(!f){if(t.verbose)H.info("Generating Root CA certificate (one-time)...");f=await mf(r);try{await Promise.all([b.writeFile(e.caCertPath,f.certificate),b.writeFile(e.caKeyPath,f.privateKey,{mode:384})]),s=!0,$("ssl",`Persisted Root CA at ${e.caCertPath}`,t.verbose)}catch(a){throw $("ssl",`Error saving Root CA files: ${a}`,t.verbose),Error(`Failed to save Root CA files: ${a}`)}}else $("ssl",`Reusing existing Root CA from ${e.caCertPath}`,t.verbose);if(t.verbose)H.info(`Generating host certificate for: ${i.join(", ")}`);let c=await df({...r,rootCA:{certificate:f.certificate,privateKey:f.privateKey}});try{await Promise.all([b.writeFile(r.certPath,c.certificate),b.writeFile(r.keyPath,c.privateKey),b.writeFile(r.caCertPath,f.certificate)]),$("ssl","Certificate files saved successfully",t.verbose)}catch(a){throw $("ssl",`Error saving certificate files: ${a}`,t.verbose),Error(`Failed to save certificate files: ${a}`)}if(s?!1:await Aa(e.caCertPath,{verbose:t.verbose,regenerateUntrustedCerts:!0})){if($("ssl","Root CA already trusted, skipping trust store update",t.verbose),t.verbose)H.success("Root CA is already trusted in system trust store");if(yi={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)H.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);return}if(t.verbose)H.info("Adding certificate to system trust store (may require sudo permission)...");let h=!1;if(Mt.platform==="darwin")try{ie({caPath:e.caCertPath,verbose:t.verbose});let a=$r();try{Vi(`security add-trusted-cert ${oi} -k "${a}" "${e.caCertPath}"`,{stdio:"ignore"})}catch{}if(yr(`security add-trusted-cert ${oi} -k ${Ei} "${e.caCertPath}"`),t.verbose)H.success("Successfully added Root CA to system trust store");h=!0;let u=tt(n,"trust-rpx-cert.sh"),y=`#!/bin/bash
|
|
133
133
|
echo "Trusting RPX Root CA"
|
|
134
|
-
sudo security add-trusted-cert ${
|
|
134
|
+
sudo security add-trusted-cert ${oi} -k ${Ei} "${e.caCertPath}"
|
|
135
135
|
echo "Root CA trusted! Please restart your browser."
|
|
136
136
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
137
|
-
`;await
|
|
137
|
+
`;await b.writeFile(u,y,{mode:493})}catch(a){if(t.verbose)H.warn(`Could not add Root CA to trust store automatically: ${a}`);let u=tt(n,"trust-rpx-cert.sh"),y=`#!/bin/bash
|
|
138
138
|
echo "Trusting RPX Root CA"
|
|
139
|
-
sudo security add-trusted-cert ${
|
|
139
|
+
sudo security add-trusted-cert ${oi} -k ${Ei} "${e.caCertPath}"
|
|
140
140
|
echo "Root CA trusted! Please restart your browser."
|
|
141
141
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
142
|
-
`;if(await
|
|
142
|
+
`;if(await b.writeFile(u,y,{mode:493}),t.verbose)H.info(`Created a trust helper script at: ${u}`),H.info(`If you're still having certificate issues, run: sh ${u}`)}else if(Mt.platform==="linux")try{let{exec:a}=await import("node:child_process"),u="/usr/local/share/ca-certificates/rpx",y=`
|
|
143
143
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
144
144
|
cp "${e.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
145
145
|
update-ca-certificates
|
|
146
146
|
echo "RPX Root CA installed. Please restart your browser."
|
|
147
|
-
`,
|
|
147
|
+
`,o=tt(us.tmpdir(),`rpx-trust-${Date.now()}.sh`);await b.writeFile(o,y,{mode:493}),await new Promise((m)=>{a(`sudo bash "${o}"`,(w)=>{if(w){if(t.verbose)H.warn(`Could not trust certificates: ${w}`);m(!1)}else{if(t.verbose)H.success("Successfully added certificates to system trust store");m(!0)}})}),await b.unlink(o).catch(()=>{}),h=!0}catch(a){if(t.verbose)H.warn(`Failed to trust certificates: ${a}`)}else if(Mt.platform==="win32")try{let a=`
|
|
148
148
|
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${e.caCertPath.replace(/\//g,"\\")}")
|
|
149
149
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
150
150
|
$store.Open("ReadWrite")
|
|
151
151
|
$store.Add($cert)
|
|
152
152
|
$store.Close()
|
|
153
153
|
Write-Host "Root CA trusted successfully!"
|
|
154
|
-
`,o=tt(as.tmpdir(),"rpx-trust.ps1");if(await D.writeFile(o,a),pi(`powershell -ExecutionPolicy Bypass -File "${o}"`),t.verbose)K.success("Successfully added certificate to Windows trust store");h=!0}catch(a){if(t.verbose)K.warn(`Could not trust certificate: ${a}`)}else try{await df(c,f.certificate,r),h=!0}catch(a){if(t.verbose)K.warn(`Could not add certificate to trust store: ${a}`)}if(yi={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)K.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!h&&t.verbose)K.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),K.warn("This will bypass the warning and you should only need to do it once")}function l0(){yi=null}async function ys(t){if(!t)return null;if(yi)return yi;let i=ws(t);try{let[r,n,e]=await Promise.all([D.access(i.keyPath).then(()=>!0).catch(()=>!1),D.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?D.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return $("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let f="regenerateUntrustedCerts"in t,s=t.regenerateUntrustedCerts,c=f?s!==!1:!0;$("ssl",`Trust check: hasFlag=${f}, flagValue=${s}, shouldCheckTrust=${c}`,t.verbose);let l=i.basePath||tt(ne(),".stacks","ssl"),h=us(l);if(!(c?await $a(h.caCertPath,t):!0))return $("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[o,y,u]=await Promise.all([D.readFile(i.keyPath,"utf8"),D.readFile(i.certPath,"utf8"),e&&i.caCertPath?D.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(u&&!u.includes("-----BEGIN CERTIFICATE-----"))return $("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(re(t))try{let{X509Certificate:m}=await import("node:crypto"),d=new m(y).subjectAltName||"",T=t.proxies.map((Y)=>Y.to).filter((Y)=>!d.includes(`DNS:${Y}`));if(T.length>0)return $("ssl",`Certificate missing SANs for: ${T.join(", ")}, will regenerate`,t.verbose),null}catch(m){$("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return $("ssl","Successfully loaded existing certificates",t.verbose),yi={key:o,cert:y,ca:u},yi}catch(r){return $("ssl",`Error checking existing certificates: ${r}`,t.verbose),null}}function ws(t,i){let r=os(t);$("ssl",`Primary domain: ${r}`,i);let n=ya(t),e=tt(ne(),".stacks","ssl");if(typeof t.https==="object"){let f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:e,s={domain:r,hostCertCN:r,basePath:f,caCertPath:t.https.caCertPath||n.caCertPath,certPath:t.https.certPath||n.certPath,keyPath:t.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||r,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(ha(t)).map((c)=>({type:2,value:c}))};if(aa(t.https.rootCA))s.rootCA=t.https.rootCA;return s}return{domain:r,hostCertCN:r,basePath:e,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(ha(t)).map((f)=>({type:2,value:f}))}}async function DE(t,i){let r=ya({to:t,verbose:i}),n=[r.caCertPath,r.certPath,r.keyPath];$("certificates","Attempting to clean up relating certificates",i),await Promise.all(n.map((e)=>ua(e,i)))}async function $a(t,i){try{if($("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),Mt.platform==="darwin"){if(i?.serverName)return mr(t,i.serverName,{verbose:i.verbose});return dr(t,{verbose:i.verbose})}else if(Mt.platform==="win32")try{let n=pi(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!n)return $("ssl","Could not extract certificate subject",i?.verbose),!1;let e=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(pi(e).toString().includes(n))return $("ssl","Certificate found in trusted root store",i?.verbose),!0;return $("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(r){return $("ssl",`Error checking certificate trust on Windows: ${r}`,i?.verbose),!1}else if(Mt.platform==="linux")try{let n=pi(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",e=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of e)try{if(pi(`find ${f} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${n}"`).toString().includes(n))return $("ssl",`Certificate fingerprint found in ${f}`,i?.verbose),!0}catch{}return $("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(r){return $("ssl",`Error checking certificate trust on Linux: ${r}`,i?.verbose),!1}return $("ssl",`Platform ${Mt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(r){return $("ssl",`Error checking if certificate is trusted: ${r}`,i?.verbose),!1}}import*as Ft from"node:path";function ma(t,i){if(typeof t==="string")return{dir:t,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:i};return{dir:t.dir,spa:t.spa??!1,pathRewriteStyle:t.pathRewriteStyle??"directory",maxAge:t.maxAge??0,cleanUrls:i}}var c0={".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 h0(t){let i=Ft.extname(t).toLowerCase();return c0[i]??"application/octet-stream"}function a0(t){let i;try{i=decodeURIComponent(t)}catch{return null}if(i.includes("\x00")||i.includes("\\"))return null;let r=Ft.posix.normalize(`/${i}`);if(r.includes(".."))return null;return r.replace(/^\/+/,"")}function o0(t,i){let r=a0(t);if(r===null)return null;let n=Ft.posix.extname(r);if(i.cleanUrls&&n===".html"){let e=t.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ft.join(i.dir,r),redirectTo:e||"/"}}if(r===""||t.endsWith("/"))return{filePath:Ft.join(i.dir,r,"index.html")};if(n!=="")return{filePath:Ft.join(i.dir,r)};if(i.pathRewriteStyle==="flat")return{filePath:Ft.join(i.dir,`${r}.html`)};return{filePath:Ft.join(i.dir,r,"index.html")}}async function da(t,i){let r=o0(t,i);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=i.maxAge>0?`public, max-age=${i.maxAge}`:"no-cache",e=Bun.file(r.filePath);if(await e.exists())return new Response(e,{status:200,headers:{"Content-Type":h0(r.filePath),"Cache-Control":n}});if(i.spa){let f=Ft.join(i.dir,"index.html"),s=Bun.file(f);if(await s.exists())return new Response(s,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var u0=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function y0(t){return(t.headers.get("host")||"").split(":")[0]}function Aa(t,i,r){let n=new URL(t.url),e=i.sourceHost??"",f=n.pathname,s=Ea(n.pathname,i.pathRewrites);if(s)e=s.targetHost,f=s.targetPath,$("request",`Path rewrite: ${n.pathname} → ${e}${f}`,r);return{targetHost:e,targetPath:f,search:n.search}}function Ta(t,i){return async(r,n)=>{let e=new URL(r.url),f=y0(r),s=t(f);if(!s)return $("request",`No route found for host: ${f}`,i),new Response(`No proxy configured for ${f}`,{status:404});if(s.static)return da(e.pathname,s.static);if(r.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!n||!s.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:o,targetPath:y,search:u}=Aa(r,s,i),m=`ws://${o}${y}${u}`,w={};for(let[T,Y]of r.headers)if(!u0.has(T.toLowerCase())&&T.toLowerCase()!=="host")w[T]=Y;w.host=o,w["x-forwarded-for"]="127.0.0.1",w["x-forwarded-proto"]="https",w["x-forwarded-host"]=f;let d={targetUrl:m,forwardHeaders:w};if(n.upgrade(r,{data:d})){$("ws",`upgraded ${f}${y} → ${m}`,i);return}return new Response("WebSocket upgrade failed",{status:400})}if(!s.sourceHost)return new Response(`No upstream configured for ${f}`,{status:502});let{targetHost:c,targetPath:l,search:h}=Aa(r,s,i),a=`http://${c}${l}${h}`;try{let o=new Headers(r.headers);if(o.set("host",c),s.changeOrigin)o.set("origin",`http://${s.sourceHost}`);o.set("x-forwarded-for","127.0.0.1"),o.set("x-forwarded-proto","https"),o.set("x-forwarded-host",f);let y=await fetch(a,{method:r.method,headers:o,body:r.body,redirect:"manual"});if(s.cleanUrls&&e.pathname.endsWith(".html")){let m=e.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let u=new Headers(y.headers);return new Response(y.body,{status:y.status,statusText:y.statusText,headers:u})}catch(o){return $("request",`Proxy error for ${f}: ${o}`,i),new Response(`Proxy Error: ${o}`,{status:502})}}}function Ca(t){let i=new WeakMap;return{open(r){let{targetUrl:n,forwardHeaders:e}=r.data,f;try{f=new WebSocket(n,{headers:e})}catch(c){$("ws",`failed to open upstream ${n}: ${c}`,t),r.close(1011,"upstream connect failed");return}f.binaryType="arraybuffer";let s={upstream:f,upstreamOpen:!1,pending:[]};i.set(r,s),f.addEventListener("open",()=>{s.upstreamOpen=!0;for(let c of s.pending)f.send(c);s.pending=[]}),f.addEventListener("message",(c)=>{r.send(c.data)}),f.addEventListener("close",(c)=>{try{r.close(c.code||1000,c.reason||"")}catch{}}),f.addEventListener("error",()=>{$("ws",`upstream error for ${n}`,t);try{r.close(1011,"upstream error")}catch{}})},message(r,n){let e=i.get(r);if(!e)return;let f=typeof n==="string"?n:new Uint8Array(n);if(e.upstreamOpen)e.upstream.send(f);else e.pending.push(f)},close(r,n,e){let f=i.get(r);if(!f)return;i.delete(r);try{f.upstream.close(n||1000,e||"")}catch{}}}}function ga(t){return t.startsWith("*.")}function w0(t,i){if(!ga(i))return!1;let r=i.slice(1);return t.length>r.length&&t.endsWith(r)}function Sa(t,i){let r=t.get(i);if(r!==void 0)return r;let n,e=-1;for(let[f,s]of t){if(!ga(f))continue;if(w0(i,f)){let c=f.length-1;if(c>e)e=c,n=s}}return n}import*as Ar from"node:fs/promises";import*as $s from"node:path";function $0(t){if(!t.endsWith(".crt"))return null;let i=t.slice(0,-4);if(i.length===0)return null;if(i.startsWith("_wildcard."))return`*.${i.slice(10)}`;return i}async function m0(t,i,r,n){try{let[e,f]=await Promise.all([Ar.readFile(i,"utf8"),Ar.readFile(r,"utf8")]);return{serverName:t,cert:e,key:f}}catch(e){return $("sni",`skipping ${t}: ${e.message}`,n),null}}async function Ba(t,i){let r=new Map;if(t.certsDir){let e=[];try{e=await Ar.readdir(t.certsDir)}catch(f){$("sni",`certsDir read failed (${t.certsDir}): ${f.message}`,i)}for(let f of e){let s=$0(f);if(!s)continue;let c=f.slice(0,-4);r.set(s,{certPath:$s.join(t.certsDir,f),keyPath:$s.join(t.certsDir,`${c}.key`)})}}if(t.domains)for(let[e,f]of Object.entries(t.domains))r.set(e,f);let n=[];for(let[e,f]of r){let s=await m0(e,f.certPath,f.keyPath,i);if(s)n.push(s)}return n}import*as wi from"node:fs/promises";import*as ms from"node:path";var d0=60000;function A0(t,i){if(!i||i.length===0)return!1;return i.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return t===n||t.endsWith(`.${n}`)})}function E0(t){if(!t||t.length>253)return!1;if(t.includes("/")||t.includes(":")||t.includes(" "))return!1;if(t.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(t)}class ds{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(t){this.config=t.config,this.certsDir=t.certsDir,this.onCertAdded=t.onCertAdded,this.http01Store=t.http01Store??an,this.issuer=t.issuer??tf,this.verbose=t.verbose??!1,this.negativeCacheMs=t.negativeCacheMs??d0;for(let i of t.initial??[])this.certs.set(i.serverName,i)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(t){return this.certs.has(t)}async isApproved(t){if(!E0(t))return!1;if(A0(t,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(t)}catch(i){return $("on-demand",`ask(${t}) threw: ${i.message}`,this.verbose),!1}return!1}async ensureCert(t){if(!this.config.enabled)return!1;if(this.certs.has(t))return!0;let i=this.inFlight.get(t);if(i)return i;let r=this.negativeCache.get(t);if(r!==void 0&&Date.now()<r)return $("on-demand",`${t} negatively cached for ${r-Date.now()}ms`,this.verbose),!1;let n=this.issue(t).finally(()=>{this.inFlight.delete(t)});return this.inFlight.set(t,n),n}async issue(t){if(this.certs.has(t))return!0;if(await this.loadFromDisk(t))return!0;if(!await this.isApproved(t))return $("on-demand",`refused issuance for ${t} (not approved)`,this.verbose),!1;try{$("on-demand",`issuing cert for ${t} (staging=${this.config.staging??!1})`,this.verbose);let i=await this.issuer({domains:[t],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(t,i.fullChainPem,i.keyPem);let r={serverName:t,cert:i.fullChainPem,key:i.keyPem};return this.certs.set(t,r),this.negativeCache.delete(t),$("on-demand",`issued + installed cert for ${t}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(i){return this.negativeCache.set(t,Date.now()+this.negativeCacheMs),$("on-demand",`issuance for ${t} failed: ${i.message}`,this.verbose),!1}}async loadFromDisk(t){let{certPath:i,keyPath:r}=this.pathsFor(t);try{let[n,e]=await Promise.all([wi.readFile(i,"utf8"),wi.readFile(r,"utf8")]),f={serverName:t,cert:n,key:e};return this.certs.set(t,f),$("on-demand",`adopted existing on-disk cert for ${t}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(t){return{certPath:ms.join(this.certsDir,`${t}.crt`),keyPath:ms.join(this.certsDir,`${t}.key`)}}async persist(t,i,r){await wi.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:e}=this.pathsFor(t);await Promise.all([wi.writeFile(n,i,"utf8"),wi.writeFile(e,r,{encoding:"utf8",mode:384})])}}import*as ee from"node:fs";import*as wt from"node:fs/promises";import{homedir as T0}from"node:os";import*as As from"node:path";import*as fe from"node:process";var C0=/^[a-zA-Z0-9._-]+$/;function Pi(){return As.join(T0(),".stacks","rpx","registry.d")}function Es(t){return typeof t==="string"&&t.length>0&&t.length<=128&&C0.test(t)}function Ts(t,i){if(!Es(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return As.join(t,`${i}.json`)}function zt(t){if(!Number.isInteger(t)||t<=0)return!1;try{return fe.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function Ra(t){if(!t||typeof t!=="object")return!1;let i=t,r=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0,n=typeof i.from==="string"&&i.from.length>0,e=typeof i.static==="string"||!!i.static&&typeof i.static==="object"&&typeof i.static.dir==="string";return typeof i.id==="string"&&Es(i.id)&&(n||e)&&typeof i.to==="string"&&i.to.length>0&&r&&typeof i.createdAt==="string"}async function g0(t){await wt.mkdir(t,{recursive:!0})}async function hT(t,i=Pi(),r){if(!Ra(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await g0(i);let n=Ts(i,t.id),e=`${n}.tmp.${fe.pid}.${Date.now()}`,f=JSON.stringify(t,null,2);try{await wt.writeFile(e,f,{encoding:"utf8",mode:420}),await wt.rename(e,n),$("registry",`wrote entry ${t.id} → ${n}`,r)}catch(s){throw await wt.unlink(e).catch(()=>{}),s}}async function S0(t,i=Pi(),r){let n=Ts(i,t);try{await wt.unlink(n),$("registry",`removed entry ${t}`,r)}catch(e){if(e.code!=="ENOENT")throw e}}async function B0(t,i=Pi(),r){let n=Ts(i,t);try{let e=await wt.readFile(n,"utf8"),f=JSON.parse(e);if(!Ra(f))return $("registry",`entry ${t} failed validation, removing`,r),await wt.unlink(n).catch(()=>{}),null;return f}catch(e){if(e.code==="ENOENT")return null;if(e instanceof SyntaxError)return $("registry",`entry ${t} has invalid JSON, removing`,r),await wt.unlink(n).catch(()=>{}),null;throw e}}async function Vi(t=Pi(),i){let r;try{r=await wt.readdir(t)}catch(e){if(e.code==="ENOENT")return[];throw e}let n=[];for(let e of r){if(!e.endsWith(".json"))continue;let f=e.slice(0,-5);if(!Es(f))continue;let s=await B0(f,t,i);if(s)n.push(s)}return n}async function Cs(t=Pi(),i){let r=await Vi(t,i),n=0;for(let e of r){if(e.pid===void 0)continue;if(!zt(e.pid))$("registry",`GC: pid ${e.pid} for ${e.id} is dead, removing`,i),await S0(e.id,t,i).catch(()=>{}),n++}return n}function Ya(t,i={}){let r=i.dir??Pi(),n=i.debounceMs??100,e=i.pollMs??Math.max(n*2,250),f=i.verbose;ee.mkdirSync(r,{recursive:!0});let s=null,c=!1,l=null,h=!1,a=(d)=>{return JSON.stringify(d.map((A)=>({id:A.id,from:A.from,to:A.to,pid:A.pid,pathRewrites:A.pathRewrites,cleanUrls:A.cleanUrls,changeOrigin:A.changeOrigin,static:A.static})).sort((A,T)=>A.id.localeCompare(T.id)))},o=()=>{if(s=null,c)return;Vi(r,f).then((d)=>{return l=a(d),t(d)}).catch((d)=>{$("registry",`watcher onChange failed: ${d}`,f)})},y=()=>{if(c)return;if(s)clearTimeout(s);s=setTimeout(o,n)},m=setInterval(()=>{if(c||h)return;h=!0,Vi(r,f).then((d)=>{if(a(d)!==l)y()}).catch((d)=>{$("registry",`watcher poll failed: ${d}`,f)}).finally(()=>{h=!1})},e),w=ee.watch(r,{persistent:!0},(d,A)=>{if(A&&/\.tmp\.\d+\.\d+$/.test(A))return;y()});return w.on("error",(d)=>{$("registry",`watcher error: ${d}`,f)}),y(),{close:()=>{if(c=!0,s)clearTimeout(s);clearInterval(m),w.close()}}}var R0=5000;function $t(){return Nt.join(Ss(),".stacks","rpx")}function se(t=$t()){return Nt.join(t,"daemon.pid")}async function vi(t=$t()){try{let i=await Gt.readFile(se(t),"utf8"),r=Number.parseInt(i.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Y0(t=$t()){let i=await vi(t);return i!==null&&zt(i)}async function U0(t=$t()){await Gt.mkdir(t,{recursive:!0});let i=se(t);while(!0){try{let n=await Gt.open(i,"wx");try{await n.write(`${N.pid}
|
|
155
|
-
`)}finally{await n.close()}return i}catch(n){if(n.code!=="EEXIST")throw n}let r=await vi(t);if(r!==null&&zt(r))throw Error(`rpx daemon already running (pid=${r})`);await Gt.unlink(i).catch(()=>{})}}async function Er(t=$t()){await Gt.unlink(
|
|
156
|
-
`),h.stdin.end();h.unref();let y=
|
|
157
|
-
`,"utf8")}async function
|
|
154
|
+
`,u=tt(us.tmpdir(),"rpx-trust.ps1");if(await b.writeFile(u,a),Vi(`powershell -ExecutionPolicy Bypass -File "${u}"`),t.verbose)H.success("Successfully added certificate to Windows trust store");h=!0}catch(a){if(t.verbose)H.warn(`Could not trust certificate: ${a}`)}else try{await Af(c,f.certificate,r),h=!0}catch(a){if(t.verbose)H.warn(`Could not add certificate to trust store: ${a}`)}if(yi={key:c.privateKey,cert:c.certificate,ca:f.certificate},t.verbose)H.success(`Certificate generated successfully for ${i.length} domain${i.length>1?"s":""}`);if(!h&&t.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function u0(){yi=null}async function ws(t){if(!t)return null;if(yi)return yi;let i=$s(t);try{let[r,n,e]=await Promise.all([b.access(i.keyPath).then(()=>!0).catch(()=>!1),b.access(i.certPath).then(()=>!0).catch(()=>!1),i.caCertPath?b.access(i.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!r||!n)return $("ssl",`Certificate files don't exist: key=${r}, cert=${n}, paths: ${i.keyPath}, ${i.certPath}`,t.verbose),null;let f="regenerateUntrustedCerts"in t,s=t.regenerateUntrustedCerts,c=f?s!==!1:!0;$("ssl",`Trust check: hasFlag=${f}, flagValue=${s}, shouldCheckTrust=${c}`,t.verbose);let l=i.basePath||tt(ne(),".stacks","ssl"),h=ys(l);if(!(c?await Aa(h.caCertPath,t):!0))return $("ssl","Root CA exists but is not trusted, will regenerate",t.verbose),null;let[u,y,o]=await Promise.all([b.readFile(i.keyPath,"utf8"),b.readFile(i.certPath,"utf8"),e&&i.caCertPath?b.readFile(i.caCertPath,"utf8"):Promise.resolve(void 0)]);if(o&&!o.includes("-----BEGIN CERTIFICATE-----"))return $("ssl","Invalid root CA certificate content, will regenerate",t.verbose),null;if(re(t))try{let{X509Certificate:m}=await import("node:crypto"),d=new m(y).subjectAltName||"",T=t.proxies.map((Y)=>Y.to).filter((Y)=>!d.includes(`DNS:${Y}`));if(T.length>0)return $("ssl",`Certificate missing SANs for: ${T.join(", ")}, will regenerate`,t.verbose),null}catch(m){$("ssl",`Could not verify cert SANs: ${m}`,t.verbose)}return $("ssl","Successfully loaded existing certificates",t.verbose),yi={key:u,cert:y,ca:o},yi}catch(r){return $("ssl",`Error checking existing certificates: ${r}`,t.verbose),null}}function $s(t,i){let r=os(t);$("ssl",`Primary domain: ${r}`,i);let n=ma(t),e=tt(ne(),".stacks","ssl");if(typeof t.https==="object"){let f=t.https.basePath&&t.https.basePath.trim()!==""?t.https.basePath:e,s={domain:r,hostCertCN:r,basePath:f,caCertPath:t.https.caCertPath||n.caCertPath,certPath:t.https.certPath||n.certPath,keyPath:t.https.keyPath||n.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:t.https.commonName||r,organizationName:t.https.organizationName||"Local Development",countryName:t.https.countryName||"US",stateName:t.https.stateName||"California",localityName:t.https.localityName||"Playa Vista",validityDays:t.https.validityDays||825,verbose:i||!1,subjectAltNames:Array.from(oa(t)).map((c)=>({type:2,value:c}))};if(ya(t.https.rootCA))s.rootCA=t.https.rootCA;return s}return{domain:r,hostCertCN:r,basePath:e,...n,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:r,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:i||!1,subjectAltNames:Array.from(oa(t)).map((f)=>({type:2,value:f}))}}async function QE(t,i){let r=ma({to:t,verbose:i}),n=[r.caCertPath,r.certPath,r.keyPath];$("certificates","Attempting to clean up relating certificates",i),await Promise.all(n.map((e)=>$a(e,i)))}async function Aa(t,i){try{if($("ssl",`Checking if certificate is trusted: ${t}`,i?.verbose),Mt.platform==="darwin"){if(i?.serverName)return mr(t,i.serverName,{verbose:i?.verbose});return dr(t,{verbose:i?.verbose})}else if(Mt.platform==="win32")try{let n=Vi(`openssl x509 -noout -subject -in "${t}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!n)return $("ssl","Could not extract certificate subject",i?.verbose),!1;let e=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${n}*' } | Select-Object Subject"`;if(Vi(e).toString().includes(n))return $("ssl","Certificate found in trusted root store",i?.verbose),!0;return $("ssl","Certificate not found in trusted root store",i?.verbose),!1}catch(r){return $("ssl",`Error checking certificate trust on Windows: ${r}`,i?.verbose),!1}else if(Mt.platform==="linux")try{let n=Vi(`openssl x509 -noout -fingerprint -sha256 -in "${t}"`).toString().trim().split("=")[1]?.trim()||"",e=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let f of e)try{if(Vi(`find ${f} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${n}"`).toString().includes(n))return $("ssl",`Certificate fingerprint found in ${f}`,i?.verbose),!0}catch{}return $("ssl","Certificate not found in system trust stores",i?.verbose),!1}catch(r){return $("ssl",`Error checking certificate trust on Linux: ${r}`,i?.verbose),!1}return $("ssl",`Platform ${Mt.platform} not supported for certificate trust check`,i?.verbose),!1}catch(r){return $("ssl",`Error checking if certificate is trusted: ${r}`,i?.verbose),!1}}import*as Nt from"node:path";function Ea(t,i){if(typeof t==="string")return{dir:t,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:i};return{dir:t.dir,spa:t.spa??!1,pathRewriteStyle:t.pathRewriteStyle??"directory",maxAge:t.maxAge??0,cleanUrls:i}}var o0={".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 y0(t){let i=Nt.extname(t).toLowerCase();return o0[i]??"application/octet-stream"}function w0(t){let i;try{i=decodeURIComponent(t)}catch{return null}if(i.includes("\x00")||i.includes("\\"))return null;let r=Nt.posix.normalize(`/${i}`);if(r.includes(".."))return null;return r.replace(/^\/+/,"")}function $0(t,i){let r=w0(t);if(r===null)return null;let n=Nt.posix.extname(r);if(i.cleanUrls&&n===".html"){let e=t.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Nt.join(i.dir,r),redirectTo:e||"/"}}if(r===""||t.endsWith("/"))return{filePath:Nt.join(i.dir,r,"index.html")};if(n!=="")return{filePath:Nt.join(i.dir,r)};if(i.pathRewriteStyle==="flat")return{filePath:Nt.join(i.dir,`${r}.html`)};return{filePath:Nt.join(i.dir,r,"index.html")}}async function Ta(t,i){let r=$0(t,i);if(!r)return new Response("Forbidden",{status:403});if(r.redirectTo)return new Response(null,{status:301,headers:{Location:r.redirectTo}});let n=i.maxAge>0?`public, max-age=${i.maxAge}`:"no-cache",e=Bun.file(r.filePath);if(await e.exists())return new Response(e,{status:200,headers:{"Content-Type":y0(r.filePath),"Cache-Control":n}});if(i.spa){let f=Nt.join(i.dir,"index.html"),s=Bun.file(f);if(await s.exists())return new Response(s,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var m0=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"]);function d0(t){return(t.headers.get("host")||"").split(":")[0]}function ga(t,i){if(!i||i==="/")return t;if(t===i)return"/";if(t.startsWith(`${i}/`)){let r=t.slice(i.length);return r===""?"/":r}return t}function Ca(t,i,r){let n=new URL(t.url),e=i.sourceHost??"",s=i.stripBasePathPrefix??!1?ga(n.pathname,i.basePath):n.pathname,c=Sa(s,i.pathRewrites);if(c)e=c.targetHost,s=c.targetPath,$("request",`Path rewrite: ${n.pathname} → ${e}${s}`,r);return{targetHost:e,targetPath:s,search:n.search}}function Ba(t,i){return async(r,n)=>{let e=new URL(r.url),f=d0(r),s=t(f,e.pathname);if(!s)return $("request",`No route found for host: ${f}`,i),new Response(`No proxy configured for ${f}`,{status:404});if(s.static){let y=s.stripBasePathPrefix??!0?ga(e.pathname,s.basePath):e.pathname;return Ta(y,s.static)}if(r.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!n||!s.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:u,targetPath:y,search:o}=Ca(r,s,i),m=`ws://${u}${y}${o}`,w={};for(let[T,Y]of r.headers)if(!m0.has(T.toLowerCase())&&T.toLowerCase()!=="host")w[T]=Y;w.host=u,w["x-forwarded-for"]="127.0.0.1",w["x-forwarded-proto"]="https",w["x-forwarded-host"]=f;let d={targetUrl:m,forwardHeaders:w};if(n.upgrade(r,{data:d})){$("ws",`upgraded ${f}${y} → ${m}`,i);return}return new Response("WebSocket upgrade failed",{status:400})}if(!s.sourceHost)return new Response(`No upstream configured for ${f}`,{status:502});let{targetHost:c,targetPath:l,search:h}=Ca(r,s,i),a=`http://${c}${l}${h}`;try{let u=new Headers(r.headers);if(u.set("host",c),s.changeOrigin)u.set("origin",`http://${s.sourceHost}`);u.set("x-forwarded-for","127.0.0.1"),u.set("x-forwarded-proto","https"),u.set("x-forwarded-host",f);let y=await fetch(a,{method:r.method,headers:u,body:r.body,redirect:"manual"});if(s.cleanUrls&&e.pathname.endsWith(".html")){let m=e.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:m}})}let o=new Headers(y.headers);return new Response(y.body,{status:y.status,statusText:y.statusText,headers:o})}catch(u){return $("request",`Proxy error for ${f}: ${u}`,i),new Response(`Proxy Error: ${u}`,{status:502})}}}function Ra(t){let i=new WeakMap;return{open(r){let{targetUrl:n,forwardHeaders:e}=r.data,f;try{f=new WebSocket(n,{headers:e})}catch(c){$("ws",`failed to open upstream ${n}: ${c}`,t),r.close(1011,"upstream connect failed");return}f.binaryType="arraybuffer";let s={upstream:f,upstreamOpen:!1,pending:[]};i.set(r,s),f.addEventListener("open",()=>{s.upstreamOpen=!0;for(let c of s.pending)f.send(c);s.pending=[]}),f.addEventListener("message",(c)=>{r.send(c.data)}),f.addEventListener("close",(c)=>{try{r.close(c.code||1000,c.reason||"")}catch{}}),f.addEventListener("error",()=>{$("ws",`upstream error for ${n}`,t);try{r.close(1011,"upstream error")}catch{}})},message(r,n){let e=i.get(r);if(!e)return;let f=typeof n==="string"?n:new Uint8Array(n);if(e.upstreamOpen)e.upstream.send(f);else e.pending.push(f)},close(r,n,e){let f=i.get(r);if(!f)return;i.delete(r);try{f.upstream.close(n||1000,e||"")}catch{}}}}function ee(t){return t.startsWith("*.")}function ms(t,i){if(!ee(i))return!1;let r=i.slice(1);return t.length>r.length&&t.endsWith(r)}function sT(t,i){let r=t.get(i);if(r!==void 0)return r;let n,e=-1;for(let[f,s]of t){if(!ee(f))continue;if(ms(i,f)){let c=f.length-1;if(c>e)e=c,n=s}}return n}function ds(t){if(!t||t==="/")return"/";let i=t.trim();if(!i.startsWith("/"))i=`/${i}`;return i=i.replace(/\/+$/,""),i===""?"/":i}function A0(t,i){if(i==="/")return!0;if(t===i)return!0;return t.startsWith(`${i}/`)}function Ya(t){let i=new Map;for(let n of t){let e=ds(n.path),f=i.get(n.host);if(!f)f=new Map,i.set(n.host,f);f.set(e,n.route)}let r=new Map;for(let[n,e]of i){let f=[];for(let[s,c]of e)f.push({path:s,route:c});f.sort((s,c)=>c.path.length-s.path.length),r.set(n,f)}return r}function E0(t,i){let r=t.get(i);if(r!==void 0)return r;let n,e=-1;for(let[f,s]of t){if(!ee(f))continue;if(ms(i,f)){let c=f.length-1;if(c>e)e=c,n=s}}return n}function Ua(t,i,r){let n=E0(t,i);if(!n)return;for(let e of n)if(A0(r,e.path))return e.route;return}import*as Ar from"node:fs/promises";import*as As from"node:path";function T0(t){if(!t.endsWith(".crt"))return null;let i=t.slice(0,-4);if(i.length===0)return null;if(i.startsWith("_wildcard."))return`*.${i.slice(10)}`;return i}async function C0(t,i,r,n){try{let[e,f]=await Promise.all([Ar.readFile(i,"utf8"),Ar.readFile(r,"utf8")]);return{serverName:t,cert:e,key:f}}catch(e){return $("sni",`skipping ${t}: ${e.message}`,n),null}}async function Fa(t,i){let r=new Map;if(t.certsDir){let e=[];try{e=await Ar.readdir(t.certsDir)}catch(f){$("sni",`certsDir read failed (${t.certsDir}): ${f.message}`,i)}for(let f of e){let s=T0(f);if(!s)continue;let c=f.slice(0,-4);r.set(s,{certPath:As.join(t.certsDir,f),keyPath:As.join(t.certsDir,`${c}.key`)})}}if(t.domains)for(let[e,f]of Object.entries(t.domains))r.set(e,f);let n=[];for(let[e,f]of r){let s=await C0(e,f.certPath,f.keyPath,i);if(s)n.push(s)}return n}import*as wi from"node:fs/promises";import*as Es from"node:path";var S0=60000;function g0(t,i){if(!i||i.length===0)return!1;return i.some((r)=>{let n=r.startsWith(".")?r.slice(1):r;return t===n||t.endsWith(`.${n}`)})}function B0(t){if(!t||t.length>253)return!1;if(t.includes("/")||t.includes(":")||t.includes(" "))return!1;if(t.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(t)}class Ts{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor(t){this.config=t.config,this.certsDir=t.certsDir,this.onCertAdded=t.onCertAdded,this.http01Store=t.http01Store??an,this.issuer=t.issuer??rf,this.verbose=t.verbose??!1,this.negativeCacheMs=t.negativeCacheMs??S0;for(let i of t.initial??[])this.certs.set(i.serverName,i)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(t){return this.certs.has(t)}async isApproved(t){if(!B0(t))return!1;if(g0(t,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(t)}catch(i){return $("on-demand",`ask(${t}) threw: ${i.message}`,this.verbose),!1}return!1}async ensureCert(t){if(!this.config.enabled)return!1;if(this.certs.has(t))return!0;let i=this.inFlight.get(t);if(i)return i;let r=this.negativeCache.get(t);if(r!==void 0&&Date.now()<r)return $("on-demand",`${t} negatively cached for ${r-Date.now()}ms`,this.verbose),!1;let n=this.issue(t).finally(()=>{this.inFlight.delete(t)});return this.inFlight.set(t,n),n}async issue(t){if(this.certs.has(t))return!0;if(await this.loadFromDisk(t))return!0;if(!await this.isApproved(t))return $("on-demand",`refused issuance for ${t} (not approved)`,this.verbose),!1;try{$("on-demand",`issuing cert for ${t} (staging=${this.config.staging??!1})`,this.verbose);let i=await this.issuer({domains:[t],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist(t,i.fullChainPem,i.keyPem);let r={serverName:t,cert:i.fullChainPem,key:i.keyPem};return this.certs.set(t,r),this.negativeCache.delete(t),$("on-demand",`issued + installed cert for ${t}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(i){return this.negativeCache.set(t,Date.now()+this.negativeCacheMs),$("on-demand",`issuance for ${t} failed: ${i.message}`,this.verbose),!1}}async loadFromDisk(t){let{certPath:i,keyPath:r}=this.pathsFor(t);try{let[n,e]=await Promise.all([wi.readFile(i,"utf8"),wi.readFile(r,"utf8")]),f={serverName:t,cert:n,key:e};return this.certs.set(t,f),$("on-demand",`adopted existing on-disk cert for ${t}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(t){return{certPath:Es.join(this.certsDir,`${t}.crt`),keyPath:Es.join(this.certsDir,`${t}.key`)}}async persist(t,i,r){await wi.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:n,keyPath:e}=this.pathsFor(t);await Promise.all([wi.writeFile(n,i,"utf8"),wi.writeFile(e,r,{encoding:"utf8",mode:384})])}}import*as fe from"node:fs";import*as wt from"node:fs/promises";import{homedir as R0}from"node:os";import*as Cs from"node:path";import*as se from"node:process";var Y0=/^[a-zA-Z0-9._-]+$/;function Pi(){return Cs.join(R0(),".stacks","rpx","registry.d")}function Ss(t){return typeof t==="string"&&t.length>0&&t.length<=128&&Y0.test(t)}function gs(t,i){if(!Ss(i))throw Error(`invalid registry id: ${JSON.stringify(i)}`);return Cs.join(t,`${i}.json`)}function zt(t){if(!Number.isInteger(t)||t<=0)return!1;try{return se.kill(t,0),!0}catch(i){return i.code==="EPERM"}}function Na(t){if(!t||typeof t!=="object")return!1;let i=t,r=i.pid===void 0||typeof i.pid==="number"&&Number.isInteger(i.pid)&&i.pid>0,n=typeof i.from==="string"&&i.from.length>0,e=typeof i.static==="string"||!!i.static&&typeof i.static==="object"&&typeof i.static.dir==="string",f=i.path===void 0||typeof i.path==="string";return typeof i.id==="string"&&Ss(i.id)&&(n||e)&&typeof i.to==="string"&&i.to.length>0&&f&&r&&typeof i.createdAt==="string"}async function U0(t){await wt.mkdir(t,{recursive:!0})}async function dT(t,i=Pi(),r){if(!Na(t))throw Error(`invalid registry entry: ${JSON.stringify(t)}`);await U0(i);let n=gs(i,t.id),e=`${n}.tmp.${se.pid}.${Date.now()}`,f=JSON.stringify(t,null,2);try{await wt.writeFile(e,f,{encoding:"utf8",mode:420}),await wt.rename(e,n),$("registry",`wrote entry ${t.id} → ${n}`,r)}catch(s){throw await wt.unlink(e).catch(()=>{}),s}}async function F0(t,i=Pi(),r){let n=gs(i,t);try{await wt.unlink(n),$("registry",`removed entry ${t}`,r)}catch(e){if(e.code!=="ENOENT")throw e}}async function N0(t,i=Pi(),r){let n=gs(i,t);try{let e=await wt.readFile(n,"utf8"),f=JSON.parse(e);if(!Na(f))return $("registry",`entry ${t} failed validation, removing`,r),await wt.unlink(n).catch(()=>{}),null;return f}catch(e){if(e.code==="ENOENT")return null;if(e instanceof SyntaxError)return $("registry",`entry ${t} has invalid JSON, removing`,r),await wt.unlink(n).catch(()=>{}),null;throw e}}async function pi(t=Pi(),i){let r;try{r=await wt.readdir(t)}catch(e){if(e.code==="ENOENT")return[];throw e}let n=[];for(let e of r){if(!e.endsWith(".json"))continue;let f=e.slice(0,-5);if(!Ss(f))continue;let s=await N0(f,t,i);if(s)n.push(s)}return n}async function Bs(t=Pi(),i){let r=await pi(t,i),n=0;for(let e of r){if(e.pid===void 0)continue;if(!zt(e.pid))$("registry",`GC: pid ${e.pid} for ${e.id} is dead, removing`,i),await F0(e.id,t,i).catch(()=>{}),n++}return n}function ja(t,i={}){let r=i.dir??Pi(),n=i.debounceMs??100,e=i.pollMs??Math.max(n*2,250),f=i.verbose;fe.mkdirSync(r,{recursive:!0});let s=null,c=!1,l=null,h=!1,a=(d)=>{return JSON.stringify(d.map((A)=>({id:A.id,from:A.from,to:A.to,path:A.path,pid:A.pid,pathRewrites:A.pathRewrites,cleanUrls:A.cleanUrls,changeOrigin:A.changeOrigin,static:A.static})).sort((A,T)=>A.id.localeCompare(T.id)))},u=()=>{if(s=null,c)return;pi(r,f).then((d)=>{return l=a(d),t(d)}).catch((d)=>{$("registry",`watcher onChange failed: ${d}`,f)})},y=()=>{if(c)return;if(s)clearTimeout(s);s=setTimeout(u,n)},m=setInterval(()=>{if(c||h)return;h=!0,pi(r,f).then((d)=>{if(a(d)!==l)y()}).catch((d)=>{$("registry",`watcher poll failed: ${d}`,f)}).finally(()=>{h=!1})},e),w=fe.watch(r,{persistent:!0},(d,A)=>{if(A&&/\.tmp\.\d+\.\d+$/.test(A))return;y()});return w.on("error",(d)=>{$("registry",`watcher error: ${d}`,f)}),y(),{close:()=>{if(c=!0,s)clearTimeout(s);clearInterval(m),w.close()}}}var j0=5000;function $t(){return jt.join(Ys(),".stacks","rpx")}function le(t=$t()){return jt.join(t,"daemon.pid")}async function vi(t=$t()){try{let i=await Gt.readFile(le(t),"utf8"),r=Number.parseInt(i.trim(),10);if(!Number.isFinite(r)||r<=0)return null;return r}catch(i){if(i.code==="ENOENT")return null;throw i}}async function W0(t=$t()){let i=await vi(t);return i!==null&&zt(i)}async function X0(t=$t()){await Gt.mkdir(t,{recursive:!0});let i=le(t);while(!0){try{let n=await Gt.open(i,"wx");try{await n.write(`${N.pid}
|
|
155
|
+
`)}finally{await n.close()}return i}catch(n){if(n.code!=="EEXIST")throw n}let r=await vi(t);if(r!==null&&zt(r))throw Error(`rpx daemon already running (pid=${r})`);await Gt.unlink(i).catch(()=>{})}}async function Er(t=$t()){await Gt.unlink(le(t)).catch(()=>{})}function _0(t){let i=t.cleanUrls??!1,r=ds(t.path);if(t.static)return{static:Ea(t.static,i),cleanUrls:i,basePath:r};let n=t.from??"localhost:1";return{sourceHost:new URL(n.startsWith("http")?n:`http://${n}`).host,cleanUrls:i,changeOrigin:t.changeOrigin??!1,pathRewrites:t.pathRewrites,basePath:r}}function I0(t){return t.find((r)=>!/^api\./.test(r)&&!/^docs\./.test(r)&&!/^dashboard\./.test(r))??t[0]??"rpx.localhost"}async function J0(t,i){let r=await pi(i,t.verbose),n=[...new Set(r.map((a)=>a.to))],e=I0(n),f=[...new Set([e,...n,"rpx.localhost"])],s=jt.join(Ys(),".stacks","ssl"),c=jt.join(s,"rpx.localhost.crt"),l={https:typeof t.https==="object"?{...t.https,certPath:c,keyPath:jt.join(s,"rpx.localhost.key"),commonName:e}:{certPath:c,keyPath:jt.join(s,"rpx.localhost.key"),caCertPath:jt.join(s,"rpx.localhost.ca.crt"),commonName:e},verbose:t.verbose,regenerateUntrustedCerts:!0,...f.length>1?{proxies:f.map((a)=>({from:"localhost:1",to:a}))}:{to:e,from:"localhost:1"}},h=await ws(l);if(!h)$("daemon","no usable cert on disk, generating one",t.verbose),await da(l),h=await ws(l);if(!h)throw Error("failed to bootstrap TLS for rpx daemon");return h}async function O0(t,i,r,n){let e=N.env.SUDO_PASSWORD,f=N.env.HOME??Ys(),s=[N.execPath,...N.argv.slice(1)],c=[`HOME=${f}`,`PATH=${N.env.PATH??""}`];if(n)c.push("RPX_VERBOSE=1");let l=e?["-S","-p","","env",...c,...s]:["-n","env",...c,...s];$("daemon",`elevating daemon via sudo for privileged ports ${i}/${r}`,n);let h=Wa("sudo",l,{detached:!0,stdio:["pipe","ignore","ignore"]}),a=null,u=null;if(h.once("error",(m)=>{a=m}),h.once("exit",(m)=>{u=m??0}),e&&h.stdin)h.stdin.write(`${e}
|
|
156
|
+
`),h.stdin.end();h.unref();let y=le(t),o=Date.now()+15000;while(Date.now()<o){if(a)throw a;let m=await vi(t);if(m!==null&&zt(m)){if(n)H.success(`rpx daemon elevated to root (pid=${m}, https on :${i})`);return{httpsPort:i,httpPort:r,pidPath:y,done:Promise.resolve(),stop:async()=>{try{N.kill(m,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if(u!==null&&u!==0)throw Error(`rpx daemon could not elevate to bind :${i} (sudo exited ${u}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((w)=>setTimeout(w,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${t})`)}async function XT(t={}){let i=t.verbose??!1,r=t.rpxDir??$t(),n=t.registryDir??jt.join(r,"registry.d"),e=t.httpsPort??443,f=t.httpPort??80,s=t.hostname??"0.0.0.0",c=t.gcIntervalMs??j0,l=e>0&&e<1024||f>0&&f<1024,h=typeof N.getuid==="function"&&N.getuid()===0;if(N.platform!=="win32"&&l&&!h)return O0(r,e,f,i);let a=await X0(r),u=new Map,y=(S,L)=>Ua(u,S,L);function o(S){u=Ya(S.map((Ct)=>({host:Ct.to,path:Ct.path,route:_0(Ct)})));let L=Array.from(u.keys());$("daemon",`routing table now covers ${L.length} host(s): ${L.join(", ")||"<empty>"}`,i)}await Bs(n,i).catch((S)=>{$("daemon",`initial gc failed: ${S}`,i)});let m=await pi(n,i);o(m),await Cr({rpxDir:r,verbose:i}).catch((S)=>{$("daemon",`DNS reconcile on start failed: ${S}`,i)}),await Rs(m,{rpxDir:r,verbose:i,ownerPid:N.pid}).catch((S)=>{$("daemon",`DNS setup on start failed: ${S}`,i)});let w=[];if(t.productionCerts){if(w=await Fa(t.productionCerts,i),i&&w.length>0)H.info(`SNI: serving ${w.length} real cert(s): ${w.map((S)=>S.serverName).join(", ")}`)}let d=Ba(y,i),A=Ra(i),T=null;if(w.length===0)T=await J0(t,n);let Y=t.onDemandTls,g=Y?.enabled?new Ts({config:Y,certsDir:Y.certsDir??t.productionCerts?.certsDir??jt.join(r,"on-demand-certs"),initial:w,verbose:i,onCertAdded:(S)=>{Qi(S)}}):null;function X(S){if(S.length>0)return S.map((L)=>({serverName:L.serverName,cert:L.cert,key:L.key}));return{key:T.key,cert:T.cert,ca:T.ca,requestCert:!1,rejectUnauthorized:!1}}function xt(S){return Bun.serve({port:e,hostname:s,tls:X(S),fetch(L,Ct){return d(L,Ct)},websocket:A,error(L){return $("daemon",`https server error: ${L}`,i),new Response(`Server Error: ${L.message}`,{status:500})}})}let Wt=xt(g?g.sniEntries():w);async function Qi(S){if(gr)return;$("daemon",`rebuilding :443 with ${S.length} SNI cert(s)`,i),Wt.stop(!1);let L;for(let Ct=0;Ct<20&&!gr;Ct++)try{Wt=xt(S);return}catch(Br){L=Br,await new Promise((qa)=>setTimeout(qa,25))}H.error(`rpx: failed to rebuild :443 after issuing cert: ${L?.message}`)}let Lt=null;if(f>0)Lt=Bun.serve({port:f,hostname:s,fetch(S){let L=new URL(S.url),Ct=(S.headers.get("host")??L.hostname).split(":")[0];if(g&&L.pathname.startsWith("/.well-known/acme-challenge/")){let Br=g.challengeStore.handlePath(L.pathname);if(Br!==void 0)return new Response(Br,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(g&&!g.hasCert(Ct))g.ensureCert(Ct).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${Ct}${L.pathname}${L.search}`}})}});if(i)H.success(`rpx daemon listening on https://${s}:${e}${Lt?` (http→https on :${f})`:""}`),H.info(`pid file: ${a}`),H.info(`registry: ${n}`);let xa=ja((S)=>{o(S),Rs(S,{rpxDir:r,verbose:i,ownerPid:N.pid}).catch((L)=>{$("daemon",`DNS sync on registry change failed: ${L}`,i)})},{dir:n,verbose:i}),oe=setInterval(()=>{Bs(n,i).then((S)=>{if(S>0)$("daemon",`gc reaped ${S} stale entries`,i)}).catch((S)=>{$("daemon",`periodic gc failed: ${S}`,i)})},c);if(typeof oe.unref==="function")oe.unref();let gr=!1,Js,ye=new Promise((S)=>{Js=S});async function Os(){if(gr)return ye;if(gr=!0,clearInterval(oe),xa.close(),Wt.stop(!1),Lt?.stop(!1),await Tr({rpxDir:r,verbose:i}).catch((S)=>{$("daemon",`DNS teardown failed: ${S}`,i)}),await Er(r),i)H.info("rpx daemon stopped");return Js(),ye}let Ks=(S)=>{$("daemon",`received ${S}, shutting down`,i),Os().catch(()=>{})};return N.once("SIGINT",Ks),N.once("SIGTERM",Ks),{stop:Os,done:ye,httpsPort:typeof Wt.port==="number"?Wt.port:e,httpPort:Lt&&typeof Lt.port==="number"?Lt.port:f,pidPath:a,ensureCert:(S)=>g?g.ensureCert(S):Promise.resolve(!1)}}function K0(){let t=N.execPath,i=jt.basename(t).toLowerCase();if((i==="bun"||i==="node"||i.startsWith("bun-"))&&N.argv[1])return[t,N.argv[1],"daemon:start"];return[t,"daemon:start"]}async function _T(t={}){let i=t.rpxDir??$t(),r=t.verbose??!1;await Cr({rpxDir:i,verbose:r}).catch((a)=>{$("daemon",`DNS reconcile before ensureDaemonRunning: ${a}`,r)});let n=await vi(i);if(n!==null&&zt(n))return $("daemon",`ensureDaemonRunning: already running pid=${n}`,r),{pid:n,spawned:!1};if(n!==null)$("daemon",`ensureDaemonRunning: clearing stale pid=${n}`,r),await Er(i);await Gt.mkdir(i,{recursive:!0});let e=t.spawnCommand??K0();if(e.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");$("daemon",`spawning daemon: ${e.join(" ")}`,r);let f=Wa(e[0],e.slice(1),{detached:!0,stdio:"ignore",cwd:t.spawnCwd??N.cwd(),env:t.spawnEnv?{...N.env,...t.spawnEnv}:N.env});f.unref();let s=null;f.once("error",(a)=>{s=a});let c=t.startupTimeoutMs??5000,l=t.pollIntervalMs??50,h=Date.now()+c;while(Date.now()<h){if(s)throw s;let a=await vi(i);if(a!==null&&zt(a))return $("daemon",`daemon registered with pid=${a}`,r),{pid:a,spawned:!0};await new Promise((u)=>setTimeout(u,l))}if(s)throw s;throw Error(`rpx daemon failed to start within ${c}ms (rpxDir=${i})`)}async function IT(t={}){let i=t.rpxDir??$t(),r=t.verbose??!1,n=t.timeoutMs??5000,e=t.pollIntervalMs??50,f=t.forceAfterTimeout??!0,s=await vi(i);if(s===null||!zt(s)){if(s!==null)await Er(i);return await Cr({rpxDir:i,verbose:r}).catch(()=>{}),{stopped:!1,pid:s,forced:!1}}try{N.kill(s,"SIGTERM")}catch(l){if(l.code==="ESRCH")return await Er(i),{stopped:!1,pid:s,forced:!1};throw l}let c=Date.now()+n;while(Date.now()<c){if(!zt(s))return $("daemon",`daemon pid=${s} stopped cleanly`,r),{stopped:!0,pid:s,forced:!1};await new Promise((l)=>setTimeout(l,e))}if(!f)throw Error(`rpx daemon (pid=${s}) did not exit within ${n}ms`);$("daemon",`daemon pid=${s} did not exit, escalating to SIGKILL`,r);try{N.kill(s,"SIGKILL")}catch(l){if(l.code!=="ESRCH")throw l}return await Er(i),await Tr({rpxDir:i,verbose:r}).catch((l)=>{$("daemon",`DNS teardown after SIGKILL: ${l}`,r)}),{stopped:!0,pid:s,forced:!0}}async function JT(t={}){let i=t.rpxDir??$t();if(await W0(i))return;await Cr({rpxDir:i,verbose:t.verbose})}import*as $i from"node:fs/promises";import{homedir as H0}from"node:os";import*as Us from"node:path";var ce=1,M0="dns-state.json",Xa=["com","test","dev","app","page","local","localhost","example","invalid"];function _a(){return Us.join(H0(),".stacks","rpx")}function Fs(t=_a()){return Us.join(t,M0)}async function he(t=_a()){try{let i=await $i.readFile(Fs(t),"utf8"),r=JSON.parse(i);if(r.version!==ce||!Array.isArray(r.resolvers))return null;return{version:ce,resolvers:r.resolvers.filter((n)=>typeof n==="string"),domains:Array.isArray(r.domains)?r.domains.filter((n)=>typeof n==="string"):[],ownerPid:typeof r.ownerPid==="number"?r.ownerPid:null,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:""}}catch(i){if(i.code==="ENOENT")return null;throw i}}async function Ia(t,i){await $i.mkdir(t,{recursive:!0}),await $i.writeFile(Fs(t),`${JSON.stringify(i,null,2)}
|
|
157
|
+
`,"utf8")}async function Ns(t){await $i.rm(Fs(t),{force:!0})}function Ja(t){let i=t.trim().toLowerCase().replace(/\.$/,"");if(!i||i.includes("127.0.0.1"))return null;if(i==="localhost"||i.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(i))return null;return i}function z0(t){let i=Ja(t);if(!i)return null;let r=i.split(".");if(r.length<2)return null;return r.slice(-2).join(".")}function js(t){let i=new Set;for(let r of t){let n=z0(r);if(n)i.add(n)}return Array.from(i).sort()}function Ws(t){let i=new Set;for(let r of t){let n=Ja(r);if(n)i.add(n)}return Array.from(i).sort()}var Xs=15353,G0="# managed-by: rpx",Ha="/etc/resolver",mt=null,ae=new Set;function x0(t){return{id:t.readUInt16BE(0),flags:t.readUInt16BE(2),qdcount:t.readUInt16BE(4),ancount:t.readUInt16BE(6),nscount:t.readUInt16BE(8),arcount:t.readUInt16BE(10)}}function Ma(t,i){let r=[],n=i;while(!0){let e=t[n];if(e===0){n++;break}if((e&192)===192){let f=t.readUInt16BE(n)&16383,{name:s}=Ma(t,f);r.push(s),n+=2;break}n++,r.push(t.subarray(n,n+e).toString("ascii")),n+=e}return{name:r.join("."),newOffset:n}}function q0(t,i){let{name:r,newOffset:n}=Ma(t,i),e=t.readUInt16BE(n),f=t.readUInt16BE(n+2);return{question:{name:r,type:e,class:f},newOffset:n+4}}function ue(t){let i=t.split("."),r=[];for(let n of i)r.push(Buffer.from([n.length])),r.push(Buffer.from(n,"ascii"));return r.push(Buffer.from([0])),Buffer.concat(r)}function k0(t,i,r){let n=[],e=Buffer.alloc(12);e.writeUInt16BE(t,0),e.writeUInt16BE(33152,2),e.writeUInt16BE(1,4),e.writeUInt16BE(1,6),e.writeUInt16BE(0,8),e.writeUInt16BE(0,10),n.push(e),n.push(ue(i.name));let f=Buffer.alloc(4);f.writeUInt16BE(i.type,0),f.writeUInt16BE(i.class,2),n.push(f),n.push(ue(i.name));let s=Buffer.alloc(10);if(s.writeUInt16BE(i.type,0),s.writeUInt16BE(1,2),s.writeUInt32BE(300,4),i.type===1){s.writeUInt16BE(4,8),n.push(s);let c=r.split(".").map((l)=>Number.parseInt(l,10));n.push(Buffer.from(c))}else if(i.type===28)s.writeUInt16BE(16,8),n.push(s),n.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return e.writeUInt16BE(33155,2),e.writeUInt16BE(0,6),Buffer.concat([e,ue(i.name),f]);return Buffer.concat(n)}function D0(t,i){let r=[],n=Buffer.alloc(12);n.writeUInt16BE(t,0),n.writeUInt16BE(33155,2),n.writeUInt16BE(1,4),n.writeUInt16BE(0,6),n.writeUInt16BE(0,8),n.writeUInt16BE(0,10),r.push(n),r.push(ue(i.name));let e=Buffer.alloc(4);return e.writeUInt16BE(i.type,0),e.writeUInt16BE(i.class,2),r.push(e),Buffer.concat(r)}async function b0(t,i){if(fi.platform!=="darwin")return!1;let r=Ws(t);if(r.length===0)return!1;if(mt){for(let n of r)ae.add(n);return $("dns","DNS server already running — merged domains",i),!0}return ae=new Set(r),new Promise((n)=>{mt=L0.createSocket("udp4"),mt.on("error",(e)=>{$("dns",`DNS server error: ${e.message}`,i),mt?.close(),mt=null,n(!1)}),mt.on("message",(e,f)=>{try{let s=x0(e),{question:c}=q0(e,12);$("dns",`Query for ${c.name} type ${c.type} from ${f.address}`,i);let l=c.name.toLowerCase(),h=!1;for(let u of ae)if(l===u||l.endsWith(`.${u}`)){h=!0;break}let a;if(h&&(c.type===1||c.type===28))a=k0(s.id,c,"127.0.0.1"),$("dns",`Responding with localhost for ${c.name}`,i);else a=D0(s.id,c),$("dns",`NXDOMAIN for ${c.name}`,i);mt?.send(a,f.port,f.address)}catch(s){$("dns",`Error processing DNS query: ${s}`,i)}}),mt.on("listening",()=>{let e=mt?.address();$("dns",`DNS server listening on ${e?.address}:${e?.port}`,i),n(!0)});try{mt.bind(Xs,"127.0.0.1")}catch(e){$("dns",`Failed to bind DNS server: ${e}`,i),n(!1)}})}function za(t){if(mt)$("dns","Stopping DNS server",t),mt.close(),mt=null,ae=new Set}function qT(){return mt!==null}function V0(){return`${G0}
|
|
158
158
|
nameserver 127.0.0.1
|
|
159
|
-
port ${
|
|
160
|
-
`}function
|
|
161
|
-
export{
|
|
159
|
+
port ${Xs}
|
|
160
|
+
`}function Sr(t){return Ka.join(Ha,t)}function p0(t){return t.includes("127.0.0.1")&&t.includes(String(Xs))}async function P0(t){try{return await Oa.readFile(Sr(t),"utf8")}catch(i){if(i.code==="ENOENT")return null;throw i}}async function _s(t){if(fi.platform!=="darwin")return;let{execSudoSync:i,getSudoPassword:r}=await import("./chunk-a0b9f9fs.js");if(!r()){$("dns","Cannot flush DNS cache without SUDO_PASSWORD",t);return}try{i("dscacheutil -flushcache"),i("killall -HUP mDNSResponder 2>/dev/null || true"),$("dns","DNS cache flushed",t)}catch(n){$("dns",`Could not flush DNS cache: ${n}`,t)}}async function v0(t,i){let{execSudoSync:r}=await import("./chunk-a0b9f9fs.js"),n=V0().replace(/\n/g,"\\n"),e=`bash -c 'mkdir -p ${Ha} && printf "%b" "${n}" > ${Sr(t)}'`;r(e),$("dns",`Created ${Sr(t)}`,i)}async function Q0(t,i){let{execSudoSync:r}=await import("./chunk-a0b9f9fs.js");r(`rm -f ${Sr(t)}`),$("dns",`Removed ${Sr(t)}`,i)}async function kT(t,i){return Ga({domains:i??[],verbose:t})}async function Z0(t,i){if(fi.platform!=="darwin")return!0;let{getSudoPassword:r}=await import("./chunk-a0b9f9fs.js");if(!r())return $("dns","SUDO_PASSWORD not set, cannot create resolver files",i),!1;try{for(let n of t)await v0(n,i);return await _s(i),!0}catch(n){return $("dns",`Failed to create resolver file: ${n}`,i),!1}}async function Is(t,i){if(fi.platform!=="darwin")return;let{getSudoPassword:r}=await import("./chunk-a0b9f9fs.js");if(!r())return;try{for(let n of t)await Q0(n,i);await _s(i)}catch(n){$("dns",`Failed to remove resolver files: ${n}`,i)}}async function La(t){if(fi.platform!=="darwin")return[];let i=[];for(let r of Xa){let n=await P0(r);if(n&&p0(n))await Is([r],t),i.push(r)}return i}async function Ga(t){let i=t.rpxDir??$t(),r=Ws(t.domains);if(r.length===0)return!1;let n=js(r);if(!await b0(r,t.verbose))return!1;if(!await Z0(n,t.verbose))return!1;let s={version:ce,resolvers:n,domains:r,ownerPid:t.ownerPid??fi.pid,updatedAt:new Date().toISOString()};return await Ia(i,s),!0}async function Rs(t,i={}){let r=t.map((l)=>l.to).filter(Boolean),n=i.rpxDir??$t(),e=js(r),c=((await he(n))?.resolvers??[]).filter((l)=>!e.includes(l));if(c.length>0)await Is(c,i.verbose);if(e.length===0){za(i.verbose),await Ns(n);return}await Ga({domains:r,rpxDir:n,verbose:i.verbose,ownerPid:i.ownerPid??fi.pid})}async function Tr(t={}){let i=t.rpxDir??$t();za(t.verbose);let n=(await he(i))?.resolvers??[];await Is(n,t.verbose),await La(t.verbose),await Ns(i)}async function DT(t){await Tr({verbose:t})}async function Cr(t={}){let i=t.rpxDir??$t(),r=await he(i),n=r?.ownerPid!=null&&zt(r.ownerPid);if(r&&!n){$("dns",`reconcile: owner pid ${r.ownerPid} is gone — tearing down DNS`,t.verbose),await Tr(t);return}let e=await La(t.verbose);if(e.length>0)$("dns",`reconcile: removed legacy TLD resolvers: ${e.join(", ")}`,t.verbose);await _s(t.verbose)}
|
|
161
|
+
export{H as a,ca as b,ha as c,te as d,i0 as e,r0 as f,n0 as g,e0 as h,oi as i,Ei as j,cs as k,$r as l,hs as m,aa as n,ie as o,mr as p,dr as q,as as r,ys as s,pE as t,PE as u,vE as v,da as w,u0 as x,ws as y,$s as z,QE as A,Aa as B,Ea as C,y0 as D,w0 as E,$0 as F,Ta as G,ga as H,Ba as I,Ra as J,ee as K,ms as L,sT as M,ds as N,A0 as O,Ya as P,E0 as Q,Ua as R,T0 as S,Fa as T,g0 as U,B0 as V,Ts as W,Pi as X,Ss as Y,zt as Z,dT as _,F0 as $,N0 as aa,pi as ba,Bs as ca,ja as da,ce as ea,Xa as fa,Ja as ga,z0 as ha,js as ia,Ws as ja,Xs as ka,G0 as la,b0 as ma,za as na,qT as oa,Sr as pa,p0 as qa,kT as ra,La as sa,Ga as ta,Rs as ua,Tr as va,DT as wa,Cr as xa,$t as ya,le as za,vi as Aa,W0 as Ba,X0 as Ca,Er as Da,XT as Ea,K0 as Fa,_T as Ga,IT as Ha,JT as Ia};
|