@stacksjs/rpx 0.11.18 → 0.11.20
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 +225 -210
- package/dist/cert-inspect.d.ts +5 -3
- package/dist/chunk-0f32jmrb.js +1 -0
- package/dist/chunk-bs9e342s.js +1 -0
- package/dist/chunk-vxj1ckdm.js +176 -0
- package/dist/{chunk-rbgb5fyg.js → chunk-w888yhnp.js} +12 -12
- package/dist/daemon.d.ts +17 -8
- package/dist/dns.d.ts +2 -0
- package/dist/https.d.ts +10 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +7 -7
- package/dist/logger.d.ts +8 -8
- package/dist/proxy-handler.d.ts +1 -1
- package/dist/proxy-pool.d.ts +82 -0
- package/dist/start.d.ts +31 -8
- package/dist/types.d.ts +13 -0
- package/dist/utils.d.ts +15 -0
- package/package.json +11 -7
- package/dist/chunk-9njrhbd4.js +0 -1
- package/dist/chunk-a0b9f9fs.js +0 -1
- package/dist/chunk-s4tdtq37.js +0 -161
- package/src/cert-inspect.ts +0 -69
- package/src/colors.ts +0 -13
- package/src/config.ts +0 -45
- package/src/daemon-runner.ts +0 -180
- package/src/daemon.ts +0 -786
- package/src/dns-state.ts +0 -116
- package/src/dns.ts +0 -509
- package/src/host-match.ts +0 -52
- package/src/host-routes.ts +0 -147
- package/src/hosts.ts +0 -278
- package/src/https.ts +0 -862
- package/src/index.ts +0 -158
- package/src/logger.ts +0 -19
- package/src/macos-trust.ts +0 -175
- package/src/on-demand.ts +0 -264
- package/src/origin-guard.ts +0 -105
- package/src/port-manager.ts +0 -183
- package/src/process-manager.ts +0 -164
- package/src/proxy-handler.ts +0 -315
- package/src/registry.ts +0 -366
- package/src/sni.ts +0 -93
- package/src/start.ts +0 -1421
- package/src/static-files.ts +0 -201
- package/src/types.ts +0 -256
- package/src/utils.ts +0 -210
package/dist/bin/cli.js
CHANGED
|
@@ -1,255 +1,270 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
3
|
#!/usr/bin/env bun
|
|
4
|
-
import{createRequire as lF}from"node:module";var vF=Object.defineProperty;var mF=($)=>$;function dF($,w){this[$]=mF.bind(null,w)}var lJ=($,w)=>{for(var A in w)vF($,A,{get:w[A],enumerable:!0,configurable:!0,set:dF.bind(w,A)})};var E0=($,w)=>()=>($&&(w=$($=0)),w);var n=lF(import.meta.url);import{existsSync as JW,statSync as WW}from"fs";import{existsSync as a9,mkdirSync as IN,readdirSync as CN,readFileSync as s9,writeFileSync as SN}from"fs";import{homedir as Pw}from"os";import{dirname as ON,resolve as A$}from"path";import UY from"process";import{existsSync as BW,statSync as EW}from"fs";import{existsSync as iX,mkdirSync as o9,readdirSync as e9,writeFileSync as $z}from"fs";import{homedir as iw}from"os";import{dirname as jW,resolve as x0}from"path";import qw from"process";import{join as wz,relative as Az,resolve as TW}from"path";import tA from"process";import{existsSync as rW,mkdirSync as cN,readdirSync as uN,writeFileSync as nN}from"fs";import{homedir as RX}from"os";import{dirname as dN,resolve as Z0}from"path";import x1 from"process";import{join as Yz,relative as fz,resolve as FW}from"path";import pA from"process";import{existsSync as aW,mkdirSync as rN,readdirSync as aN,writeFileSync as sN}from"fs";import{dirname as eN,resolve as rA}from"path";import bX from"process";import{Buffer as Aw}from"buffer";import{createCipheriv as Xz,createDecipheriv as Uz,randomBytes as NX}from"crypto";import{closeSync as qX,createReadStream as zW,createWriteStream as Jz,existsSync as hX,fsyncSync as GW,openSync as HW,writeFileSync as Wz}from"fs";import{access as Bz,constants as KW,mkdir as Ez,readdir as LA,rename as RW,stat as bw,unlink as VA,writeFile as yX}from"fs/promises";import{join as cw}from"path";import I0 from"process";import{pipeline as jz}from"stream/promises";import{createGzip as NW}from"zlib";import uw from"process";import D$ from"process";import{Buffer as O$}from"buffer";import{createCipheriv as Tz,createDecipheriv as Fz,randomBytes as MX}from"crypto";import{closeSync as IX,createReadStream as qW,createWriteStream as zz,existsSync as OA,fsyncSync as hW,openSync as yW,writeFileSync as Gz}from"fs";import{access as Hz,constants as MW,mkdir as Kz,readdir as _A,rename as IW,stat as nw,unlink as QA,writeFile as CX}from"fs/promises";import{isAbsolute as Rz,join as vw,resolve as Nz}from"path";import _ from"process";import{pipeline as qz}from"stream/promises";import{createGzip as CW}from"zlib";import mw from"process";import k$ from"process";import DA from"process";import{existsSync as kA}from"fs";import{resolve as SX}from"path";import{existsSync as hz}from"fs";import{existsSync as yz,readdirSync as Mz}from"fs";import{extname as LX,resolve as SW}from"path";import Iz from"process";import{join as Cz,relative as Sz,resolve as LW}from"path";import aA from"process";import{Buffer as _$}from"buffer";import{createCipheriv as Lz,createDecipheriv as Vz,randomBytes as VX}from"crypto";import{closeSync as OX,createReadStream as VW,createWriteStream as Oz,existsSync as ZA,fsyncSync as OW,openSync as _W,writeFileSync as _z}from"fs";import{access as Qz,constants as QW,mkdir as Dz,readdir as xA,rename as DW,stat as dw,unlink as PA,writeFile as _X}from"fs/promises";import{isAbsolute as kz,join as lw,resolve as Zz}from"path";import Q from"process";import{pipeline as xz}from"stream/promises";import{createGzip as kW}from"zlib";import gw from"process";import Z$ from"process";import bA from"process";import{existsSync as cA}from"fs";import{resolve as PX}from"path";import{existsSync as wG}from"fs";class tW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!JW($))return!0;return WW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=JW(A)?WW(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class pW{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function bz($,w){this[$]=iz.bind(null,w)}class aX{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!BW($))return!0;return EW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=BW(A)?EW(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class sX{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function nz($,w={}){let Y=Object.keys(w).sort().map((f)=>`${f}:${w[f]}`).join("|");return Y?`${$}:${Y}`:$}function vz($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function mz($){return $.getStats().size*2}function oX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&o(w[0])&&"id"in w[0]&&w[0].id===3&&o(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(o(w)&&o($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(o($)&&"arr"in $&&Array.isArray($.arr)&&o(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&o(w[0])&&o($[0])){let Y=[...w];for(let f of $)if(o(f)&&"name"in f){if(!Y.find((U)=>o(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(o(f)&&"path"in f){if(!Y.find((U)=>o(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>sA(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!o(w)||!o($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(o(f)&&o(A[Y]))A[Y]=oX(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&o(f[0])&&o(A[Y][0])){let X=[...f];for(let U of A[Y])if(o(U)&&"name"in U){if(!X.find((J)=>o(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(o(U)&&"path"in U){if(!X.find((J)=>o(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>sA(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function sA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!sA($[A],w[A]))return!1;return!0}if(o($)&&o(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!sA($[f],w[f]))return!1}return!0}return!1}function o($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function dz($,w){if(!aW($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return oX(w,Y)}catch{return null}}catch{return null}}async function lz({name:$="",cwd:w,defaultConfig:A}){let Y=w||bX.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=rA(Y,`${U}${W}`),B=await dz(J,A);if(B!==null)return B}try{let U=rA(Y,"package.json");if(aW(U)){let J=(await import(U))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return oX(A,J)}catch{}}}catch{}return A}function gz($,w={}){let A=pA.cwd();while(A.includes("storage"))A=FW(A,"..");let Y=FW(A,$||"");if(w?.relative)return fz(pA.cwd(),Y);return Y}async function tz(){try{let $=await lz({name:"clarity",defaultConfig:vA,cwd:pA.cwd(),endpoint:"",headers:{}});return{...vA,...$}}catch{return vA}}function Y0(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function pz(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D$<"u"){let $=D$.type;if($==="renderer"||$==="worker")return!1;return!!(D$.versions&&(D$.versions.node||D$.versions.bun))}return!1}class oW{async format($){let w=await pz(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:uw.pid,hostname:w(),environment:uw.env.NODE_ENV||"development",platform:uw.platform,version:uw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:uw.env.NODE_ENV||uw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oA{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($,w={}){this.name=$,this.config={...uX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new oW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??I0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...mA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...mA};return{...mA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:uX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await Bz(this.config.logDirectory,KW.F_OK|KW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Ez(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Aw.from($);try{if(!hX(this.currentLogFile))await yX(this.currentLogFile,"",{mode:420});if(f=HW(this.currentLogFile,"a",420),Wz(f,J,{flag:"a"}),GW(f),f!==void 0)qX(f),f=void 0;if((await bw(this.currentLogFile)).size===0){if(await yX(this.currentLogFile,J,{flag:"w",mode:420}),(await bw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{qX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 cw(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 cw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return cw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(Y0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return NX(16).toString("hex")}generateKey(){return NX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=NX(16),Y=Xz("aes-256-gcm",w,A),f=Aw.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:Aw.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=NW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Aw.from(Aw.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(Y0())return;let $=await bw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await LA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await bw(A).catch(()=>null))try{if(await RW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await VA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await yX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await bw(A).catch(()=>null))await RW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await LA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await VA(cw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=zW($),Y=Jz(w),f=NW();await jz(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),hX(this.currentLogFile))try{let $=HW(this.currentLogFile,"r+");GW($),qX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!Y0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await LA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await VA(cw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?t.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=I0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${t.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!Y0()){let B=WB[$],E=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:t.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:t.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
5
|
-
`);for(let F of
|
|
6
|
-
`;if(W)
|
|
7
|
-
`;
|
|
8
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!
|
|
9
|
-
`),
|
|
10
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
11
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||
|
|
12
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||Y0()||!I0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(Y0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await LA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=cw(this.config.logDirectory,Y);if($.before)try{if((await bw(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await VA(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function nA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&v(w[0])&&"id"in w[0]&&w[0].id===3&&v(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(v(w)&&v($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(v($)&&"arr"in $&&Array.isArray($.arr)&&v(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&v(w[0])&&v($[0])){let Y=[...w];for(let f of $)if(v(f)&&"name"in f){if(!Y.find((U)=>v(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(v(f)&&"path"in f){if(!Y.find((U)=>v(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>eA(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!v(w)||!v($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(v(f)&&v(A[Y]))A[Y]=nA(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&v(f[0])&&v(A[Y][0])){let X=[...f];for(let U of A[Y])if(v(U)&&"name"in U){if(!X.find((J)=>v(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(v(U)&&"path"in U){if(!X.find((J)=>v(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>eA(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function eX($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:nA($,w);if(Array.isArray($))return A==="replace"?w:nA($,w);if(!v(w)||!v($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=nA(U,X);else if(v(X)&&v(U))Y[f]=eX(U,X,A);else Y[f]=X}return Y}function eA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!eA($[A],w[A]))return!1;return!0}if(v($)&&v(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!eA($[f],w[f]))return!1}return!0}return!1}function v($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iA($,w,A="replace"){if(!rW($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return eX(w,f,A)}catch{return null}}catch{return null}}function rz($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((G)=>G.toUpperCase()).join("_")}`;if(A)S0.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let G=x1.env[F]||x1.env[H];if(G!==void 0){if(A)S0.info(`Using environment variable ${G?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(G);else if(typeof E==="boolean")J[B]=G.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(G);if(Array.isArray(K))J[B]=K;else J[B]=G.split(",").map((R)=>R.trim())}catch{J[B]=G.split(",").map((K)=>K.trim())}else J[B]=G}}}return J}return X(f)}async function az({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?rz($,f,X):f,B=A||x1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)S0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],G=Array.from(new Set([B,Z0(B,"config"),Z0(B,".config"),Y?Z0(B,Y):void 0].filter(Boolean)));for(let K of G){if(X)S0.info(`Searching for configuration in: ${K}`);let N=[Z0(B,"config"),Z0(B,".config")].concat(Y?[Z0(B,Y)]:[]).includes(K)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let h of N)for(let y of E){let I=Z0(K,`${h}${y}`),S=await iA(I,J,W);if(S!==null){if(X)S0.success(`Configuration loaded from: ${I}`);return S}}}if($){let K=Z0(RX(),".config",$),R=["config",`${$}.config`];if(w)R.push(`${w}.config`);if(X)S0.info(`Checking user config directory: ${K}`);for(let N of R)for(let h of E){let y=Z0(K,`${N}${h}`),I=await iA(y,J,W);if(I!==null){if(X)S0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let K=Z0(RX(),".config"),R=[`.${$}.config`];if(w)R.push(`.${w}.config`);if(X)S0.info(`Checking user config directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=Z0(K,`${N}${h}`),I=await iA(y,J,W);if(I!==null){if(X)S0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let K=RX(),R=[`.${$}.config`,`.${$}`];if(w)R.push(`.${w}.config`),R.push(`.${w}`);if(X)S0.info(`Checking user home directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=Z0(K,`${N}${h}`),I=await iA(y,J,W);if(I!==null){if(X)S0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let K=Z0(B,"package.json");if(rW(K)){let R=await import(K),N=R[$];if(!N&&w){if(N=R[w],N&&X)S0.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(X)S0.success(`Configuration loaded from package.json: ${N===R[$]?$:w}`);return eX(J,N,W)}catch(h){if(X)S0.warn("Failed to merge package.json config:",h)}}}catch(K){if(X)S0.warn("Failed to load package.json:",K)}if(X)S0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function sz($,w={}){let A=tA.cwd();while(A.includes("storage"))A=TW(A,"..");let Y=TW(A,$||"");if(w?.relative)return Az(tA.cwd(),Y);return Y}async function oz(){try{let $=await az({name:"clarity",alias:"logging",defaultConfig:dA,cwd:tA.cwd()});return{...dA,...$||{}}}catch{return dA}}function j0(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ez(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof k$<"u"){let $=k$.type;if($==="renderer"||$==="worker")return!1;return!!(k$.versions&&(k$.versions.node||k$.versions.bun))}return!1}class eW{async format($){let w=await ez(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:mw.pid,hostname:w(),environment:mw.env.NODE_ENV||"development",platform:mw.platform,version:mw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:mw.env.NODE_ENV||mw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $Y{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($,w={}){this.name=$,this.config={...nX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new eW,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...lA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...lA};return{...lA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:nX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!j0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await Hz(this.config.logDirectory,MW.F_OK|MW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Kz(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O$.from($);try{if(!OA(this.currentLogFile))await CX(this.currentLogFile,"",{mode:420});if(f=yW(this.currentLogFile,"a",420),Gz(f,J,{flag:"a"}),hW(f),f!==void 0)IX(f),f=void 0;if((await nw(this.currentLogFile)).size===0){if(await CX(this.currentLogFile,J,{flag:"w",mode:420}),(await nw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{IX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 vw(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 vw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return vw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(j0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return MX(16).toString("hex")}generateKey(){return MX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=MX(16),Y=Tz("aes-256-gcm",w,A),f=O$.isBuffer($)?$:O$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=O$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=CW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(O$.from(O$.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(j0())return;if(!this.shouldWriteToFile())return;let $=await nw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await _A(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await nw(A).catch(()=>null))try{if(await IW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await QA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await CX(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await nw(A).catch(()=>null))await IW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await _A(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await QA(vw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=qW($),Y=zz(w),f=CW();await qz(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),OA(this.currentLogFile))try{let $=yW(this.currentLogFile,"r+");hW($),IX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!j0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await _A(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await QA(vw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?Z.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||j0())return!1;let $=typeof _.env.NO_COLOR<"u",w=_.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=_.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${Z.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=Z.underline(Z.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>Z.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>Z.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>Z.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>Z.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>Z.strikethrough(Y)),w}supportsHyperlinks(){if(j0())return!1;let $=_.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=_.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Rz(w)||w.startsWith("./")||w.startsWith("../"))w=Nz(w);else return null;return OA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":BB[$],T=this.options.showTags!==!1&&this.name?Z.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:Z.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:Z.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
13
|
-
`);for(let
|
|
14
|
-
`;if(W)
|
|
15
|
-
`;if(
|
|
16
|
-
`);if(this[
|
|
17
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let
|
|
18
|
-
`),
|
|
19
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
20
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let
|
|
21
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
22
|
-
|
|
23
|
-
`;for(let
|
|
24
|
-
`,
|
|
25
|
-
`,
|
|
26
|
-
`,
|
|
27
|
-
|
|
28
|
-
`;return
|
|
29
|
-
|
|
30
|
-
`;
|
|
31
|
-
`,
|
|
32
|
-
`;for(let
|
|
33
|
-
`;return A}}function A2($,w){let A=UB("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function AB($,w,A={}){return YB($,w,A,new WeakMap)}function YB($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return fB($,w,f,Y);if(!Y$(w)||!Y$($))return w;return U2($,w,A,Y)}function fB($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return Y2($,w);case"smart":return f2($,w,Y);default:return w}return w}function Y2($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>cX(f,Y)))A.push(Y);return A}function f2($,w,A){if(w.length===0)return $;if($.length===0)return w;if(Y$(w[0])&&Y$($[0]))return X2($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function X2($,w,A){let Y=[...w];for(let f of $){if(!Y$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>Y$(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function U2($,w,A,Y){let f=w;if(Y$(f)&&Y.has(f))return Y.get(f);let X={...$};if(Y$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(Y$(W)&&Y$(J))X[U]=YB(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=fB(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function $U($,w,A="replace"){return AB($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function cX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!cX($[A],w[A]))return!1;return!0}if(Y$($)&&Y$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!cX($[f],w[f]))return!1}return!0}return!1}function Y$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class WY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=tw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!kA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new P1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new P1($,Error("Configuration must export a valid object"),"unknown");let K={config:$U(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)tw.setWithFileCheck("file",K,$,X);return K}catch(B){throw B instanceof Error?Yw.configLoad($,B):Yw.configLoad($,Error(String(B)))}};if(U)return b1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(SX(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return $B(async()=>{return kA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!kA($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=SX($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=SX($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){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((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!kA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class wU{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await b1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!hz(w))throw new i1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new i1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.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:jB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class AU{fileLoader=new WY;envProcessor=new JY;validator=new wU;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)G$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw G$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||qw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(x0(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Yw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?Z1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)G$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)G$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?Z1($,A,f):A,W=[x0(iw(),".config",$),x0(iw(),".config"),iw()];for(let J of W){if(f)G$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)G$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?Z1($,Y,X):Y;try{let J=x0(A,"package.json");if(!iX(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)G$.success(`Configuration loaded from package.json: ${j}`);return{config:$U(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)G$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:Z1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Yw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return tw.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);tw.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,x0($,"config"),x0($,".config"),w?x0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(x0(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[x0(iw(),".config",$),x0(iw(),".config"),iw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function ZW($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function J2($){return x$.loadConfig({...$,__strictErrorHandling:!0})}async function XB($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await x$.loadConfig($);else Y=await x$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)G$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await x$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function W2($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await x$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&ZW(A)))return(await x$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await x$.loadConfig({...$,cwd:$.cwd||qw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&ZW(w)))return(await x$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function B2($,w,A="replace"){let Y=new WY;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function Z1($,w,A=!1){let Y=new JY,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=qw.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function E2($){let w=x0(qw.cwd(),$.configDir),A=x0(qw.cwd(),$.generatedDir),Y=x0(A,"config-types.ts");if(!iX(jW(Y)))o9(jW(Y),{recursive:!0,mode:511});let f=iX(w)?e9(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${c2}
|
|
34
|
-
export type ConfigNames = ${
|
|
35
|
-
|
|
36
|
-
${
|
|
4
|
+
import{createRequire as dF}from"node:module";var cF=Object.defineProperty;var vF=($)=>$;function mF($,w){this[$]=vF.bind(null,w)}var RW=($,w)=>{for(var Y in w)cF($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:mF.bind(w,Y)})};var j0=($,w)=>()=>($&&(w=$($=0)),w);var v=dF(import.meta.url);import{existsSync as PW,statSync as bW}from"fs";import{existsSync as t5,mkdirSync as eR,readdirSync as $M,readFileSync as r5,writeFileSync as wM}from"fs";import{homedir as uw}from"os";import{dirname as UM,resolve as w$}from"path";import RA from"process";import{existsSync as uW,statSync as iW}from"fs";import{existsSync as U8,mkdirSync as a5,readdirSync as s5,writeFileSync as o5}from"fs";import{homedir as iw}from"os";import{dirname as cW,resolve as u0}from"path";import Cw from"process";import{join as e5,relative as $G,resolve as vW}from"path";import fA from"process";import{existsSync as CB,mkdirSync as EM,readdirSync as KM,writeFileSync as TM}from"fs";import{homedir as iX}from"os";import{dirname as qM,resolve as b0}from"path";import a1 from"process";import{join as wG,relative as YG,resolve as mW}from"path";import WA from"process";import{existsSync as hB,mkdirSync as CM,readdirSync as hM,writeFileSync as VM}from"fs";import{dirname as QM,resolve as BA}from"path";import X8 from"process";import{Buffer as Xw}from"buffer";import{createCipheriv as AG,createDecipheriv as UG,randomBytes as cX}from"crypto";import{closeSync as vX,createReadStream as dW,createWriteStream as XG,existsSync as mX,fsyncSync as gW,openSync as lW,writeFileSync as JG}from"fs";import{access as fG,constants as nW,mkdir as WG,readdir as vY,rename as pW,stat as cw,unlink as mY,writeFile as dX}from"fs/promises";import{join as vw}from"path";import V0 from"process";import{pipeline as BG}from"stream/promises";import{createGzip as tW}from"zlib";import mw from"process";import k$ from"process";import{Buffer as O$}from"buffer";import{createCipheriv as jG,createDecipheriv as zG,randomBytes as gX}from"crypto";import{closeSync as lX,createReadStream as rW,createWriteStream as FG,existsSync as dY,fsyncSync as aW,openSync as sW,writeFileSync as GG}from"fs";import{access as EG,constants as oW,mkdir as KG,readdir as gY,rename as eW,stat as dw,unlink as lY,writeFile as nX}from"fs/promises";import{isAbsolute as TG,join as gw,resolve as HG}from"path";import _ from"process";import{pipeline as NG}from"stream/promises";import{createGzip as $B}from"zlib";import lw from"process";import D$ from"process";import nY from"process";import{existsSync as pY}from"fs";import{resolve as pX}from"path";import{existsSync as qG}from"fs";import{existsSync as RG,readdirSync as MG}from"fs";import{extname as tX,resolve as wB}from"path";import IG from"process";import{join as yG,relative as CG,resolve as YB}from"path";import jA from"process";import{Buffer as S$}from"buffer";import{createCipheriv as hG,createDecipheriv as VG,randomBytes as rX}from"crypto";import{closeSync as aX,createReadStream as AB,createWriteStream as LG,existsSync as tY,fsyncSync as UB,openSync as XB,writeFileSync as QG}from"fs";import{access as OG,constants as JB,mkdir as SG,readdir as rY,rename as fB,stat as nw,unlink as aY,writeFile as sX}from"fs/promises";import{isAbsolute as _G,join as pw,resolve as kG}from"path";import k from"process";import{pipeline as DG}from"stream/promises";import{createGzip as WB}from"zlib";import tw from"process";import Z$ from"process";import oY from"process";import{existsSync as eY}from"fs";import{resolve as A8}from"path";import{existsSync as e6}from"fs";class IB{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!PW($))return!0;return bW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=PW(Y)?bW(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class yB{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function PG($,w){this[$]=xG.bind(null,w)}class H8{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!uW($))return!0;return iW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=uW(Y)?iW(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class N8{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function iG($,w={}){let A=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return A?`${$}:${A}`:$}function cG($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function vG($){return $.getStats().size*2}function q8($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&e(w[0])&&"id"in w[0]&&w[0].id===3&&e(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(e(w)&&e($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(e($)&&"arr"in $&&Array.isArray($.arr)&&e(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&e(w[0])&&e($[0])){let A=[...w];for(let U of $)if(e(U)&&"name"in U){if(!A.find((J)=>e(J)&&("name"in J)&&J.name===U.name))A.push(U)}else if(e(U)&&"path"in U){if(!A.find((J)=>e(J)&&("path"in J)&&J.path===U.path))A.push(U)}else if(!A.some((X)=>zA(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!e(w)||!e($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(e(U)&&e(Y[A]))Y[A]=q8(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&e(U[0])&&e(Y[A][0])){let X=[...U];for(let J of Y[A])if(e(J)&&"name"in J){if(!X.find((f)=>e(f)&&("name"in f)&&f.name===J.name))X.push(J)}else if(e(J)&&"path"in J){if(!X.find((f)=>e(f)&&("path"in f)&&f.path===J.path))X.push(J)}else if(!X.some((W)=>zA(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function zA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!zA($[Y],w[Y]))return!1;return!0}if(e($)&&e(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!zA($[U],w[U]))return!1}return!0}return!1}function e($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function mG($,w){if(!hB($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return q8(w,A)}catch{return null}}catch{return null}}async function dG({name:$="",cwd:w,defaultConfig:Y}){let A=w||X8.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let J of X)for(let W of U){let f=BA(A,`${J}${W}`),B=await mG(f,Y);if(B!==null)return B}try{let J=BA(A,"package.json");if(hB(J)){let f=(await import(J))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return q8(Y,f)}catch{}}}catch{}return Y}function gG($,w={}){let Y=WA.cwd();while(Y.includes("storage"))Y=mW(Y,"..");let A=mW(Y,$||"");if(w?.relative)return YG(WA.cwd(),A);return A}async function lG(){try{let $=await dG({name:"clarity",defaultConfig:YA,cwd:WA.cwd(),endpoint:"",headers:{}});return{...YA,...$}}catch{return YA}}function U0(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nG(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof k$<"u"){let $=k$.type;if($==="renderer"||$==="worker")return!1;return!!(k$.versions&&(k$.versions.node||k$.versions.bun))}return!1}class LB{async format($){let w=await nG(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:mw.pid,hostname:w(),environment:mw.env.NODE_ENV||"development",platform:mw.platform,version:mw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:mw.env.NODE_ENV||mw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class FA{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($,w={}){this.name=$,this.config={...f8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new LB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??V0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...AA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...AA};return{...AA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:f8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await fG(this.config.logDirectory,nW.F_OK|nW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await WG(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Xw.from($);try{if(!mX(this.currentLogFile))await dX(this.currentLogFile,"",{mode:420});if(U=lW(this.currentLogFile,"a",420),JG(U,f,{flag:"a"}),gW(U),U!==void 0)vX(U),U=void 0;if((await cw(this.currentLogFile)).size===0){if(await dX(this.currentLogFile,f,{flag:"w",mode:420}),(await cw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{vX(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,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 vw(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 vw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return vw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return cX(16).toString("hex")}generateKey(){return cX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=cX(16),A=AG("aes-256-gcm",w,Y),U=Xw.concat([A.update($,"utf8"),A.final()]),X=A.getAuthTag();return{encrypted:Xw.concat([Y,U,X]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=tW(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(Xw.from(Xw.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(U0())return;let $=await cw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await vY(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await cw(Y).catch(()=>null))try{if(await pW(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await mY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await dX(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await cw(Y).catch(()=>null))await pW(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await vY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await mY(vw(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=dW($),A=XG(w),U=tW();await BG(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),mX(this.currentLogFile))try{let $=lW(this.currentLogFile,"r+");gW($),vX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await vY(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await mY(vw(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?r.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=V0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${r.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);if(this.fancy&&!U0()){let B=bB[$],j=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:r.gray(J),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:r.green(J),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z),W){let G=W.split(`
|
|
5
|
+
`);for(let F of G)if(F.trim()&&!F.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:r.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let f=`${X} ${this.environment}.${$.toUpperCase()}: ${J}
|
|
6
|
+
`;if(W)f+=`${W}
|
|
7
|
+
`;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!U0()){let Y=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:r.blue("◐"),tag:Y,message:`${r.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
8
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let j=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:r.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new FA(w,{...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(Y),Y}createReadStream(){if(U0())throw Error("createReadStream is not supported in browser environments");if(!mX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return dW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Xw.isBuffer($)?$:Xw.from($,"base64"),U=A.slice(0,16),X=A.slice(-16),J=A.slice(16,-16),W=UG("aes-256-gcm",Y,U);return W.setAuthTag(X),Xw.concat([W.update(J),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U0()}isServerMode(){return!U0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}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($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!U0()){let X=$.split(`
|
|
9
|
+
`),J=Math.max(...X.map((j)=>j.length))+2,W=`┌${"─".repeat(J)}┐`,f=`└${"─".repeat(J)}┘`,B=X.map((j)=>{let z=" ".repeat(J-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:r.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:r.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:r.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:r.cyan(f),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let U=`${A} ${this.environment}.INFO: [BOX] ${$}
|
|
10
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(U0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${r.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();V0.stdin.removeListener("data",Y);try{if(typeof V0.stdin.setRawMode==="function")V0.stdin.setRawMode(!1)}catch{}V0.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof V0.stdin.setRawMode==="function")V0.stdin.setRawMode(!0)}catch{}V0.stdin.resume(),V0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,W=0;if(Y=$.replace(J,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)Y+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!U0()){let J=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",W=r.blue("◐");console.error(`${W} ${J} ${r.cyan(Y)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
11
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||U0()||$<=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 Y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),W!==void 0)this.activeProgressBar.message=W;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;V0.stdout.write(`${"\r".padEnd(V0.stdout.columns||80)}\r`),this.log(W,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||U0()||!V0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=r.green("━".repeat(A)),J=r.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=w||Y===100?r.green("✓"):r.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${r.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=V0.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,V0.stdout.write($.lastRenderedLine),w)V0.stdout.write(`
|
|
12
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||U0()||!V0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await vY(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=vw(this.config.logDirectory,A);if($.before)try{if((await cw(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await mY(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function wA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&m(w[0])&&"id"in w[0]&&w[0].id===3&&m(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(m(w)&&m($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(m($)&&"arr"in $&&Array.isArray($.arr)&&m(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&m(w[0])&&m($[0])){let A=[...w];for(let U of $)if(m(U)&&"name"in U){if(!A.find((J)=>m(J)&&("name"in J)&&J.name===U.name))A.push(U)}else if(m(U)&&"path"in U){if(!A.find((J)=>m(J)&&("path"in J)&&J.path===U.path))A.push(U)}else if(!A.some((X)=>GA(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!m(w)||!m($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(m(U)&&m(Y[A]))Y[A]=wA(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&m(U[0])&&m(Y[A][0])){let X=[...U];for(let J of Y[A])if(m(J)&&"name"in J){if(!X.find((f)=>m(f)&&("name"in f)&&f.name===J.name))X.push(J)}else if(m(J)&&"path"in J){if(!X.find((f)=>m(f)&&("path"in f)&&f.path===J.path))X.push(J)}else if(!X.some((W)=>GA(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function R8($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:wA($,w);if(Array.isArray($))return Y==="replace"?w:wA($,w);if(!m(w)||!m($))return w;let A={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let X=w[U],J=A[U];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(J))if(Y==="replace")A[U]=X;else A[U]=wA(J,X);else if(m(X)&&m(J))A[U]=R8(J,X,Y);else A[U]=X}return A}function GA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!GA($[Y],w[Y]))return!1;return!0}if(m($)&&m(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!GA($[U],w[U]))return!1}return!0}return!1}function m($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function sY($,w,Y="replace"){if(!CB($))return null;try{let A=await import($),U=A.default||A;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return R8(w,U,Y)}catch{return null}}catch{return null}}function pG($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),U={...w};function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${z.map(G).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)Q0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=X(j,z);else{let K=a1.env[F]||a1.env[T];if(K!==void 0){if(Y)Q0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((q)=>q.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return X(U)}async function tG({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:U,verbose:X=!1,checkEnv:J=!0,arrayStrategy:W="replace"}){let f=J&&typeof U==="object"&&U!==null&&!Array.isArray(U)?pG($,U,X):U,B=Y||a1.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(X)Q0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),G=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,b0(B,"config"),b0(B,".config"),A?b0(B,A):void 0].filter(Boolean)));for(let H of K){if(X)Q0.info(`Searching for configuration in: ${H}`);let M=[b0(B,"config"),b0(B,".config")].concat(A?[b0(B,A)]:[]).includes(H)?[...z,...G,...F,...T]:[...G,...z,...T,...F];for(let I of M)for(let h of j){let N=b0(H,`${I}${h}`),C=await sY(N,f,W);if(C!==null){if(X)Q0.success(`Configuration loaded from: ${N}`);return C}}}if($){let H=b0(iX(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(X)Q0.info(`Checking user config directory: ${H}`);for(let M of q)for(let I of j){let h=b0(H,`${M}${I}`),N=await sY(h,f,W);if(N!==null){if(X)Q0.success(`Configuration loaded from user config directory: ${h}`);return N}}}if($){let H=b0(iX(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(X)Q0.info(`Checking user config directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=b0(H,`${M}${I}`),N=await sY(h,f,W);if(N!==null){if(X)Q0.success(`Configuration loaded from user config directory dotfile: ${h}`);return N}}}if($){let H=iX(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(X)Q0.info(`Checking user home directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=b0(H,`${M}${I}`),N=await sY(h,f,W);if(N!==null){if(X)Q0.success(`Configuration loaded from user home directory: ${h}`);return N}}}try{let H=b0(B,"package.json");if(CB(H)){let q=await import(H),M=q[$];if(!M&&w){if(M=q[w],M&&X)Q0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(X)Q0.success(`Configuration loaded from package.json: ${M===q[$]?$:w}`);return R8(f,M,W)}catch(I){if(X)Q0.warn("Failed to merge package.json config:",I)}}}catch(H){if(X)Q0.warn("Failed to load package.json:",H)}if(X)Q0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function rG($,w={}){let Y=fA.cwd();while(Y.includes("storage"))Y=vW(Y,"..");let A=vW(Y,$||"");if(w?.relative)return $G(fA.cwd(),A);return A}async function aG(){try{let $=await tG({name:"clarity",alias:"logging",defaultConfig:UA,cwd:fA.cwd()});return{...UA,...$||{}}}catch{return UA}}function G0(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function sG(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D$<"u"){let $=D$.type;if($==="renderer"||$==="worker")return!1;return!!(D$.versions&&(D$.versions.node||D$.versions.bun))}return!1}class QB{async format($){let w=await sG(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:lw.pid,hostname:w(),environment:lw.env.NODE_ENV||"development",platform:lw.platform,version:lw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lw.env.NODE_ENV||lw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class EA{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($,w={}){this.name=$,this.config={...W8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new QB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...XA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...XA};return{...XA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:W8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!G0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await EG(this.config.logDirectory,oW.F_OK|oW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await KG(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O$.from($);try{if(!dY(this.currentLogFile))await nX(this.currentLogFile,"",{mode:420});if(U=sW(this.currentLogFile,"a",420),GG(U,f,{flag:"a"}),aW(U),U!==void 0)lX(U),U=void 0;if((await dw(this.currentLogFile)).size===0){if(await nX(this.currentLogFile,f,{flag:"w",mode:420}),(await dw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{lX(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,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 gw(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 gw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return gw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(G0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return gX(16).toString("hex")}generateKey(){return gX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=gX(16),A=jG("aes-256-gcm",w,Y),U=O$.isBuffer($)?$:O$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=O$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=$B(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(O$.from(O$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(G0())return;if(!this.shouldWriteToFile())return;let $=await dw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await gY(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await dw(Y).catch(()=>null))try{if(await eW(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await lY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await nX(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await dw(Y).catch(()=>null))await eW(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await gY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await lY(gw(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=rW($),A=FG(w),U=$B();await NG(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),dY(this.currentLogFile))try{let $=sW(this.currentLogFile,"r+");aW($),lX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!G0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await gY(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await lY(gw(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?x.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||G0())return!1;let $=typeof _.env.NO_COLOR<"u",w=_.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=_.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${x.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=x.underline(x.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>x.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>x.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>x.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>x.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>x.strikethrough(A)),w}supportsHyperlinks(){if(G0())return!1;let $=_.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=_.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(TG(w)||w.startsWith("./")||w.startsWith("../"))w=HG(w);else return null;return dY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":uB[$],G=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:x.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:x.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
13
|
+
`);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:x.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!G0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
14
|
+
`;if(W)j+=`${W}
|
|
15
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!G0()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!G0()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!G0()&&_.stdout.isTTY)_.stdout.write(`
|
|
16
|
+
`);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!G0()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":x.blue("◐"),tag:Y,message:`${x.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
17
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":x.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!G0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new EA(w,{...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(Y),Y}createReadStream(){if(G0())throw Error("createReadStream is not supported in browser environments");if(!dY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=O$.isBuffer($)?$:O$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=zG("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=O$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return G0()}isServerMode(){return!G0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}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($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
18
|
+
`),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:x.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:x.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:x.cyan(j),showTimestamp:!1}))}else if(!G0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
|
|
19
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(G0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${x.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();_.stdin.removeListener("data",Y);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(Y=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let G=w[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<w.length)Y+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${x.blue("◐")} `;console.error(`${B}${f} ${x.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
20
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=x.green("━".repeat(A)),J=x.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?x.green("✓"):x.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=_.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,_.stdout.write($.lastRenderedLine),w)_.stdout.write(`
|
|
21
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||G0()||!_.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(G0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await gY(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=gw(this.config.logDirectory,A);if($.before)try{if((await dw(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await lY(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function OB($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}function SB($){return $ instanceof a0}function oG($){return $ instanceof KA}function eG($){if(SB($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class MA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return e1.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=nY.env[f]||(B?nY.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=nY.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof TA)throw z;throw Jw.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw Jw.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(nY.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
22
|
+
|
|
23
|
+
`;for(let A of $)Y+=`${A.key}
|
|
24
|
+
`,Y+=` Type: ${A.type}
|
|
25
|
+
`,Y+=` Description: ${A.description}
|
|
26
|
+
`,Y+=` Example: ${A.example}
|
|
27
|
+
|
|
28
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
29
|
+
|
|
30
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
31
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
32
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
33
|
+
`;return Y}}function $6($,w){let Y=xB("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function _B($,w,Y={}){return kB($,w,Y,new WeakMap)}function kB($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return DB($,w,U,A);if(!Y$(w)||!Y$($))return w;return U6($,w,Y,A)}function DB($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return w6($,w);case"smart":return Y6($,w,A);default:return w}return w}function w6($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>J8(U,A)))Y.push(A);return Y}function Y6($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(Y$(w[0])&&Y$($[0]))return A6($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function A6($,w,Y){let A=[...w];for(let U of $){if(!Y$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((B)=>Y$(B)&&(W in B)&&B[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function U6($,w,Y,A){let U=w;if(Y$(U)&&A.has(U))return A.get(U);let X={...$};if(Y$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(Y$(W)&&Y$(f))X[J]=kB(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=DB(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function M8($,w,Y="replace"){return _B($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function J8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!J8($[Y],w[Y]))return!1;return!0}if(Y$($)&&Y$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!J8($[U],w[U]))return!1}return!0}return!1}function Y$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class IA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=rw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!pY($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new s1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new s1($,Error("Configuration must export a valid object"),"unknown");let H={config:M8(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)rw.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?Jw.configLoad($,B):Jw.configLoad($,Error(String(B)))}};if(J)return e1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(pX(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return OB(async()=>{return pY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!pY($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=pX($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=pX($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){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((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!pY($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class I8{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await e1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!qG(w))throw new o1(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new o1(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.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:cB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class y8{fileLoader=new IA;envProcessor=new MA;validator=new I8;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)F$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw F$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||Cw.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(u0(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw Jw.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?r1($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)F$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)F$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?r1($,Y,U):Y,W=[u0(iw(),".config",$),u0(iw(),".config"),iw()];for(let f of W){if(U)F$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)F$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?r1($,A,X):A;try{let f=u0(Y,"package.json");if(!U8(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)F$.success(`Configuration loaded from package.json: ${z}`);return{config:M8(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)F$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:r1($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw Jw.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return rw.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);rw.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,u0($,"config"),u0($,".config"),w?u0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(u0(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[u0(iw(),".config",$),u0(iw(),".config"),iw()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function BB($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function X6($){return x$.loadConfig({...$,__strictErrorHandling:!0})}async function ZB($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await x$.loadConfig($);else A=await x$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}catch(A){let U=A instanceof Error?A.name:"UnknownError",X=A instanceof Error?A.message:String(A);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||X.includes("config"))&&$.verbose)F$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await x$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function J6($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await x$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&BB(Y)))return(await x$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await x$.loadConfig({...$,cwd:$.cwd||Cw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&BB(w)))return(await x$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function f6($,w,Y="replace"){let A=new IA;try{let U=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function r1($,w,Y=!1){let A=new MA,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=Cw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}function W6($){let w=u0(Cw.cwd(),$.configDir),Y=u0(Cw.cwd(),$.generatedDir),A=u0(Y,"config-types.ts");if(!U8(cW(A)))a5(cW(A),{recursive:!0,mode:511});let U=U8(w)?s5(w).map((J)=>J.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${b6}
|
|
34
|
+
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
35
|
+
`;o5(A,X,{mode:438})}function B6($){let w=null,Y=null,A=()=>{if(!Y)Y=ZB($).then((X)=>{return w=X,X},(X)=>{let J="defaultConfig"in $?$.defaultConfig:{};if(w=J,"verbose"in $&&$.verbose)F$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return J});return Y},U="defaultConfig"in $?$.defaultConfig:{};return w=U,A(),new Proxy({},{get(X,J){if(w)return w[J];let W=U[J];return A(),W},has(X,J){return J in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(X,J){return Object.getOwnPropertyDescriptor(w||U,J)},set(X,J,W){if(!w)w={...U};return w[J]=W,!0}})}function j6($){let w=wB(IG.cwd(),$?.configDir||"./config");function Y(){if(!RG(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],J=MG(w).filter((f)=>U.has(tX(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),W=new Map;for(let{base:f,file:B}of J){let j=tX(B).toLowerCase(),z=W.get(f);if(!z){W.set(f,B);continue}let G=tX(z).toLowerCase();if(X.indexOf(j)<X.indexOf(G))W.set(f,B)}return Array.from(W.entries()).map(([f,B])=>({base:f,file:B})).sort((f,B)=>f.base.localeCompare(B.base))}function A(){let U=Y(),X=U.map((B)=>B.base),J=X.length?X.map((B)=>`'${B}'`).join(" | "):"string",W=U.length?`{
|
|
36
|
+
${U.map((B)=>{let j=wB(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
|
|
37
37
|
`)}
|
|
38
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
38
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${J}
|
|
39
39
|
export type ConfigByName = ${W}
|
|
40
40
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
41
41
|
export type ConfigOf = Config
|
|
42
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function n2($,w={}){let A=aA.cwd();while(A.includes("storage"))A=LW(A,"..");let Y=LW(A,$||"");if(w?.relative)return Sz(aA.cwd(),Y);return Y}function F0(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function m2(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z$<"u"){let $=Z$.type;if($==="renderer"||$==="worker")return!1;return!!(Z$.versions&&(Z$.versions.node||Z$.versions.bun))}return!1}class GB{async format($){let w=await m2(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:gw.pid,hostname:w(),environment:gw.env.NODE_ENV||"development",platform:gw.platform,version:gw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:gw.env.NODE_ENV||gw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class BY{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($,w={}){this.name=$,this.config={...YY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new GB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Q.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...xX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...xX};return{...xX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:YY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await Qz(this.config.logDirectory,QW.F_OK|QW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Dz(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:_$.from($);try{if(!ZA(this.currentLogFile))await _X(this.currentLogFile,"",{mode:420});if(f=_W(this.currentLogFile,"a",420),_z(f,J,{flag:"a"}),OW(f),f!==void 0)OX(f),f=void 0;if((await dw(this.currentLogFile)).size===0){if(await _X(this.currentLogFile,J,{flag:"w",mode:420}),(await dw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{OX(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 lw(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 lw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return lw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return VX(16).toString("hex")}generateKey(){return VX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=VX(16),Y=Lz("aes-256-gcm",w,A),f=_$.isBuffer($)?$:_$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=_$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=kW(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(_$.from(_$.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(F0())return;if(!this.shouldWriteToFile())return;let $=await dw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await xA(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await dw(A).catch(()=>null))try{if(await DW(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await PA(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await _X(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await dw(A).catch(()=>null))await DW(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await xA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await PA(lw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=VW($),Y=Oz(w),f=kW();await xz(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),ZA(this.currentLogFile))try{let $=_W(this.currentLogFile,"r+");OW($),OX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await xA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await PA(lw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let $=typeof Q.env.NO_COLOR<"u",w=Q.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof Q.stderr<"u"&&Q.stderr.isTTY||typeof Q.stdout<"u"&&Q.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=Q.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${b.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=b.underline(b.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>b.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>b.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>b.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>b.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>b.strikethrough(Y)),w}supportsHyperlinks(){if(F0())return!1;let $=Q.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=Q.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(kz(w)||w.startsWith("./")||w.startsWith("../"))w=Zz(w);else return null;return ZA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":p2[$],T=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:b.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:b.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
43
|
-
`);for(let
|
|
44
|
-
`;if(W)
|
|
45
|
-
`;if(
|
|
46
|
-
`);if(this[
|
|
47
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let
|
|
48
|
-
`),
|
|
49
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
50
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
51
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
52
|
-
|
|
53
|
-
`;for(let
|
|
54
|
-
`,
|
|
55
|
-
`,
|
|
56
|
-
`,
|
|
57
|
-
|
|
58
|
-
`;return
|
|
59
|
-
|
|
60
|
-
`;
|
|
61
|
-
`,
|
|
62
|
-
`;for(let
|
|
63
|
-
`;return A}}function a2($,w,A={}){return MB($,w,A,new WeakMap)}function MB($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return IB($,w,f,Y);if(!f$(w)||!f$($))return w;return $G($,w,A,Y)}function IB($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return s2($,w);case"smart":return o2($,w,Y);default:return w}return w}function s2($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>pX(f,Y)))A.push(Y);return A}function o2($,w,A){if(w.length===0)return $;if($.length===0)return w;if(f$(w[0])&&f$($[0]))return e2($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function e2($,w,A){let Y=[...w];for(let f of $){if(!f$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>f$(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function $G($,w,A,Y){let f=w;if(f$(f)&&Y.has(f))return Y.get(f);let X={...$};if(f$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(f$(W)&&f$(J))X[U]=MB(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=IB(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function CB($,w,A="replace"){return a2($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function pX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!pX($[A],w[A]))return!1;return!0}if(f$($)&&f$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!pX($[f],w[f]))return!1}return!0}return!1}function f$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class SB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=gA.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!cA($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new fY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new fY($,Error("Configuration must export a valid object"),"unknown");let K={config:CB(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)gA.setWithFileCheck("file",K,$,X);return K}catch(B){throw B instanceof Error?pw.configLoad($,B):pw.configLoad($,Error(String(B)))}};if(U)return rX.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(PX(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of Y){if(!X)continue;if(A.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)A.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let f=new Set;return A.filter((X)=>{if(!X||f.has(X))return!1;return f.add(X),!0})}checkFileAccess($){return r2(async()=>{return cA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!cA($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=PX($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=PX($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){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((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!cA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class LB{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await rX.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!wG(w))throw new XY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new XY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.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:AG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function YG($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class VB{fileLoader=new SB;envProcessor=new fU;validator=new LB;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)Q$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let J=Date.now()-w;throw Q$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||UY.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(A$(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw pw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${YG(f)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?uA($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)Q$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)Q$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?uA($,A,f):A,W=[A$(Pw(),".config",$),A$(Pw(),".config"),Pw()];for(let J of W){if(f)Q$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)Q$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?uA($,Y,X):Y;try{let J=A$(A,"package.json");if(!a9(J))return null;let B={};try{B=JSON.parse(s9(J,"utf8"))}catch(T){if(X)Q$.warn("Failed to parse package.json:",[T instanceof Error?T:Error(String(T))]);return null}let E=B[$],j=$;if(!E&&w){let T=Array.isArray(w)?w:[w];for(let F of T){if(!F)continue;if(B[F]){E=B[F],j=F;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)Q$.success(`Configuration loaded from package.json: ${j}`);return{config:CB(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)Q$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:uA($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw pw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return gA.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);gA.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,A$($,"config"),A$($,".config"),w?A$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(A$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[A$(Pw(),".config",$),A$(Pw(),".config"),Pw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function uA($,w,A=!1){let Y=new fU,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=UY.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}var gA,rX,Pz,iz=($)=>$,cz=($,w)=>{for(var A in w)Pz($,A,{get:w[A],enumerable:!0,configurable:!0,set:bz.bind(w,A)})},uz=($,w)=>()=>($&&(w=$($=0)),w),sW,UB,tw,b1,JB,F2,z2,xW,vA,uX,C0,t,G2,PW,H2,iW,K2,R2,QX,N2,bW,cW,DX,q2,h2,y2,M2,mA,WB,I2,S0,C2,S2,uW,dA,nX,T0,Z,L2,nW,V2,vW,O2,_2,kX,Q2,mW,dW,D2,ZX,k2,Z2,x2,P2,i2,lA,BB,b2,c2="0.15.6",p0,wY,P1,vX,mX,AY,dX,lX,i1,gX,tX,Yw,EB,jB,G$,x$,TB,FB,u2,v2,zB,YY,uq,h0,b,nq,d2,vq,l2,mq,dq,lW,lq,g2,t2,gq,gW,tq,pq,rq,aq,sq,xX,p2,oq,H$,HB,fY,KB,RB,YU,NB,qB,XY,hB,yB,pw,AG,Q$,Yh,fh,Xh;var XU=E0(()=>{gA=new tW,rX=new pW,Pz=Object.defineProperty;sW={};cz(sW,{withErrorRecovery:()=>$B,tryLoadConfig:()=>B2,loadConfigWithResult:()=>J2,loadConfig:()=>XB,isRetryableError:()=>w2,isConfigNotFoundError:()=>$2,isBunfigError:()=>wB,globalPerformanceMonitor:()=>b1,globalCache:()=>tw,getEnvOrDefault:()=>A2,generateConfigTypes:()=>E2,defaultGeneratedDir:()=>FB,defaultConfigDir:()=>TB,deepMergeWithArrayStrategy:()=>$U,deepMerge:()=>AB,createLibraryConfig:()=>j2,config:()=>W2,bunfigPlugin:()=>T2,applyEnvVarsToConfig:()=>Z1,TypeGenerationError:()=>lX,SchemaValidationError:()=>i1,PluginError:()=>tX,PerformanceMonitor:()=>sX,FileSystemError:()=>dX,ErrorFactory:()=>Yw,EnvVarError:()=>AY,EnvProcessor:()=>JY,ConfigValidator:()=>wU,ConfigValidationError:()=>vX,ConfigNotFoundError:()=>wY,ConfigMergeError:()=>mX,ConfigLoader:()=>AU,ConfigLoadError:()=>P1,ConfigFileLoader:()=>WY,ConfigCache:()=>aX,CacheUtils:()=>JB,BunfigError:()=>p0,BrowserConfigError:()=>gX,ArrayMergeStrategies:()=>EB});u2=uz(async()=>{UB=import.meta.require,tw=new aX,b1=new sX,JB={createKey:nz,isEquivalent:vz,estimateMemoryUsage:mz},F2=rA(bX.cwd(),"config"),z2=rA(bX.cwd(),"src/generated"),xW=pA.env.CLARITY_LOG_DIR||Yz(gz(),"logs"),vA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:xW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},uX=await tz(),C0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},t=C0,G2=C0.red,PW=C0.green,H2=C0.yellow,iW=C0.blue,K2=C0.magenta,R2=C0.cyan,QX=C0.white,N2=C0.gray,bW=C0.bgRed,cW=C0.bgYellow,DX=C0.bold,q2=C0.dim,h2=C0.italic,y2=C0.underline,M2=C0.reset,mA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},WB={debug:"\uD83D\uDD0D",info:iW("ℹ"),success:PW("✓"),warning:cW(QX(DX(" WARN "))),error:bW(QX(DX(" ERROR ")))},I2=new oA("stacks"),S0=new oA("bunfig",{showTags:!0}),C2=Z0(x1.cwd(),"config"),S2=Z0(x1.cwd(),"src/generated"),uW=tA.env.CLARITY_LOG_DIR||wz(sz(),"logs"),dA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},nX=await oz(),T0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},Z=T0,L2=T0.red,nW=T0.green,V2=T0.yellow,vW=T0.blue,O2=T0.magenta,_2=T0.cyan,kX=T0.white,Q2=T0.gray,mW=T0.bgRed,dW=T0.bgYellow,D2=T0.bgGray,ZX=T0.bold,k2=T0.dim,Z2=T0.italic,x2=T0.underline,P2=T0.strikethrough,i2=T0.reset,lA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},BB={debug:"\uD83D\uDD0D",info:vW("ℹ"),success:nW("✓"),warning:dW(kX(ZX(" WARN "))),error:mW(kX(ZX(" ERROR ")))},b2=new $Y("stacks"),p0=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},wY=class extends p0{code="CONFIG_NOT_FOUND";constructor(w,A,Y){let f=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${f} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},P1=class extends p0{code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},vX=class extends p0{code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},mX=class extends p0{code="CONFIG_MERGE_ERROR";constructor(w,A,Y,f){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:f,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},AY=class extends p0{code="ENV_VAR_ERROR";constructor(w,A,Y,f){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:f})}},dX=class extends p0{code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},lX=class extends p0{code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},i1=class extends p0{code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},gX=class extends p0{code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,f){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:f})}},tX=class extends p0{code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Yw={configNotFound($,w,A){return new wY($,w,A)},configLoad($,w,A){return new P1($,w,A)},configValidation($,w,A){return new vX($,w,A)},configMerge($,w,A,Y){return new mX($,w,A,Y)},envVar($,w,A,Y){return new AY($,w,A,Y)},fileSystem($,w,A){return new dX($,w,A)},typeGeneration($,w,A){return new lX($,w,A)},schemaValidation($,w,A){return new i1($,w,A)},browserConfig($,w,A,Y){return new gX($,w,A,Y)},plugin($,w,A){return new tX($,w,A)}},EB={replace:"replace",concat:"concat",smart:"smart"},jB=/^https?:\/\//,G$=new $Y("bunfig",{showTags:!0}),x$=new AU,TB=x0(qw.cwd(),"config"),FB=x0(qw.cwd(),"src/generated")});v2=aA.env.CLARITY_LOG_DIR||Cz(n2(),"logs"),zB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:v2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},YY={...zB},uq=(async()=>{try{let{loadConfig:$}=await u2().then(()=>sW),w=await $({name:"clarity",alias:"logging",defaultConfig:zB,cwd:aA.cwd()});if(w)Object.assign(YY,w)}catch{}return YY})();h0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},b=h0,nq=h0.red,d2=h0.green,vq=h0.yellow,l2=h0.blue,mq=h0.magenta,dq=h0.cyan,lW=h0.white,lq=h0.gray,g2=h0.bgRed,t2=h0.bgYellow,gq=h0.bgGray,gW=h0.bold,tq=h0.dim,pq=h0.italic,rq=h0.underline,aq=h0.strikethrough,sq=h0.reset,xX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},p2={debug:"\uD83D\uDD0D",info:l2("ℹ"),success:d2("✓"),warning:t2(lW(gW(" WARN "))),error:g2(lW(gW(" ERROR ")))};oq=new BY("stacks");H$=class H$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};HB=class HB extends H${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],f="";if(Y.length===1)f=` or alias "${Y[0]}"`;else if(Y.length>1)f=` or aliases ${Y.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${f} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};fY=class fY extends H${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};KB=class KB extends H${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};RB=class RB extends H${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};YU=class YU extends H${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};NB=class NB extends H${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};qB=class qB extends H${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};XY=class XY extends H${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};hB=class hB extends H${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};yB=class yB extends H${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};pw={configNotFound($,w,A){return new HB($,w,A)},configLoad($,w,A){return new fY($,w,A)},configValidation($,w,A){return new KB($,w,A)},configMerge($,w,A,Y){return new RB($,w,A,Y)},envVar($,w,A,Y){return new YU($,w,A,Y)},fileSystem($,w,A){return new NB($,w,A)},typeGeneration($,w,A){return new qB($,w,A)},schemaValidation($,w,A){return new XY($,w,A)},browserConfig($,w,A,Y){return new hB($,w,A,Y)},plugin($,w,A){return new yB($,w,A)}};AG=/^https?:\/\//;Q$=new BY("bunfig",{showTags:!0});Yh=new VB;fh=A$(UY.cwd(),"config"),Xh=A$(UY.cwd(),"src/generated")});var q;var fw=E0(()=>{q={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as UG}from"node:module";import{Resolver as WU}from"node:dns/promises";import{createHash as WG,sign as BG}from"node:crypto";import{createHash as EG}from"node:crypto";import{sign as jG}from"node:crypto";import{generateKeyPairSync as xE,X509Certificate as qG}from"node:crypto";import BU from"node:os";import EU from"node:path";import{existsSync as _B,statSync as QB}from"fs";import{existsSync as yG,mkdirSync as Mh,readdirSync as Ih,readFileSync as MG,writeFileSync as Ch}from"fs";import{homedir as aw}from"os";import{dirname as Vh,resolve as U$}from"path";import rY from"process";import{existsSync as DB,statSync as kB}from"fs";import{existsSync as ZU,mkdirSync as IG,readdirSync as CG,writeFileSync as SG}from"fs";import{homedir as sw}from"os";import{dirname as ZB,resolve as i0}from"path";import yw from"process";import{join as LG,relative as VG,resolve as xB}from"path";import DY from"process";import{existsSync as PE,mkdirSync as bh,readdirSync as ch,writeFileSync as uh}from"fs";import{homedir as jU}from"os";import{dirname as mh,resolve as P0}from"path";import m1 from"process";import{join as OG,relative as _G,resolve as PB}from"path";import kY from"process";import{existsSync as iE,mkdirSync as ph,readdirSync as rh,writeFileSync as ah}from"fs";import{dirname as oh,resolve as ZY}from"path";import xU from"process";import{Buffer as Xw}from"buffer";import{createCipheriv as QG,createDecipheriv as DG,randomBytes as TU}from"crypto";import{closeSync as FU,createReadStream as iB,createWriteStream as kG,existsSync as zU,fsyncSync as bB,openSync as cB,writeFileSync as ZG}from"fs";import{access as xG,constants as uB,mkdir as PG,readdir as EY,rename as nB,stat as ow,unlink as jY,writeFile as GU}from"fs/promises";import{join as ew}from"path";import L0 from"process";import{pipeline as iG}from"stream/promises";import{createGzip as vB}from"zlib";import $1 from"process";import c$ from"process";import{Buffer as P$}from"buffer";import{createCipheriv as bG,createDecipheriv as cG,randomBytes as HU}from"crypto";import{closeSync as KU,createReadStream as mB,createWriteStream as uG,existsSync as TY,fsyncSync as dB,openSync as lB,writeFileSync as nG}from"fs";import{access as vG,constants as gB,mkdir as mG,readdir as FY,rename as tB,stat as w1,unlink as zY,writeFile as RU}from"fs/promises";import{isAbsolute as dG,join as A1,resolve as lG}from"path";import m from"process";import{pipeline as gG}from"stream/promises";import{createGzip as pB}from"zlib";import Y1 from"process";import u$ from"process";import GY from"process";import{existsSync as HY}from"fs";import{resolve as NU}from"path";import{existsSync as tG}from"fs";import{existsSync as pG,readdirSync as rG}from"fs";import{extname as qU,resolve as rB}from"path";import aG from"process";import{join as sG,relative as oG,resolve as aB}from"path";import xY from"process";import{Buffer as i$}from"buffer";import{createCipheriv as eG,createDecipheriv as $H,randomBytes as hU}from"crypto";import{closeSync as yU,createReadStream as sB,createWriteStream as wH,existsSync as KY,fsyncSync as oB,openSync as eB,writeFileSync as AH}from"fs";import{access as YH,constants as $E,mkdir as fH,readdir as RY,rename as wE,stat as f1,unlink as NY,writeFile as MU}from"fs/promises";import{isAbsolute as XH,join as X1,resolve as UH}from"path";import d from"process";import{pipeline as JH}from"stream/promises";import{createGzip as AE}from"zlib";import U1 from"process";import n$ from"process";import qY from"process";import{existsSync as hY}from"fs";import{resolve as IU}from"path";import{existsSync as WH}from"fs";import{exec as _5}from"node:child_process";import HE from"node:fs";import Q5 from"node:os";import K$ from"node:path";import Nj from"node:process";import{promisify as D5}from"node:util";import E1 from"node:crypto";import v$ from"node:fs";import pU from"node:path";import{execSync as hE}from"node:child_process";import tY from"node:os";async function yE($,w,A={}){let Y=A.timeoutMs??120000,f=A.intervalMs??3000,X=$.split(".").slice(-2).join("."),U;try{let B=new WU,E=await B.resolveNs(X),j=(await Promise.all(E.map((T)=>B.resolve4(T).catch(()=>[])))).flat();if(j.length>0)U=new WU,U.setServers(j)}catch{}let W=Date.now()+Y,J=U??new WU;for(;;){try{if((await J.resolveTxt($)).some((B)=>B.join("")===w))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,f))}}class v1{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(v1.PATH_PREFIX);if(w===-1)return;let A=$.slice(w+v1.PATH_PREFIX.length);return this.get(A)}}function IY($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function _U($){return Buffer.from($,"base64url")}function ME($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function IE($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return WG("sha256").update(w).digest("base64url")}function CE($){let{protectedHeader:w,payload:A,privateKey:Y}=$,f=IY(JSON.stringify(w)),X=A===""?"":IY(JSON.stringify(A)),U=`${f}.${X}`,W=BG("sha256",Buffer.from(U),{key:Y,dsaEncoding:"ieee-p1363"});return{protected:f,payload:X,signature:IY(W)}}class QY{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=ME($.accountPublicKey),this.thumbprint=IE(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:A,useJwk:Y}=$,f={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(Y)f.jwk=this.jwk;else f.kid=this.requireKid();let X=CE({protectedHeader:f,payload:A,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(X)}),W=U.headers.get("replay-nonce");if(W)this.nonce=W;let J=U.headers.get("content-type")??"",B;if(J.includes("application/pem-certificate-chain")||J.startsWith("text/"))B=await U.text();else{let E=await U.text();B=E?JSON.parse(E):{}}if(U.status>=400){let E=B??{};throw new _Y(`ACME request to ${w} failed (HTTP ${U.status}): ${E.type??""} ${E.detail??""}`.trim(),E,U.status)}return{status:U.status,headers:U.headers,body:B,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),A={termsOfServiceAgreed:!0};if($.email)A.contact=[`mailto:${$.email}`];let Y=await this.signedPost({url:w.newAccount,payload:A,useJwk:!0});if(!Y.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=Y.location,this.accountKid}async newOrder($){let w=await this.directory(),A={identifiers:$.map((f)=>({type:"dns",value:f}))},Y=await this.signedPost({url:w.newOrder,payload:A});if(!Y.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:Y.body,orderUrl:Y.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return EG("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,f=Date.now()+A;while(Date.now()<f){let X=await this.getAuthorization($);if(X.status==="valid")return;if(X.status==="invalid"){let U=X.challenges.find((W)=>W.status==="invalid");throw new _Y(`Authorization for ${X.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await OB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,f=Date.now()+A;while(Date.now()<f){let X=await this.getOrder($);if(X.status==="valid"){if(!X.certificate)throw Error("ACME order is valid but has no certificate URL");return X.certificate}if(X.status==="invalid")throw Error(`ACME order ${$} became invalid`);await OB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let A=$.challenges.find((Y)=>Y.type===w);if(!A)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return A}}function VE($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],A=w[0];if(!A)return{certPem:`${$.trim()}
|
|
64
|
-
`,chainPem:""};let
|
|
65
|
-
`,
|
|
66
|
-
`);return{certPem:
|
|
67
|
-
`:""}}function OE($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function OB($){return new Promise((w)=>setTimeout(w,$))}function TG($){if($<128)return Buffer.from([$]);let w=[],A=$;while(A>0)w.unshift(A&255),A>>=8;return Buffer.from([128|w.length,...w])}function Ww($,w){return Buffer.concat([Buffer.from([$]),TG(w.length),w])}function _E($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=[],Y=$;while(Y>0)A.unshift(Y&255),Y>>=8;if(A[0]&128)A.unshift(0);w=Buffer.from(A)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return Ww(2,w)}function hw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let A=[40*w[0]+w[1]];for(let Y=2;Y<w.length;Y++){let f=w[Y],X=[f&127];f=Math.floor(f/128);while(f>0)X.unshift(f&127|128),f=Math.floor(f/128);A.push(...X)}return Ww(6,Buffer.from(A))}function X$(...$){return Ww(48,Buffer.concat($))}function QU(...$){return Ww(49,Buffer.concat($))}function DU($){return Ww(3,Buffer.concat([Buffer.from([0]),$]))}function QE($){return Ww(4,$)}function DE($){return Ww(12,Buffer.from($,"utf8"))}function kU($,w,A){let Y=128|(A?32:0)|$;return Ww(Y,w)}function NG($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let A=_U(w.x),Y=_U(w.y);if(A.length!==32||Y.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${A.length} y=${Y.length}`);return Buffer.concat([Buffer.from([4]),A,Y])}function kE($){let{domains:w,publicKey:A,privateKey:Y}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let f=X$(QU(X$(hw(HG),DE(w[0])))),X=X$(X$(hw(FG),hw(zG)),DU(NG(A))),U=w.map((G)=>kU(2,Buffer.from(G,"ascii"),!1)),W=X$(...U),J=X$(hw(RG),QE(W)),B=X$(J),E=X$(hw(KG),QU(B)),j=kU(0,E,!0),T=X$(_E(0),f,X,j),F=jG("sha256",T,Y),H=X$(hw(GG));return X$(T,H,DU(F))}function ZE($){return kE($).toString("base64url")}function hG($){if($){let{createPrivateKey:f,createPublicKey:X}=JG("node:crypto"),U=f($),W=X(U);return{privateKey:U,publicKey:W,pem:$}}let{privateKey:w,publicKey:A}=xE("ec",{namedCurve:"P-256"}),Y=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:A,pem:Y}}async function rU($){let{domains:w,method:A}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(A==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((j)=>j.startsWith("*."))&&A!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let Y=$.directoryUrl??($.staging===!1?LE:SE),f=hG($.accountKeyPem),X=new QY({directoryUrl:Y,accountKey:f.privateKey,accountPublicKey:f.publicKey});await X.newAccount({email:$.email});let{order:U,orderUrl:W}=await X.newOrder(w),J=$.http01Store??pY,B=[],E=[];try{for(let I of U.authorizations){let S=await X.getAuthorization(I);if(S.status==="valid")continue;let B0=QY.selectChallenge(S,A);if(A==="dns-01"){let V=OE(S.identifier.value),O=X.dns01TxtValue(B0.token);await $.dnsProvider.setTxt(V,O),B.push({name:V,value:O}),await yE(V,O,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else J.add(B0.token,X.keyAuthorization(B0.token)),E.push(B0.token);await X.notifyChallengeReady(B0.url),await X.pollAuthorization(I,{timeoutMs:$.timeoutMs})}let{privateKey:j,publicKey:T}=xE("ec",{namedCurve:"P-256"}),F=ZE({domains:w,publicKey:T,privateKey:j});await X.finalizeOrder(U.finalize,F);let H=await X.pollOrder(W,{timeoutMs:$.timeoutMs}),G=await X.downloadCertificate(H),{certPem:K,chainPem:R}=VE(G),N=R?`${K}${R}`:K,h=j.export({format:"pem",type:"pkcs8"}).toString(),y=new Date(new qG(K).validTo);return{certPem:K,keyPem:h,chainPem:R,fullChainPem:N,accountKeyPem:f.pem,notAfter:y}}finally{for(let{name:j,value:T}of B)await $.dnsProvider?.removeTxt(j,T).catch(()=>{});for(let j of E)J.remove(j)}}class bE{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!_B($))return!0;return QB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=_B(A)?QB(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class cE{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function jH($,w){this[$]=EH.bind(null,w)}class sU{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!DB($))return!0;return kB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=DB(A)?kB(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class oU{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function zH($,w={}){let A=Object.keys(w).sort().map((Y)=>`${Y}:${w[Y]}`).join("|");return A?`${$}:${A}`:$}function GH($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function HH($){return $.getStats().size*2}function eU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&e(w[0])&&"id"in w[0]&&w[0].id===3&&e(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(e(w)&&e($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(e($)&&"arr"in $&&Array.isArray($.arr)&&e(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&e(w[0])&&e($[0])){let Y=[...w];for(let f of $)if(e(f)&&"name"in f){if(!Y.find((X)=>e(X)&&("name"in X)&&X.name===f.name))Y.push(f)}else if(e(f)&&"path"in f){if(!Y.find((X)=>e(X)&&("path"in X)&&X.path===f.path))Y.push(f)}else if(!Y.some((X)=>iY(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!e(w)||!e($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(e(f)&&e(A[Y]))A[Y]=eU(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&e(f[0])&&e(A[Y][0])){let X=[...f];for(let U of A[Y])if(e(U)&&"name"in U){if(!X.find((W)=>e(W)&&("name"in W)&&W.name===U.name))X.push(U)}else if(e(U)&&"path"in U){if(!X.find((W)=>e(W)&&("path"in W)&&W.path===U.path))X.push(U)}else if(!X.some((W)=>iY(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function iY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!iY($[A],w[A]))return!1;return!0}if(e($)&&e(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!iY($[f],w[f]))return!1}return!0}return!1}function e($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function KH($,w){if(!iE($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return eU(w,Y)}catch{return null}}catch{return null}}async function RH({name:$="",cwd:w,defaultConfig:A}){let Y=w||xU.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=ZY(Y,`${U}${W}`),B=await KH(J,A);if(B!==null)return B}try{let U=ZY(Y,"package.json");if(iE(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return eU(A,W)}catch{}}}catch{}return A}function NH($,w={}){let A=kY.cwd();while(A.includes("storage"))A=PB(A,"..");let Y=PB(A,$||"");if(w?.relative)return _G(kY.cwd(),Y);return Y}async function qH(){try{let $=await RH({name:"clarity",defaultConfig:SY,cwd:kY.cwd(),endpoint:"",headers:{}});return{...SY,...$}}catch{return SY}}function f0(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hH(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c$<"u"){let $=c$.type;if($==="renderer"||$==="worker")return!1;return!!(c$.versions&&(c$.versions.node||c$.versions.bun))}return!1}class nE{async format($){let w=await hH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:$1.pid,hostname:w(),environment:$1.env.NODE_ENV||"development",platform:$1.platform,version:$1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:$1.env.NODE_ENV||$1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class bY{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($,w={}){this.name=$,this.config={...iU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new nE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...LY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...LY};return{...LY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:iU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let w=(async()=>{let Y,f=0,X=3,U=1000;while(f<X)try{try{try{await xG(this.config.logDirectory,uB.F_OK|uB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await PG(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Xw.from($);try{if(!zU(this.currentLogFile))await GU(this.currentLogFile,"",{mode:420});if(Y=cB(this.currentLogFile,"a",420),ZG(Y,W,{flag:"a"}),bB(Y),Y!==void 0)FU(Y),Y=void 0;if((await ow(this.currentLogFile)).size===0){if(await GU(this.currentLogFile,W,{flag:"w",mode:420}),(await ow(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{FU(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,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 ew(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 ew(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return ew(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(f0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return TU(16).toString("hex")}generateKey(){return TU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=TU(16),Y=QG("aes-256-gcm",w,A),f=Xw.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:Xw.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=vB(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Xw.from(Xw.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(f0())return;let $=await ow(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await EY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await ow(A).catch(()=>null))try{if(await nB(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await jY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await GU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await ow(A).catch(()=>null))await nB(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await EY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await jY(ew(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=iB($),Y=kG(w),f=vB();await iG(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),zU(this.currentLogFile))try{let $=cB(this.currentLogFile,"r+");bB($),FU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!f0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await EY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await jY(ew(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?p.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=L0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${p.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!f0()){let B=sE[$],E=this.options.showTags!==!1&&this.name?p.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:p.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:p.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
68
|
-
`);for(let F of
|
|
69
|
-
`;if(W)
|
|
70
|
-
`;
|
|
71
|
-
`,
|
|
72
|
-
`),
|
|
73
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
74
|
-
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(
|
|
75
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||f0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(f0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await EY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let f=ew(this.config.logDirectory,Y);if($.before)try{if((await ow(f)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${f}:`,X);continue}A.push(f)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await jY(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function CY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&l(w[0])&&"id"in w[0]&&w[0].id===3&&l(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(l(w)&&l($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(l($)&&"arr"in $&&Array.isArray($.arr)&&l(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&l(w[0])&&l($[0])){let Y=[...w];for(let f of $)if(l(f)&&"name"in f){if(!Y.find((X)=>l(X)&&("name"in X)&&X.name===f.name))Y.push(f)}else if(l(f)&&"path"in f){if(!Y.find((X)=>l(X)&&("path"in X)&&X.path===f.path))Y.push(f)}else if(!Y.some((X)=>cY(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!l(w)||!l($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(l(f)&&l(A[Y]))A[Y]=CY(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&l(f[0])&&l(A[Y][0])){let X=[...f];for(let U of A[Y])if(l(U)&&"name"in U){if(!X.find((W)=>l(W)&&("name"in W)&&W.name===U.name))X.push(U)}else if(l(U)&&"path"in U){if(!X.find((W)=>l(W)&&("path"in W)&&W.path===U.path))X.push(U)}else if(!X.some((W)=>cY(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function $8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:CY($,w);if(Array.isArray($))return A==="replace"?w:CY($,w);if(!l(w)||!l($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=CY(U,X);else if(l(X)&&l(U))Y[f]=$8(U,X,A);else Y[f]=X}return Y}function cY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!cY($[A],w[A]))return!1;return!0}if(l($)&&l(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!cY($[f],w[f]))return!1}return!0}return!1}function l($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function yY($,w,A="replace"){if(!PE($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return $8(w,f,A)}catch{return null}}catch{return null}}function yH($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((G)=>G.toUpperCase()).join("_")}`;if(A)O0.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let G=m1.env[F]||m1.env[H];if(G!==void 0){if(A)O0.info(`Using environment variable ${G?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(G);else if(typeof E==="boolean")J[B]=G.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(G);if(Array.isArray(K))J[B]=K;else J[B]=G.split(",").map((R)=>R.trim())}catch{J[B]=G.split(",").map((K)=>K.trim())}else J[B]=G}}}return J}return X(f)}async function MH({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?yH($,f,X):f,B=A||m1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)O0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],G=Array.from(new Set([B,P0(B,"config"),P0(B,".config"),Y?P0(B,Y):void 0].filter(Boolean)));for(let K of G){if(X)O0.info(`Searching for configuration in: ${K}`);let R=[P0(B,"config"),P0(B,".config")].concat(Y?[P0(B,Y)]:[]).includes(K)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let N of R)for(let h of E){let y=P0(K,`${N}${h}`),I=await yY(y,J,W);if(I!==null){if(X)O0.success(`Configuration loaded from: ${y}`);return I}}}if($){let K=P0(jU(),".config",$),R=["config",`${$}.config`];if(w)R.push(`${w}.config`);if(X)O0.info(`Checking user config directory: ${K}`);for(let N of R)for(let h of E){let y=P0(K,`${N}${h}`),I=await yY(y,J,W);if(I!==null){if(X)O0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let K=P0(jU(),".config"),R=[`.${$}.config`];if(w)R.push(`.${w}.config`);if(X)O0.info(`Checking user config directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=P0(K,`${N}${h}`),I=await yY(y,J,W);if(I!==null){if(X)O0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let K=jU(),R=[`.${$}.config`,`.${$}`];if(w)R.push(`.${w}.config`),R.push(`.${w}`);if(X)O0.info(`Checking user home directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=P0(K,`${N}${h}`),I=await yY(y,J,W);if(I!==null){if(X)O0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let K=P0(B,"package.json");if(PE(K)){let R=await import(K),N=R[$];if(!N&&w){if(N=R[w],N&&X)O0.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(X)O0.success(`Configuration loaded from package.json: ${N===R[$]?$:w}`);return $8(J,N,W)}catch(h){if(X)O0.warn("Failed to merge package.json config:",h)}}}catch(K){if(X)O0.warn("Failed to load package.json:",K)}if(X)O0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function IH($,w={}){let A=DY.cwd();while(A.includes("storage"))A=xB(A,"..");let Y=xB(A,$||"");if(w?.relative)return VG(DY.cwd(),Y);return Y}async function CH(){try{let $=await MH({name:"clarity",alias:"logging",defaultConfig:VY,cwd:DY.cwd()});return{...VY,...$||{}}}catch{return VY}}function z0(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function SH(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof u$<"u"){let $=u$.type;if($==="renderer"||$==="worker")return!1;return!!(u$.versions&&(u$.versions.node||u$.versions.bun))}return!1}class vE{async format($){let w=await SH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Y1.pid,hostname:w(),environment:Y1.env.NODE_ENV||"development",platform:Y1.platform,version:Y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Y1.env.NODE_ENV||Y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class uY{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($,w={}){this.name=$,this.config={...bU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new vE,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??m.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...OY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...OY};return{...OY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:bU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!z0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,f=0,X=3,U=1000;while(f<X)try{try{try{await vG(this.config.logDirectory,gB.F_OK|gB.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await mG(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P$.from($);try{if(!TY(this.currentLogFile))await RU(this.currentLogFile,"",{mode:420});if(Y=lB(this.currentLogFile,"a",420),nG(Y,W,{flag:"a"}),dB(Y),Y!==void 0)KU(Y),Y=void 0;if((await w1(this.currentLogFile)).size===0){if(await RU(this.currentLogFile,W,{flag:"w",mode:420}),(await w1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{KU(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,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 A1(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 A1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return A1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(z0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return HU(16).toString("hex")}generateKey(){return HU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=HU(16),Y=bG("aes-256-gcm",w,A),f=P$.isBuffer($)?$:P$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=P$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=pB(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(P$.from(P$.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(z0())return;if(!this.shouldWriteToFile())return;let $=await w1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await FY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await w1(A).catch(()=>null))try{if(await tB(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await zY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await RU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await w1(A).catch(()=>null))await tB(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await FY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await zY(A1(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=mB($),Y=uG(w),f=pB();await gG(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),TY(this.currentLogFile))try{let $=lB(this.currentLogFile,"r+");dB($),KU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!z0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await FY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await zY(A1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?x.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||z0())return!1;let $=typeof m.env.NO_COLOR<"u",w=m.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof m.stderr<"u"&&m.stderr.isTTY||typeof m.stdout<"u"&&m.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=m.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${x.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=x.underline(x.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>x.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>x.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>x.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>x.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>x.strikethrough(Y)),w}supportsHyperlinks(){if(z0())return!1;let $=m.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=m.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(dG(w)||w.startsWith("./")||w.startsWith("../"))w=lG(w);else return null;return TY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":oE[$],T=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:x.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:x.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
76
|
-
`);for(let
|
|
77
|
-
`;if(W)
|
|
78
|
-
`;if(
|
|
79
|
-
`);if(this[X==="warning"?"warn":X](
|
|
80
|
-
`,
|
|
81
|
-
`),
|
|
82
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
83
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
84
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
85
|
-
|
|
86
|
-
`;for(let
|
|
87
|
-
`,
|
|
88
|
-
`,
|
|
89
|
-
`,
|
|
90
|
-
|
|
91
|
-
`;return
|
|
92
|
-
|
|
93
|
-
`;
|
|
94
|
-
`,
|
|
95
|
-
`;for(let
|
|
96
|
-
`;return A}}function OH($,w){let A=rE("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function lE($,w,A={}){return gE($,w,A,new WeakMap)}function gE($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return tE($,w,f,Y);if(!J$(w)||!J$($))return w;return kH($,w,A,Y)}function tE($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return _H($,w);case"smart":return QH($,w,Y);default:return w}return w}function _H($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>PU(f,Y)))A.push(Y);return A}function QH($,w,A){if(w.length===0)return $;if($.length===0)return w;if(J$(w[0])&&J$($[0]))return DH($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function DH($,w,A){let Y=[...w];for(let f of $){if(!J$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((J)=>J$(J)&&(W in J)&&J[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function kH($,w,A,Y){let f=w;if(J$(f)&&Y.has(f))return Y.get(f);let X={...$};if(J$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(J$(W)&&J$(J))X[U]=gE(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=tE(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function w8($,w,A="replace"){return lE($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function PU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!PU($[A],w[A]))return!1;return!0}if(J$($)&&J$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!PU($[f],w[f]))return!1}return!0}return!1}function J$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class sY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=W1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!HY($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new d1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new d1($,Error("Configuration must export a valid object"),"unknown");let H={config:w8(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)W1.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?Jw.configLoad($,B):Jw.configLoad($,Error(String(B)))}};if(U)return t1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(NU(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return mE(async()=>{return HY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!HY($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=NU($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=NU($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){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((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!HY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class A8{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await t1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!tG(w))throw new l1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new l1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.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:$j},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class Y8{fileLoader=new sY;envProcessor=new aY;validator=new A8;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)R$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw R$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||yw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(i0(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Jw.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?u1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)R$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)R$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?u1($,A,f):A,W=[i0(sw(),".config",$),i0(sw(),".config"),sw()];for(let J of W){if(f)R$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)R$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?u1($,Y,X):Y;try{let J=i0(A,"package.json");if(!ZU(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)R$.success(`Configuration loaded from package.json: ${j}`);return{config:w8(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)R$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:u1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Jw.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return W1.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);W1.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,i0($,"config"),i0($,".config"),w?i0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(i0(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[i0(sw(),".config",$),i0(sw(),".config"),sw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function YE($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||A}async function ZH($){return m$.loadConfig({...$,__strictErrorHandling:!0})}async function pE($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await m$.loadConfig($);else Y=await m$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)R$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let U=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await m$.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function xH($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await m$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&YE(A)))return(await m$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await m$.loadConfig({...$,cwd:$.cwd||yw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&YE(w)))return(await m$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function PH($,w,A="replace"){let Y=new sY;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function u1($,w,A=!1){let Y=new aY,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=yw.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function iH($){let w=i0(yw.cwd(),$.configDir),A=i0(yw.cwd(),$.generatedDir),Y=i0(A,"config-types.ts");if(!ZU(ZB(Y)))IG(ZB(Y),{recursive:!0,mode:511});let f=ZU(w)?CG(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${T5}
|
|
97
|
-
export type ConfigNames = ${
|
|
98
|
-
`;
|
|
99
|
-
${
|
|
42
|
+
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function i6($,w={}){let Y=jA.cwd();while(Y.includes("storage"))Y=YB(Y,"..");let A=YB(Y,$||"");if(w?.relative)return CG(jA.cwd(),A);return A}function K0(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function v6(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z$<"u"){let $=Z$.type;if($==="renderer"||$==="worker")return!1;return!!(Z$.versions&&(Z$.versions.node||Z$.versions.bun))}return!1}class gB{async format($){let w=await v6(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:tw.pid,hostname:w(),environment:tw.env.NODE_ENV||"development",platform:tw.platform,version:tw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tw.env.NODE_ENV||tw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yA{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($,w={}){this.name=$,this.config={...HA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new gB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Y8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Y8};return{...Y8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:HA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!K0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await OG(this.config.logDirectory,JB.F_OK|JB.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await SG(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:S$.from($);try{if(!tY(this.currentLogFile))await sX(this.currentLogFile,"",{mode:420});if(U=XB(this.currentLogFile,"a",420),QG(U,f,{flag:"a"}),UB(U),U!==void 0)aX(U),U=void 0;if((await nw(this.currentLogFile)).size===0){if(await sX(this.currentLogFile,f,{flag:"w",mode:420}),(await nw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{aX(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,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 pw(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 pw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return pw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(K0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return rX(16).toString("hex")}generateKey(){return rX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=rX(16),A=hG("aes-256-gcm",w,Y),U=S$.isBuffer($)?$:S$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=S$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=WB(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(S$.from(S$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(K0())return;if(!this.shouldWriteToFile())return;let $=await nw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await rY(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await nw(Y).catch(()=>null))try{if(await fB(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await aY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await sX(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await nw(Y).catch(()=>null))await fB(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await rY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await aY(pw(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=AB($),A=LG(w),U=WB();await DG(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),tY(this.currentLogFile))try{let $=XB(this.currentLogFile,"r+");UB($),aX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!K0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await rY(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await aY(pw(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||K0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=k.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${u.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=u.underline(u.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),w}supportsHyperlinks(){if(K0())return!1;let $=k.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=k.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(_G(w)||w.startsWith("./")||w.startsWith("../"))w=kG(w);else return null;return tY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":n6[$],G=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:u.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:u.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
43
|
+
`);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:u.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!K0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
44
|
+
`;if(W)j+=`${W}
|
|
45
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!K0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!K0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!K0()&&k.stdout.isTTY)k.stdout.write(`
|
|
46
|
+
`);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!K0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:Y,message:`${u.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
47
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":u.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!K0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new yA(w,{...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(Y),Y}createReadStream(){if(K0())throw Error("createReadStream is not supported in browser environments");if(!tY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return AB(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=S$.isBuffer($)?$:S$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=VG("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=S$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return K0()}isServerMode(){return!K0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}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($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
48
|
+
`),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(j),showTimestamp:!1}))}else if(!K0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
|
|
49
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(K0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${u.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();k.stdin.removeListener("data",Y);try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!1)}catch{}k.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!0)}catch{}k.stdin.resume(),k.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(Y=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let G=w[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<w.length)Y+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${B}${f} ${u.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
50
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!k.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=u.green("━".repeat(A)),J=u.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?u.green("✓"):u.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=k.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,k.stdout.write($.lastRenderedLine),w)k.stdout.write(`
|
|
51
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||K0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(K0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await rY(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=pw(this.config.logDirectory,A);if($.before)try{if((await nw(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await aY(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function p6($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}class h8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return T8.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=oY.env[f]||(B?oY.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=oY.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof C8)throw z;throw aw.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw aw.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(oY.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
52
|
+
|
|
53
|
+
`;for(let A of $)Y+=`${A.key}
|
|
54
|
+
`,Y+=` Type: ${A.type}
|
|
55
|
+
`,Y+=` Description: ${A.description}
|
|
56
|
+
`,Y+=` Example: ${A.example}
|
|
57
|
+
|
|
58
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
59
|
+
|
|
60
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
61
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
62
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
63
|
+
`;return Y}}function t6($,w,Y={}){return oB($,w,Y,new WeakMap)}function oB($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return eB($,w,U,A);if(!A$(w)||!A$($))return w;return o6($,w,Y,A)}function eB($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return r6($,w);case"smart":return a6($,w,A);default:return w}return w}function r6($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>K8(U,A)))Y.push(A);return Y}function a6($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(A$(w[0])&&A$($[0]))return s6($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function s6($,w,Y){let A=[...w];for(let U of $){if(!A$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((B)=>A$(B)&&(W in B)&&B[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function o6($,w,Y,A){let U=w;if(A$(U)&&A.has(U))return A.get(U);let X={...$};if(A$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(A$(W)&&A$(f))X[J]=oB(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=eB(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function $j($,w,Y="replace"){return t6($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function K8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!K8($[Y],w[Y]))return!1;return!0}if(A$($)&&A$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!K8($[U],w[U]))return!1}return!0}return!1}function A$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class wj{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=JA.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!eY($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new NA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new NA($,Error("Configuration must export a valid object"),"unknown");let H={config:$j(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)JA.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?aw.configLoad($,B):aw.configLoad($,Error(String(B)))}};if(J)return T8.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(A8(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of A){if(!X)continue;if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)Y.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let U=new Set;return Y.filter((X)=>{if(!X||U.has(X))return!1;return U.add(X),!0})}checkFileAccess($){return p6(async()=>{return eY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!eY($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=A8($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=A8($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){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((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!eY($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class Yj{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await T8.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!e6(w))throw new qA(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new qA(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.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:$E},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function wE($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class Aj{fileLoader=new wj;envProcessor=new h8;validator=new Yj;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)_$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let f=Date.now()-w;throw _$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||RA.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(w$(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw aw.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${wE(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?$A($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)_$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)_$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?$A($,Y,U):Y,W=[w$(uw(),".config",$),w$(uw(),".config"),uw()];for(let f of W){if(U)_$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)_$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?$A($,A,X):A;try{let f=w$(Y,"package.json");if(!t5(f))return null;let B={};try{B=JSON.parse(r5(f,"utf8"))}catch(G){if(X)_$.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let j=B[$],z=$;if(!j&&w){let G=Array.isArray(w)?w:[w];for(let F of G){if(!F)continue;if(B[F]){j=B[F],z=F;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)_$.success(`Configuration loaded from package.json: ${z}`);return{config:$j(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)_$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:$A($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw aw.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return JA.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);JA.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,w$($,"config"),w$($,".config"),w?w$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(w$(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[w$(uw(),".config",$),w$(uw(),".config"),uw()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function $A($,w,Y=!1){let A=new h8,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=RA.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}var JA,T8,ZG,xG=($)=>$,bG=($,w)=>{for(var Y in w)ZG($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:PG.bind(w,Y)})},uG=($,w)=>()=>($&&(w=$($=0)),w),VB,xB,rw,e1,PB,z6,F6,jB,YA,f8,L0,r,G6,zB,E6,FB,K6,T6,oX,H6,GB,EB,eX,N6,q6,R6,M6,AA,bB,I6,Q0,y6,C6,KB,UA,W8,E0,x,h6,TB,V6,HB,L6,Q6,$8,O6,NB,qB,S6,w8,_6,k6,D6,Z6,x6,XA,uB,P6,b6="0.15.6",a0,KA,s1,B8,j8,TA,z8,F8,o1,G8,E8,Jw,iB,cB,F$,x$,vB,mB,u6,c6,dB,HA,KI,I0,u,TI,m6,HI,d6,NI,qI,RB,RI,g6,l6,MI,MB,II,yI,CI,hI,VI,Y8,n6,LI,G$,lB,NA,nB,pB,C8,tB,rB,qA,aB,sB,aw,$E,_$,kI,DI,ZI;var V8=j0(()=>{JA=new IB,T8=new yB,ZG=Object.defineProperty;VB={};bG(VB,{withErrorRecovery:()=>OB,tryLoadConfig:()=>f6,loadConfigWithResult:()=>X6,loadConfig:()=>ZB,isRetryableError:()=>eG,isConfigNotFoundError:()=>oG,isBunfigError:()=>SB,globalPerformanceMonitor:()=>e1,globalCache:()=>rw,getEnvOrDefault:()=>$6,generateConfigTypes:()=>W6,defaultGeneratedDir:()=>mB,defaultConfigDir:()=>vB,deepMergeWithArrayStrategy:()=>M8,deepMerge:()=>_B,createLibraryConfig:()=>B6,config:()=>J6,bunfigPlugin:()=>j6,applyEnvVarsToConfig:()=>r1,TypeGenerationError:()=>F8,SchemaValidationError:()=>o1,PluginError:()=>E8,PerformanceMonitor:()=>N8,FileSystemError:()=>z8,ErrorFactory:()=>Jw,EnvVarError:()=>TA,EnvProcessor:()=>MA,ConfigValidator:()=>I8,ConfigValidationError:()=>B8,ConfigNotFoundError:()=>KA,ConfigMergeError:()=>j8,ConfigLoader:()=>y8,ConfigLoadError:()=>s1,ConfigFileLoader:()=>IA,ConfigCache:()=>H8,CacheUtils:()=>PB,BunfigError:()=>a0,BrowserConfigError:()=>G8,ArrayMergeStrategies:()=>iB});u6=uG(async()=>{xB=import.meta.require,rw=new H8,e1=new N8,PB={createKey:iG,isEquivalent:cG,estimateMemoryUsage:vG},z6=BA(X8.cwd(),"config"),F6=BA(X8.cwd(),"src/generated"),jB=WA.env.CLARITY_LOG_DIR||wG(gG(),"logs"),YA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:jB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},f8=await lG(),L0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},r=L0,G6=L0.red,zB=L0.green,E6=L0.yellow,FB=L0.blue,K6=L0.magenta,T6=L0.cyan,oX=L0.white,H6=L0.gray,GB=L0.bgRed,EB=L0.bgYellow,eX=L0.bold,N6=L0.dim,q6=L0.italic,R6=L0.underline,M6=L0.reset,AA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bB={debug:"\uD83D\uDD0D",info:FB("ℹ"),success:zB("✓"),warning:EB(oX(eX(" WARN "))),error:GB(oX(eX(" ERROR ")))},I6=new FA("stacks"),Q0=new FA("bunfig",{showTags:!0}),y6=b0(a1.cwd(),"config"),C6=b0(a1.cwd(),"src/generated"),KB=fA.env.CLARITY_LOG_DIR||e5(rG(),"logs"),UA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:KB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},W8=await aG(),E0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},x=E0,h6=E0.red,TB=E0.green,V6=E0.yellow,HB=E0.blue,L6=E0.magenta,Q6=E0.cyan,$8=E0.white,O6=E0.gray,NB=E0.bgRed,qB=E0.bgYellow,S6=E0.bgGray,w8=E0.bold,_6=E0.dim,k6=E0.italic,D6=E0.underline,Z6=E0.strikethrough,x6=E0.reset,XA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uB={debug:"\uD83D\uDD0D",info:HB("ℹ"),success:TB("✓"),warning:qB($8(w8(" WARN "))),error:NB($8(w8(" ERROR ")))},P6=new EA("stacks"),a0=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},KA=class extends a0{code="CONFIG_NOT_FOUND";constructor(w,Y,A){let U=A?` or alias "${A}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},s1=class extends a0{code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},B8=class extends a0{code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},j8=class extends a0{code="CONFIG_MERGE_ERROR";constructor(w,Y,A,U){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:U,originalError:A.name,originalMessage:A.message});this.cause=A}},TA=class extends a0{code="ENV_VAR_ERROR";constructor(w,Y,A,U){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:U})}},z8=class extends a0{code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},F8=class extends a0{code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},o1=class extends a0{code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},G8=class extends a0{code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,U){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:U})}},E8=class extends a0{code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Jw={configNotFound($,w,Y){return new KA($,w,Y)},configLoad($,w,Y){return new s1($,w,Y)},configValidation($,w,Y){return new B8($,w,Y)},configMerge($,w,Y,A){return new j8($,w,Y,A)},envVar($,w,Y,A){return new TA($,w,Y,A)},fileSystem($,w,Y){return new z8($,w,Y)},typeGeneration($,w,Y){return new F8($,w,Y)},schemaValidation($,w,Y){return new o1($,w,Y)},browserConfig($,w,Y,A){return new G8($,w,Y,A)},plugin($,w,Y){return new E8($,w,Y)}},iB={replace:"replace",concat:"concat",smart:"smart"},cB=/^https?:\/\//,F$=new EA("bunfig",{showTags:!0}),x$=new y8,vB=u0(Cw.cwd(),"config"),mB=u0(Cw.cwd(),"src/generated")});c6=jA.env.CLARITY_LOG_DIR||yG(i6(),"logs"),dB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:c6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},HA={...dB},KI=(async()=>{try{let{loadConfig:$}=await u6().then(()=>VB),w=await $({name:"clarity",alias:"logging",defaultConfig:dB,cwd:jA.cwd()});if(w)Object.assign(HA,w)}catch{}return HA})();I0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},u=I0,TI=I0.red,m6=I0.green,HI=I0.yellow,d6=I0.blue,NI=I0.magenta,qI=I0.cyan,RB=I0.white,RI=I0.gray,g6=I0.bgRed,l6=I0.bgYellow,MI=I0.bgGray,MB=I0.bold,II=I0.dim,yI=I0.italic,CI=I0.underline,hI=I0.strikethrough,VI=I0.reset,Y8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},n6={debug:"\uD83D\uDD0D",info:d6("ℹ"),success:m6("✓"),warning:l6(RB(MB(" WARN "))),error:g6(RB(MB(" ERROR ")))};LI=new yA("stacks");G$=class G$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};lB=class lB extends G${code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],U="";if(A.length===1)U=` or alias "${A[0]}"`;else if(A.length>1)U=` or aliases ${A.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${U} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};NA=class NA extends G${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};nB=class nB extends G${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};pB=class pB extends G${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};C8=class C8 extends G${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};tB=class tB extends G${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};rB=class rB extends G${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};qA=class qA extends G${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};aB=class aB extends G${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};sB=class sB extends G${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};aw={configNotFound($,w,Y){return new lB($,w,Y)},configLoad($,w,Y){return new NA($,w,Y)},configValidation($,w,Y){return new nB($,w,Y)},configMerge($,w,Y,A){return new pB($,w,Y,A)},envVar($,w,Y,A){return new C8($,w,Y,A)},fileSystem($,w,Y){return new tB($,w,Y)},typeGeneration($,w,Y){return new rB($,w,Y)},schemaValidation($,w,Y){return new qA($,w,Y)},browserConfig($,w,Y,A){return new aB($,w,Y,A)},plugin($,w,Y){return new sB($,w,Y)}};$E=/^https?:\/\//;_$=new yA("bunfig",{showTags:!0});kI=new Aj;DI=w$(RA.cwd(),"config"),ZI=w$(RA.cwd(),"src/generated")});var R;var fw=j0(()=>{R={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as UE}from"node:module";import{Resolver as O8}from"node:dns/promises";import{createHash as JE,sign as fE}from"node:crypto";import{createHash as WE}from"node:crypto";import{sign as BE}from"node:crypto";import{generateKeyPairSync as Wz,X509Certificate as NE}from"node:crypto";import S8 from"node:os";import _8 from"node:path";import{existsSync as Xj,statSync as Jj}from"fs";import{existsSync as RE,mkdirSync as oI,readdirSync as eI,readFileSync as ME,writeFileSync as $4}from"fs";import{homedir as ow}from"os";import{dirname as A4,resolve as X$}from"path";import BU from"process";import{existsSync as fj,statSync as Wj}from"fs";import{existsSync as wJ,mkdirSync as IE,readdirSync as yE,writeFileSync as CE}from"fs";import{homedir as ew}from"os";import{dirname as Bj,resolve as c0}from"path";import Vw from"process";import{join as hE,relative as VE,resolve as jj}from"path";import nA from"process";import{existsSync as Bz,mkdirSync as G4,readdirSync as E4,writeFileSync as K4}from"fs";import{homedir as k8}from"os";import{dirname as N4,resolve as i0}from"path";import UY from"process";import{join as LE,relative as QE,resolve as zj}from"path";import pA from"process";import{existsSync as jz,mkdirSync as y4,readdirSync as C4,writeFileSync as h4}from"fs";import{dirname as L4,resolve as tA}from"path";import YJ from"process";import{Buffer as Ww}from"buffer";import{createCipheriv as OE,createDecipheriv as SE,randomBytes as D8}from"crypto";import{closeSync as Z8,createReadStream as Fj,createWriteStream as _E,existsSync as x8,fsyncSync as Gj,openSync as Ej,writeFileSync as kE}from"fs";import{access as DE,constants as Kj,mkdir as ZE,readdir as CA,rename as Tj,stat as $1,unlink as hA,writeFile as P8}from"fs/promises";import{join as w1}from"path";import O0 from"process";import{pipeline as xE}from"stream/promises";import{createGzip as Hj}from"zlib";import Y1 from"process";import i$ from"process";import{Buffer as P$}from"buffer";import{createCipheriv as PE,createDecipheriv as bE,randomBytes as b8}from"crypto";import{closeSync as u8,createReadStream as Nj,createWriteStream as uE,existsSync as VA,fsyncSync as qj,openSync as Rj,writeFileSync as iE}from"fs";import{access as cE,constants as Mj,mkdir as vE,readdir as LA,rename as Ij,stat as A1,unlink as QA,writeFile as i8}from"fs/promises";import{isAbsolute as mE,join as U1,resolve as dE}from"path";import d from"process";import{pipeline as gE}from"stream/promises";import{createGzip as yj}from"zlib";import X1 from"process";import c$ from"process";import OA from"process";import{existsSync as SA}from"fs";import{resolve as c8}from"path";import{existsSync as lE}from"fs";import{existsSync as nE,readdirSync as pE}from"fs";import{extname as v8,resolve as Cj}from"path";import tE from"process";import{join as rE,relative as aE,resolve as hj}from"path";import rA from"process";import{Buffer as b$}from"buffer";import{createCipheriv as sE,createDecipheriv as oE,randomBytes as m8}from"crypto";import{closeSync as d8,createReadStream as Vj,createWriteStream as eE,existsSync as _A,fsyncSync as Lj,openSync as Qj,writeFileSync as $K}from"fs";import{access as wK,constants as Oj,mkdir as YK,readdir as kA,rename as Sj,stat as J1,unlink as DA,writeFile as g8}from"fs/promises";import{isAbsolute as AK,join as f1,resolve as UK}from"path";import g from"process";import{pipeline as XK}from"stream/promises";import{createGzip as _j}from"zlib";import W1 from"process";import v$ from"process";import ZA from"process";import{existsSync as xA}from"fs";import{resolve as l8}from"path";import{existsSync as JK}from"fs";import{exec as Q7}from"node:child_process";import GJ from"node:fs";import O7 from"node:os";import E$ from"node:path";import nz from"node:process";import{promisify as S7}from"node:util";import F1 from"node:crypto";import m$ from"node:fs";import TJ from"node:path";import e7 from"node:crypto";import{execSync as YT}from"node:child_process";import fU from"node:os";async function rj($,w,Y={}){let A=Y.timeoutMs??120000,U=Y.intervalMs??3000,X=$.split(".").slice(-2).join("."),J;try{let B=new O8,j=await B.resolveNs(X),z=(await Promise.all(j.map((G)=>B.resolve4(G).catch(()=>[])))).flat();if(z.length>0)J=new O8,J.setServers(z)}catch{}let W=Date.now()+A,f=J??new O8;for(;;){try{if((await f.resolveTxt($)).some((B)=>B.join("")===w))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,U))}}class AY{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(AY.PATH_PREFIX);if(w===-1)return;let Y=$.slice(w+AY.PATH_PREFIX.length);return this.get(Y)}}function uA($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function s8($){return Buffer.from($,"base64url")}function aj($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function sj($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return JE("sha256").update(w).digest("base64url")}function oj($){let{protectedHeader:w,payload:Y,privateKey:A}=$,U=uA(JSON.stringify(w)),X=Y===""?"":uA(JSON.stringify(Y)),J=`${U}.${X}`,W=fE("sha256",Buffer.from(J),{key:A,dsaEncoding:"ieee-p1363"});return{protected:U,payload:X,signature:uA(W)}}class lA{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=aj($.accountPublicKey),this.thumbprint=sj(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:Y,useJwk:A}=$,U={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(A)U.jwk=this.jwk;else U.kid=this.requireKid();let X=oj({protectedHeader:U,payload:Y,privateKey:this.accountKey}),J=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(X)}),W=J.headers.get("replay-nonce");if(W)this.nonce=W;let f=J.headers.get("content-type")??"",B;if(f.includes("application/pem-certificate-chain")||f.startsWith("text/"))B=await J.text();else{let j=await J.text();B=j?JSON.parse(j):{}}if(J.status>=400){let j=B??{};throw new gA(`ACME request to ${w} failed (HTTP ${J.status}): ${j.type??""} ${j.detail??""}`.trim(),j,J.status)}return{status:J.status,headers:J.headers,body:B,location:J.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),Y={termsOfServiceAgreed:!0};if($.email)Y.contact=[`mailto:${$.email}`];let A=await this.signedPost({url:w.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder($){let w=await this.directory(),Y={identifiers:$.map((U)=>({type:"dns",value:U}))},A=await this.signedPost({url:w.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return WE("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,U=Date.now()+Y;while(Date.now()<U){let X=await this.getAuthorization($);if(X.status==="valid")return;if(X.status==="invalid"){let J=X.challenges.find((W)=>W.status==="invalid");throw new gA(`Authorization for ${X.identifier.value} became invalid: ${J?.error?.detail??"unknown reason"}`,J?.error??{},0)}await Uj(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,U=Date.now()+Y;while(Date.now()<U){let X=await this.getOrder($);if(X.status==="valid"){if(!X.certificate)throw Error("ACME order is valid but has no certificate URL");return X.certificate}if(X.status==="invalid")throw Error(`ACME order ${$} became invalid`);await Uj(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let Y=$.challenges.find((A)=>A.type===w);if(!Y)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return Y}}function wz($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=w[0];if(!Y)return{certPem:`${$.trim()}
|
|
64
|
+
`,chainPem:""};let A=`${Y.trim()}
|
|
65
|
+
`,U=w.slice(1).map((X)=>X.trim()).join(`
|
|
66
|
+
`);return{certPem:A,chainPem:U?`${U}
|
|
67
|
+
`:""}}function Yz($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function Uj($){return new Promise((w)=>setTimeout(w,$))}function jE($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function zw($,w){return Buffer.concat([Buffer.from([$]),jE(w.length),w])}function Az($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=[],A=$;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);w=Buffer.from(Y)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return zw(2,w)}function hw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let Y=[40*w[0]+w[1]];for(let A=2;A<w.length;A++){let U=w[A],X=[U&127];U=Math.floor(U/128);while(U>0)X.unshift(U&127|128),U=Math.floor(U/128);Y.push(...X)}return zw(6,Buffer.from(Y))}function U$(...$){return zw(48,Buffer.concat($))}function o8(...$){return zw(49,Buffer.concat($))}function e8($){return zw(3,Buffer.concat([Buffer.from([0]),$]))}function Uz($){return zw(4,$)}function Xz($){return zw(12,Buffer.from($,"utf8"))}function $J($,w,Y){let A=128|(Y?32:0)|$;return zw(A,w)}function HE($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let Y=s8(w.x),A=s8(w.y);if(Y.length!==32||A.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${Y.length} y=${A.length}`);return Buffer.concat([Buffer.from([4]),Y,A])}function Jz($){let{domains:w,publicKey:Y,privateKey:A}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let U=U$(o8(U$(hw(EE),Xz(w[0])))),X=U$(U$(hw(zE),hw(FE)),e8(HE(Y))),J=w.map((K)=>$J(2,Buffer.from(K,"ascii"),!1)),W=U$(...J),f=U$(hw(TE),Uz(W)),B=U$(f),j=U$(hw(KE),o8(B)),z=$J(0,j,!0),G=U$(Az(0),U,X,z),F=BE("sha256",G,A),T=U$(hw(GE));return U$(G,T,e8(F))}function fz($){return Jz($).toString("base64url")}function qE($){if($){let{createPrivateKey:U,createPublicKey:X}=XE("node:crypto"),J=U($),W=X(J);return{privateKey:J,publicKey:W,pem:$}}let{privateKey:w,publicKey:Y}=Wz("ec",{namedCurve:"P-256"}),A=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:Y,pem:A}}async function HJ($){let{domains:w,method:Y}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((z)=>z.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=$.directoryUrl??($.staging===!1?$z:ej),U=qE($.accountKeyPem),X=new lA({directoryUrl:A,accountKey:U.privateKey,accountPublicKey:U.publicKey});await X.newAccount({email:$.email});let{order:J,orderUrl:W}=await X.newOrder(w),f=$.http01Store??WU,B=[],j=[];try{for(let N of J.authorizations){let C=await X.getAuthorization(N);if(C.status==="valid")continue;let O=lA.selectChallenge(C,Y);if(Y==="dns-01"){let p=Yz(C.identifier.value),x0=X.dns01TxtValue(O.token);await $.dnsProvider.setTxt(p,x0),B.push({name:p,value:x0}),await rj(p,x0,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else f.add(O.token,X.keyAuthorization(O.token)),j.push(O.token);await X.notifyChallengeReady(O.url),await X.pollAuthorization(N,{timeoutMs:$.timeoutMs})}let{privateKey:z,publicKey:G}=Wz("ec",{namedCurve:"P-256"}),F=fz({domains:w,publicKey:G,privateKey:z});await X.finalizeOrder(J.finalize,F);let T=await X.pollOrder(W,{timeoutMs:$.timeoutMs}),K=await X.downloadCertificate(T),{certPem:H,chainPem:q}=wz(K),M=q?`${H}${q}`:H,I=z.export({format:"pem",type:"pkcs8"}).toString(),h=new Date(new NE(H).validTo);return{certPem:H,keyPem:I,chainPem:q,fullChainPem:M,accountKeyPem:U.pem,notAfter:h}}finally{for(let{name:z,value:G}of B)await $.dnsProvider?.removeTxt(z,G).catch(()=>{});for(let z of j)f.remove(z)}}class zz{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!Xj($))return!0;return Jj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=Xj(Y)?Jj(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Fz{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function BK($,w){this[$]=WK.bind(null,w)}class qJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!fj($))return!0;return Wj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=fj(Y)?Wj(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class RJ{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function FK($,w={}){let Y=Object.keys(w).sort().map((A)=>`${A}:${w[A]}`).join("|");return Y?`${$}:${Y}`:$}function GK($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function EK($){return $.getStats().size*2}function MJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let A=[...w];for(let U of $)if($0(U)&&"name"in U){if(!A.find((X)=>$0(X)&&("name"in X)&&X.name===U.name))A.push(U)}else if($0(U)&&"path"in U){if(!A.find((X)=>$0(X)&&("path"in X)&&X.path===U.path))A.push(U)}else if(!A.some((X)=>sA(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!$0(w)||!$0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if($0(U)&&$0(Y[A]))Y[A]=MJ(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&$0(U[0])&&$0(Y[A][0])){let X=[...U];for(let J of Y[A])if($0(J)&&"name"in J){if(!X.find((W)=>$0(W)&&("name"in W)&&W.name===J.name))X.push(J)}else if($0(J)&&"path"in J){if(!X.find((W)=>$0(W)&&("path"in W)&&W.path===J.path))X.push(J)}else if(!X.some((W)=>sA(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function sA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!sA($[Y],w[Y]))return!1;return!0}if($0($)&&$0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!sA($[U],w[U]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function KK($,w){if(!jz($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return MJ(w,A)}catch{return null}}catch{return null}}async function TK({name:$="",cwd:w,defaultConfig:Y}){let A=w||YJ.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let J of X)for(let W of U){let f=tA(A,`${J}${W}`),B=await KK(f,Y);if(B!==null)return B}try{let J=tA(A,"package.json");if(jz(J)){let W=(await import(J))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return MJ(Y,W)}catch{}}}catch{}return Y}function HK($,w={}){let Y=pA.cwd();while(Y.includes("storage"))Y=zj(Y,"..");let A=zj(Y,$||"");if(w?.relative)return QE(pA.cwd(),A);return A}async function NK(){try{let $=await TK({name:"clarity",defaultConfig:cA,cwd:pA.cwd(),endpoint:"",headers:{}});return{...cA,...$}}catch{return cA}}function X0(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function qK(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof i$<"u"){let $=i$.type;if($==="renderer"||$==="worker")return!1;return!!(i$.versions&&(i$.versions.node||i$.versions.bun))}return!1}class Ez{async format($){let w=await qK(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Y1.pid,hostname:w(),environment:Y1.env.NODE_ENV||"development",platform:Y1.platform,version:Y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Y1.env.NODE_ENV||Y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oA{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($,w={}){this.name=$,this.config={...UJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Ez,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...vA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...vA};return{...vA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:UJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let w=(async()=>{let A,U=0,X=3,J=1000;while(U<X)try{try{try{await DE(this.config.logDirectory,Kj.F_OK|Kj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await ZE(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Ww.from($);try{if(!x8(this.currentLogFile))await P8(this.currentLogFile,"",{mode:420});if(A=Ej(this.currentLogFile,"a",420),kE(A,W,{flag:"a"}),Gj(A),A!==void 0)Z8(A),A=void 0;if((await $1(this.currentLogFile)).size===0){if(await P8(this.currentLogFile,W,{flag:"w",mode:420}),(await $1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<X-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${X}:`,j);let z=J*2**U;await new Promise((G)=>setTimeout(G,z)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{Z8(A)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(W){if(U===X-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}U++;let f=J*2**(U-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,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 w1(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 w1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return w1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(X0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,J],[,W])=>W.createdAt.getTime()-J.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,U);if(A.length>X)for(let[J]of A.slice(X))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return D8(16).toString("hex")}generateKey(){return D8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=D8(16),A=OE("aes-256-gcm",w,Y),U=Ww.concat([A.update($,"utf8"),A.final()]),X=A.getAuthTag();return{encrypted:Ww.concat([Y,U,X]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Hj(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(Ww.from(Ww.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(X0())return;let $=await $1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await CA(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await $1(Y).catch(()=>null))try{if(await Tj(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await hA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await P8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await $1(Y).catch(()=>null))await Tj(Y,X)}if(this.currentLogFile=A,w.maxFiles){let U=(await CA(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,J)=>J.localeCompare(X));for(let X of U.slice(w.maxFiles))await hA(w1(this.config.logDirectory,X))}}}async compressLogFile($,w){let Y=Fj($),A=_E(w),U=Hj();await xE(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),x8(this.currentLogFile))try{let $=Ej(this.currentLogFile,"r+");Gj($),Z8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!X0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await CA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await hA(w1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?a.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=O0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${a.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);if(this.fancy&&!X0()){let B=Cz[$],j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:a.gray(J),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:a.green(J),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z),W){let G=W.split(`
|
|
68
|
+
`);for(let F of G)if(F.trim()&&!F.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:a.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!X0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let f=`${X} ${this.environment}.${$.toUpperCase()}: ${J}
|
|
69
|
+
`;if(W)f+=`${W}
|
|
70
|
+
`;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!X0()){let Y=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:a.blue("◐"),tag:Y,message:`${a.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),f=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)f+=` ${JSON.stringify(Y)}`;if(f+=`
|
|
71
|
+
`,f=f.replace(this.ANSI_PATTERN,""),this.fancy&&!X0()){let B=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:a.green("✓"),tag:B,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!X0())console.error(f.trim());await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new oA(w,{...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(Y),Y}createReadStream(){if(X0())throw Error("createReadStream is not supported in browser environments");if(!x8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Fj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Ww.isBuffer($)?$:Ww.from($,"base64"),U=A.slice(0,16),X=A.slice(-16),J=A.slice(16,-16),W=SE("aes-256-gcm",Y,U);return W.setAuthTag(X),Ww.concat([W.update(J),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return X0()}isServerMode(){return!X0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}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($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!X0()){let X=$.split(`
|
|
72
|
+
`),J=Math.max(...X.map((j)=>j.length))+2,W=`┌${"─".repeat(J)}┐`,f=`└${"─".repeat(J)}┘`,B=X.map((j)=>{let z=" ".repeat(J-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:a.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(f),showTimestamp:!1}))}else if(!X0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let U=`${A} ${this.environment}.INFO: [BOX] ${$}
|
|
73
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(X0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${a.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();O0.stdin.removeListener("data",Y);try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!1)}catch{}O0.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!0)}catch{}O0.stdin.resume(),O0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,X=0;if(Y=$.replace(U,(J,W)=>{if(W==="%")return"%";if(X>=w.length)return J;let f=w[X++];switch(W){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return J}}),X<w.length)Y+=` ${w.slice(X).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!X0()){let U=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",X=a.blue("◐");console.error(`${X} ${U} ${a.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
74
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress($,w=""){if(!this.enabled||!this.fancy||X0()||$<=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 Y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,A)),U!==void 0)this.activeProgressBar.message=U;let X=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,X)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,A!==void 0)this.activeProgressBar.message=A;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(A,U="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;O0.stdout.write(`${"\r".padEnd(O0.stdout.columns||80)}\r`),this.log(U,A),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||X0()||!O0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=a.green("━".repeat(A)),J=a.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=w||Y===100?a.green("✓"):a.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=O0.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,O0.stdout.write($.lastRenderedLine),w)O0.stdout.write(`
|
|
75
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||X0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(X0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await CA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let U=w1(this.config.logDirectory,A);if($.before)try{if((await $1(U)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${U}:`,X);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await hA(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function iA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&l(w[0])&&"id"in w[0]&&w[0].id===3&&l(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(l(w)&&l($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(l($)&&"arr"in $&&Array.isArray($.arr)&&l(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&l(w[0])&&l($[0])){let A=[...w];for(let U of $)if(l(U)&&"name"in U){if(!A.find((X)=>l(X)&&("name"in X)&&X.name===U.name))A.push(U)}else if(l(U)&&"path"in U){if(!A.find((X)=>l(X)&&("path"in X)&&X.path===U.path))A.push(U)}else if(!A.some((X)=>eA(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!l(w)||!l($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(l(U)&&l(Y[A]))Y[A]=iA(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&l(U[0])&&l(Y[A][0])){let X=[...U];for(let J of Y[A])if(l(J)&&"name"in J){if(!X.find((W)=>l(W)&&("name"in W)&&W.name===J.name))X.push(J)}else if(l(J)&&"path"in J){if(!X.find((W)=>l(W)&&("path"in W)&&W.path===J.path))X.push(J)}else if(!X.some((W)=>eA(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function IJ($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:iA($,w);if(Array.isArray($))return Y==="replace"?w:iA($,w);if(!l(w)||!l($))return w;let A={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let X=w[U],J=A[U];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(J))if(Y==="replace")A[U]=X;else A[U]=iA(J,X);else if(l(X)&&l(J))A[U]=IJ(J,X,Y);else A[U]=X}return A}function eA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!eA($[Y],w[Y]))return!1;return!0}if(l($)&&l(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!eA($[U],w[U]))return!1}return!0}return!1}function l($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function PA($,w,Y="replace"){if(!Bz($))return null;try{let A=await import($),U=A.default||A;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return IJ(w,U,Y)}catch{return null}}catch{return null}}function RK($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),U={...w};function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${z.map(G).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)_0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=X(j,z);else{let K=UY.env[F]||UY.env[T];if(K!==void 0){if(Y)_0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((q)=>q.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return X(U)}async function MK({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:U,verbose:X=!1,checkEnv:J=!0,arrayStrategy:W="replace"}){let f=J&&typeof U==="object"&&U!==null&&!Array.isArray(U)?RK($,U,X):U,B=Y||UY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(X)_0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),G=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,i0(B,"config"),i0(B,".config"),A?i0(B,A):void 0].filter(Boolean)));for(let H of K){if(X)_0.info(`Searching for configuration in: ${H}`);let q=[i0(B,"config"),i0(B,".config")].concat(A?[i0(B,A)]:[]).includes(H)?[...z,...G,...F,...T]:[...G,...z,...T,...F];for(let M of q)for(let I of j){let h=i0(H,`${M}${I}`),N=await PA(h,f,W);if(N!==null){if(X)_0.success(`Configuration loaded from: ${h}`);return N}}}if($){let H=i0(k8(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(X)_0.info(`Checking user config directory: ${H}`);for(let M of q)for(let I of j){let h=i0(H,`${M}${I}`),N=await PA(h,f,W);if(N!==null){if(X)_0.success(`Configuration loaded from user config directory: ${h}`);return N}}}if($){let H=i0(k8(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(X)_0.info(`Checking user config directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=i0(H,`${M}${I}`),N=await PA(h,f,W);if(N!==null){if(X)_0.success(`Configuration loaded from user config directory dotfile: ${h}`);return N}}}if($){let H=k8(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(X)_0.info(`Checking user home directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=i0(H,`${M}${I}`),N=await PA(h,f,W);if(N!==null){if(X)_0.success(`Configuration loaded from user home directory: ${h}`);return N}}}try{let H=i0(B,"package.json");if(Bz(H)){let q=await import(H),M=q[$];if(!M&&w){if(M=q[w],M&&X)_0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(X)_0.success(`Configuration loaded from package.json: ${M===q[$]?$:w}`);return IJ(f,M,W)}catch(I){if(X)_0.warn("Failed to merge package.json config:",I)}}}catch(H){if(X)_0.warn("Failed to load package.json:",H)}if(X)_0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function IK($,w={}){let Y=nA.cwd();while(Y.includes("storage"))Y=jj(Y,"..");let A=jj(Y,$||"");if(w?.relative)return VE(nA.cwd(),A);return A}async function yK(){try{let $=await MK({name:"clarity",alias:"logging",defaultConfig:mA,cwd:nA.cwd()});return{...mA,...$||{}}}catch{return mA}}function T0(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CK(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c$<"u"){let $=c$.type;if($==="renderer"||$==="worker")return!1;return!!(c$.versions&&(c$.versions.node||c$.versions.bun))}return!1}class Kz{async format($){let w=await CK(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:X1.pid,hostname:w(),environment:X1.env.NODE_ENV||"development",platform:X1.platform,version:X1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:X1.env.NODE_ENV||X1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $U{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($,w={}){this.name=$,this.config={...XJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Kz,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??d.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...dA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...dA};return{...dA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:XJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,U=0,X=3,J=1000;while(U<X)try{try{try{await cE(this.config.logDirectory,Mj.F_OK|Mj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await vE(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P$.from($);try{if(!VA(this.currentLogFile))await i8(this.currentLogFile,"",{mode:420});if(A=Rj(this.currentLogFile,"a",420),iE(A,W,{flag:"a"}),qj(A),A!==void 0)u8(A),A=void 0;if((await A1(this.currentLogFile)).size===0){if(await i8(this.currentLogFile,W,{flag:"w",mode:420}),(await A1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<X-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${X}:`,j);let z=J*2**U;await new Promise((G)=>setTimeout(G,z)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{u8(A)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(W){if(U===X-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}U++;let f=J*2**(U-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,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 U1(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 U1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return U1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,J],[,W])=>W.createdAt.getTime()-J.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,U);if(A.length>X)for(let[J]of A.slice(X))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return b8(16).toString("hex")}generateKey(){return b8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=b8(16),A=PE("aes-256-gcm",w,Y),U=P$.isBuffer($)?$:P$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=P$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=yj(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(P$.from(P$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let $=await A1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await LA(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await A1(Y).catch(()=>null))try{if(await Ij(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await QA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await i8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await A1(Y).catch(()=>null))await Ij(Y,X)}if(this.currentLogFile=A,w.maxFiles){let U=(await LA(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,J)=>J.localeCompare(X));for(let X of U.slice(w.maxFiles))await QA(U1(this.config.logDirectory,X))}}}async compressLogFile($,w){let Y=Nj($),A=uE(w),U=yj();await gE(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),VA(this.currentLogFile))try{let $=Rj(this.currentLogFile,"r+");qj($),u8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await LA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await QA(U1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let $=typeof d.env.NO_COLOR<"u",w=d.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof d.stderr<"u"&&d.stderr.isTTY||typeof d.stdout<"u"&&d.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=d.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${P.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=P.underline(P.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>P.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>P.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>P.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>P.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>P.strikethrough(A)),w}supportsHyperlinks(){if(T0())return!1;let $=d.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=d.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(mE(w)||w.startsWith("./")||w.startsWith("../"))w=dE(w);else return null;return VA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":hz[$],G=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:P.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:P.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
76
|
+
`);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:P.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
77
|
+
`;if(W)j+=`${W}
|
|
78
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(U,X)=>{},finish:(U)=>{},interrupt:(U,X)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,X)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),X!==void 0)this.activeProgressBar.message=X;if(this.shouldStyleConsole()&&!T0()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,X="info")=>{if(!T0()&&d.stdout.isTTY)d.stdout.write(`
|
|
79
|
+
`);if(this[X==="warning"?"warn":X](U),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":P.blue("◐"),tag:Y,message:`${P.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),f=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)f+=` ${JSON.stringify(Y)}`;if(f+=`
|
|
80
|
+
`,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":P.green("✓"),tag:B,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T0())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new $U(w,{...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(Y),Y}createReadStream(){if(T0())throw Error("createReadStream is not supported in browser environments");if(!VA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Nj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=P$.isBuffer($)?$:P$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=bE("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=P$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T0()}isServerMode(){return!T0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}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($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
81
|
+
`),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:P.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:P.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:P.cyan(j),showTimestamp:!1}))}else if(!T0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
|
|
82
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(T0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${P.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();d.stdin.removeListener("data",Y);try{if(typeof d.stdin.setRawMode==="function")d.stdin.setRawMode(!1)}catch{}d.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof d.stdin.setRawMode==="function")d.stdin.setRawMode(!0)}catch{}d.stdin.resume(),d.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,W=0;if(Y=$.replace(J,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)Y+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${P.blue("◐")} `;console.error(`${W}${J} ${P.cyan(A)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
83
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!d.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=P.green("━".repeat(A)),J=P.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?P.green("✓"):P.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=d.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,d.stdout.write($.lastRenderedLine),w)d.stdout.write(`
|
|
84
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||T0()||!d.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await LA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let U=U1(this.config.logDirectory,A);if($.before)try{if((await A1(U)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${U}:`,X);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await QA(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function Tz($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}function Hz($){return $ instanceof s0}function hK($){return $ instanceof wU}function VK($){if(Hz($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}class jU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return WY.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=OA.env[f]||(B?OA.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=OA.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof YU)throw z;throw jw.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw jw.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(OA.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
85
|
+
|
|
86
|
+
`;for(let A of $)Y+=`${A.key}
|
|
87
|
+
`,Y+=` Type: ${A.type}
|
|
88
|
+
`,Y+=` Description: ${A.description}
|
|
89
|
+
`,Y+=` Example: ${A.example}
|
|
90
|
+
|
|
91
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
92
|
+
|
|
93
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
94
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
95
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
96
|
+
`;return Y}}function LK($,w){let Y=Iz("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function Nz($,w,Y={}){return qz($,w,Y,new WeakMap)}function qz($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return Rz($,w,U,A);if(!J$(w)||!J$($))return w;return _K($,w,Y,A)}function Rz($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return QK($,w);case"smart":return OK($,w,A);default:return w}return w}function QK($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>AJ(U,A)))Y.push(A);return Y}function OK($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(J$(w[0])&&J$($[0]))return SK($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function SK($,w,Y){let A=[...w];for(let U of $){if(!J$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((f)=>J$(f)&&(W in f)&&f[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function _K($,w,Y,A){let U=w;if(J$(U)&&A.has(U))return A.get(U);let X={...$};if(J$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(J$(W)&&J$(f))X[J]=qz(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=Rz(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function yJ($,w,Y="replace"){return Nz($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function AJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!AJ($[Y],w[Y]))return!1;return!0}if(J$($)&&J$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!AJ($[U],w[U]))return!1}return!0}return!1}function J$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class zU{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=j1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!SA($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new XY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new XY($,Error("Configuration must export a valid object"),"unknown");let T={config:yJ(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)j1.setWithFileCheck("file",T,$,X);return T}catch(B){throw B instanceof Error?jw.configLoad($,B):jw.configLoad($,Error(String(B)))}};if(J)return WY.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(c8(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return Tz(async()=>{return SA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!SA($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=c8($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=c8($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){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((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!SA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class CJ{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await WY.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!lE(w))throw new JY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new JY(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.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:Lz},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class hJ{fileLoader=new zU;envProcessor=new jU;validator=new CJ;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)K$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw K$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||Vw.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(c0(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw jw.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?wY($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)K$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)K$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?wY($,Y,U):Y,W=[c0(ew(),".config",$),c0(ew(),".config"),ew()];for(let f of W){if(U)K$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)K$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?wY($,A,X):A;try{let f=c0(Y,"package.json");if(!wJ(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)K$.success(`Configuration loaded from package.json: ${z}`);return{config:yJ(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)K$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:wY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw jw.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return j1.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);j1.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,c0($,"config"),c0($,".config"),w?c0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(c0(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[c0(ew(),".config",$),c0(ew(),".config"),ew()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function kj($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||Y}async function kK($){return d$.loadConfig({...$,__strictErrorHandling:!0})}async function Mz($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await d$.loadConfig($);else A=await d$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}catch(A){let U=A instanceof Error?A.name:"UnknownError",X=A instanceof Error?A.message:String(A);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||X.includes("config"))&&$.verbose)K$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let J=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await d$.applyEnvironmentVariables(J.name||"",w,!0,J.verbose||!1))?.config??w;return w}}async function DK($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await d$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&kj(Y)))return(await d$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await d$.loadConfig({...$,cwd:$.cwd||Vw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&kj(w)))return(await d$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function ZK($,w,Y="replace"){let A=new zU;try{let U=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function wY($,w,Y=!1){let A=new jU,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=Vw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}function xK($){let w=c0(Vw.cwd(),$.configDir),Y=c0(Vw.cwd(),$.generatedDir),A=c0(Y,"config-types.ts");if(!wJ(Bj(A)))IE(Bj(A),{recursive:!0,mode:511});let U=wJ(w)?yE(w).map((J)=>J.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${j7}
|
|
97
|
+
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
98
|
+
`;CE(A,X,{mode:438})}function PK($){let w=null,Y=null,A=()=>{if(!Y)Y=Mz($).then((X)=>{return w=X,X},(X)=>{let J="defaultConfig"in $?$.defaultConfig:{};if(w=J,"verbose"in $&&$.verbose)K$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return J});return Y},U="defaultConfig"in $?$.defaultConfig:{};return w=U,A(),new Proxy({},{get(X,J){if(w)return w[J];let W=U[J];return A(),W},has(X,J){return J in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(X,J){return Object.getOwnPropertyDescriptor(w||U,J)},set(X,J,W){if(!w)w={...U};return w[J]=W,!0}})}function bK($){let w=Cj(tE.cwd(),$?.configDir||"./config");function Y(){if(!nE(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],J=pE(w).filter((f)=>U.has(v8(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),W=new Map;for(let{base:f,file:B}of J){let j=v8(B).toLowerCase(),z=W.get(f);if(!z){W.set(f,B);continue}let G=v8(z).toLowerCase();if(X.indexOf(j)<X.indexOf(G))W.set(f,B)}return Array.from(W.entries()).map(([f,B])=>({base:f,file:B})).sort((f,B)=>f.base.localeCompare(B.base))}function A(){let U=Y(),X=U.map((f)=>f.base),J=X.length?X.map((f)=>`'${f}'`).join(" | "):"string",W=U.length?`{
|
|
99
|
+
${U.map((f)=>{let B=Cj(w,f.file).replace(/\\/g,"/");return` '${f.base}': typeof import('${B}').default`}).join(`,
|
|
100
100
|
`)}
|
|
101
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
101
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${J}
|
|
102
102
|
export type ConfigByName = ${W}
|
|
103
103
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
104
104
|
export type ConfigOf = Config
|
|
105
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function z5($,w={}){let A=xY.cwd();while(A.includes("storage"))A=aB(A,"..");let Y=aB(A,$||"");if(w?.relative)return oG(xY.cwd(),Y);return Y}function H0(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function H5(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n$<"u"){let $=n$.type;if($==="renderer"||$==="worker")return!1;return!!(n$.versions&&(n$.versions.node||n$.versions.bun))}return!1}class fj{async format($){let w=await H5(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:U1.pid,hostname:w(),environment:U1.env.NODE_ENV||"development",platform:U1.platform,version:U1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:U1.env.NODE_ENV||U1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oY{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($,w={}){this.name=$,this.config={...mY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new fj,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??d.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...OU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...OU};return{...OU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:mY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,f=0,X=3,U=1000;while(f<X)try{try{try{await YH(this.config.logDirectory,$E.F_OK|$E.W_OK)}catch(J){if(J instanceof Error&&"code"in J)if(J.code==="ENOENT")await fH(this.config.logDirectory,{recursive:!0,mode:493});else if(J.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw J;else throw J}}catch(J){throw console.error("Debug: [writeToFile] Failed to create log directory:",J),J}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:i$.from($);try{if(!KY(this.currentLogFile))await MU(this.currentLogFile,"",{mode:420});if(Y=eB(this.currentLogFile,"a",420),AH(Y,W,{flag:"a"}),oB(Y),Y!==void 0)yU(Y),Y=void 0;if((await f1(this.currentLogFile)).size===0){if(await MU(this.currentLogFile,W,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(J){let B=J;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(f<X-1){let E=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${f+1}/${X}:`,E);let j=U*2**f;await new Promise((T)=>setTimeout(T,j)),f++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(Y!==void 0)try{yU(Y)}catch(J){console.error("Debug: [writeToFile] Error closing file descriptor:",J)}}}catch(W){if(f===X-1){let B=W,E=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",E),W}f++;let J=U*2**(f-1);await new Promise((B)=>setTimeout(B,J))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,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 X1(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 X1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return X1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),f=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,f);if(Y.length>X)for(let[U]of Y.slice(X))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return hU(16).toString("hex")}generateKey(){return hU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=hU(16),Y=eG("aes-256-gcm",w,A),f=i$.isBuffer($)?$:i$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=i$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=AE(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(i$.from(i$.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let $=await f1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await RY(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await f1(A).catch(()=>null))try{if(await wE(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await NY(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await MU(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await f1(A).catch(()=>null))await wE(A,X)}if(this.currentLogFile=Y,w.maxFiles){let f=(await RY(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,U)=>U.localeCompare(X));for(let X of f.slice(w.maxFiles))await NY(X1(this.config.logDirectory,X))}}}async compressLogFile($,w){let A=sB($),Y=wH(w),f=AE();await JH(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),KY(this.currentLogFile))try{let $=eB(this.currentLogFile,"r+");oB($),yU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await RY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await NY(X1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let $=typeof d.env.NO_COLOR<"u",w=d.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof d.stderr<"u"&&d.stderr.isTTY||typeof d.stdout<"u"&&d.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=d.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${c.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=c.underline(c.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>c.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>c.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>c.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>c.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>c.strikethrough(Y)),w}supportsHyperlinks(){if(H0())return!1;let $=d.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=d.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(XH(w)||w.startsWith("./")||w.startsWith("../"))w=UH(w);else return null;return KY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":h5[$],T=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:c.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:c.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
106
|
-
`);for(let
|
|
107
|
-
`;if(W)
|
|
108
|
-
`;if(
|
|
109
|
-
`);if(this[X==="warning"?"warn":X](
|
|
110
|
-
`,
|
|
111
|
-
`),
|
|
112
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
113
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
114
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||
|
|
115
|
-
|
|
116
|
-
`;for(let
|
|
117
|
-
`,
|
|
118
|
-
`,
|
|
119
|
-
`,
|
|
120
|
-
|
|
121
|
-
`;return
|
|
122
|
-
|
|
123
|
-
`;
|
|
124
|
-
`,
|
|
125
|
-
`;for(let
|
|
126
|
-
`;return A}}function M5($,w,A={}){return Tj($,w,A,new WeakMap)}function Tj($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return Fj($,w,f,Y);if(!W$(w)||!W$($))return w;return L5($,w,A,Y)}function Fj($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return I5($,w);case"smart":return C5($,w,Y);default:return w}return w}function I5($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>lU(f,Y)))A.push(Y);return A}function C5($,w,A){if(w.length===0)return $;if($.length===0)return w;if(W$(w[0])&&W$($[0]))return S5($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function S5($,w,A){let Y=[...w];for(let f of $){if(!W$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((J)=>W$(J)&&(W in J)&&J[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function L5($,w,A,Y){let f=w;if(W$(f)&&Y.has(f))return Y.get(f);let X={...$};if(W$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(W$(W)&&W$(J))X[U]=Tj(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=Fj(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function zj($,w,A="replace"){return M5($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function lU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!lU($[A],w[A]))return!1;return!0}if(W$($)&&W$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!lU($[f],w[f]))return!1}return!0}return!1}function W$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class Gj{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=PY.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!hY($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new dY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new dY($,Error("Configuration must export a valid object"),"unknown");let H={config:zj(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)PY.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?B1.configLoad($,B):B1.configLoad($,Error(String(B)))}};if(U)return aU.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(IU(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of Y){if(!X)continue;if(A.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)A.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let f=new Set;return A.filter((X)=>{if(!X||f.has(X))return!1;return f.add(X),!0})}checkFileAccess($){return y5(async()=>{return hY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!hY($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=IU($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=IU($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){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((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!hY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class Hj{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await aU.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!WH(w))throw new lY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new lY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.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:V5},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function O5($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class Kj{fileLoader=new Gj;envProcessor=new X8;validator=new Hj;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)b$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let J=Date.now()-w;throw b$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||rY.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(U$(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw B1.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${O5(f)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?MY($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)b$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)b$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?MY($,A,f):A,W=[U$(aw(),".config",$),U$(aw(),".config"),aw()];for(let J of W){if(f)b$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)b$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?MY($,Y,X):Y;try{let J=U$(A,"package.json");if(!yG(J))return null;let B={};try{B=JSON.parse(MG(J,"utf8"))}catch(T){if(X)b$.warn("Failed to parse package.json:",[T instanceof Error?T:Error(String(T))]);return null}let E=B[$],j=$;if(!E&&w){let T=Array.isArray(w)?w:[w];for(let F of T){if(!F)continue;if(B[F]){E=B[F],j=F;break}}}if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)b$.success(`Configuration loaded from package.json: ${j}`);return{config:zj(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)b$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:MY($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw B1.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return PY.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);PY.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,U$($,"config"),U$($,".config"),w?U$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(U$(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[U$(aw(),".config",$),U$(aw(),".config"),aw()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function MY($,w,A=!1){let Y=new X8,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=rY.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function gU($,w){let A=[];function Y(f){let X;try{X=HE.readdirSync(f)}catch{return}for(let U of X){let W=K$.join(f,U);try{if(HE.statSync(W).isDirectory())Y(W);else if(U===w)A.push(f)}catch{continue}}}return Y($),A}function M($,w,A){if(A||W0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function qj(){return Nj.env.SUDO_PASSWORD}function P5($){let w=$.toLowerCase();return Z5.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function gY($){if(Array.isArray($))return $.map((A)=>gY(A));if(typeof $==="string")return x5.test($)?KE:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(P5(A)){w[A]=KE;continue}w[A]=gY(Y)}return w}function eY($){return JSON.stringify(gY($))}function i5($){let w=qj();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),Y=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${Y}`}async function Uw($,w={}){let A=i5($);try{let{stdout:Y,stderr:f}=await k5(A,{cwd:w.cwd||Nj.cwd(),timeout:w.timeout||30000});return{stdout:Y.trim(),stderr:f.trim()}}catch(Y){let f=Error(`Failed to execute command: ${$}
|
|
127
|
-
Error: ${
|
|
128
|
-
${
|
|
105
|
+
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function F7($,w={}){let Y=rA.cwd();while(Y.includes("storage"))Y=hj(Y,"..");let A=hj(Y,$||"");if(w?.relative)return aE(rA.cwd(),A);return A}function N0(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function E7(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof v$<"u"){let $=v$.type;if($==="renderer"||$==="worker")return!1;return!!(v$.versions&&(v$.versions.node||v$.versions.bun))}return!1}class _z{async format($){let w=await E7(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:W1.pid,hostname:w(),environment:W1.env.NODE_ENV||"development",platform:W1.platform,version:W1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:W1.env.NODE_ENV||W1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class FU{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($,w={}){this.name=$,this.config={...AU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new _z,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...a8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...a8};return{...a8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:AU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,U=0,X=3,J=1000;while(U<X)try{try{try{await wK(this.config.logDirectory,Oj.F_OK|Oj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await YK(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:b$.from($);try{if(!_A(this.currentLogFile))await g8(this.currentLogFile,"",{mode:420});if(A=Qj(this.currentLogFile,"a",420),$K(A,W,{flag:"a"}),Lj(A),A!==void 0)d8(A),A=void 0;if((await J1(this.currentLogFile)).size===0){if(await g8(this.currentLogFile,W,{flag:"w",mode:420}),(await J1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<X-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${X}:`,j);let z=J*2**U;await new Promise((G)=>setTimeout(G,z)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{d8(A)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(W){if(U===X-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}U++;let f=J*2**(U-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,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 f1(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 f1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return f1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,J],[,W])=>W.createdAt.getTime()-J.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,U);if(A.length>X)for(let[J]of A.slice(X))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return m8(16).toString("hex")}generateKey(){return m8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=m8(16),A=sE("aes-256-gcm",w,Y),U=b$.isBuffer($)?$:b$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=b$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=_j(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(b$.from(b$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let $=await J1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await kA(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await J1(Y).catch(()=>null))try{if(await Sj(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await DA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await g8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await J1(Y).catch(()=>null))await Sj(Y,X)}if(this.currentLogFile=A,w.maxFiles){let U=(await kA(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,J)=>J.localeCompare(X));for(let X of U.slice(w.maxFiles))await DA(f1(this.config.logDirectory,X))}}}async compressLogFile($,w){let Y=Vj($),A=eE(w),U=_j();await XK(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),_A(this.currentLogFile))try{let $=Qj(this.currentLogFile,"r+");Lj($),d8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await kA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await DA(f1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let $=typeof g.env.NO_COLOR<"u",w=g.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=g.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${i.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=i.underline(i.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>i.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>i.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>i.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>i.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>i.strikethrough(A)),w}supportsHyperlinks(){if(N0())return!1;let $=g.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=g.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(AK(w)||w.startsWith("./")||w.startsWith("../"))w=UK(w);else return null;return _A(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":q7[$],G=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:i.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:i.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
106
|
+
`);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:i.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!N0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
107
|
+
`;if(W)j+=`${W}
|
|
108
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(U,X)=>{},finish:(U)=>{},interrupt:(U,X)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,X)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),X!==void 0)this.activeProgressBar.message=X;if(this.shouldStyleConsole()&&!N0()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,X="info")=>{if(!N0()&&g.stdout.isTTY)g.stdout.write(`
|
|
109
|
+
`);if(this[X==="warning"?"warn":X](U),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":i.blue("◐"),tag:Y,message:`${i.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),f=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)f+=` ${JSON.stringify(Y)}`;if(f+=`
|
|
110
|
+
`,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":i.green("✓"),tag:B,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!N0())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new FU(w,{...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(Y),Y}createReadStream(){if(N0())throw Error("createReadStream is not supported in browser environments");if(!_A(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Vj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=b$.isBuffer($)?$:b$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=oE("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=b$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N0()}isServerMode(){return!N0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}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($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
111
|
+
`),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:i.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(j),showTimestamp:!1}))}else if(!N0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
|
|
112
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(N0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${i.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();g.stdin.removeListener("data",Y);try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!1)}catch{}g.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!0)}catch{}g.stdin.resume(),g.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,W=0;if(Y=$.replace(J,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)Y+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${W}${J} ${i.cyan(A)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
113
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!g.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=i.green("━".repeat(A)),J=i.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?i.green("✓"):i.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=g.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,g.stdout.write($.lastRenderedLine),w)g.stdout.write(`
|
|
114
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||N0()||!g.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(N0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await kA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let U=f1(this.config.logDirectory,A);if($.before)try{if((await J1(U)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${U}:`,X);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await DA(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function R7($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}class LJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return NJ.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=ZA.env[f]||(B?ZA.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=ZA.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof VJ)throw z;throw z1.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw z1.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(ZA.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
115
|
+
|
|
116
|
+
`;for(let A of $)Y+=`${A.key}
|
|
117
|
+
`,Y+=` Type: ${A.type}
|
|
118
|
+
`,Y+=` Description: ${A.description}
|
|
119
|
+
`,Y+=` Example: ${A.example}
|
|
120
|
+
|
|
121
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
122
|
+
|
|
123
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
124
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
125
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
126
|
+
`;return Y}}function M7($,w,Y={}){return iz($,w,Y,new WeakMap)}function iz($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return cz($,w,U,A);if(!f$(w)||!f$($))return w;return h7($,w,Y,A)}function cz($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return I7($,w);case"smart":return y7($,w,A);default:return w}return w}function I7($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>FJ(U,A)))Y.push(A);return Y}function y7($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(f$(w[0])&&f$($[0]))return C7($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function C7($,w,Y){let A=[...w];for(let U of $){if(!f$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((f)=>f$(f)&&(W in f)&&f[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function h7($,w,Y,A){let U=w;if(f$(U)&&A.has(U))return A.get(U);let X={...$};if(f$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(f$(W)&&f$(f))X[J]=iz(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=cz(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function vz($,w,Y="replace"){return M7($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function FJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!FJ($[Y],w[Y]))return!1;return!0}if(f$($)&&f$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!FJ($[U],w[U]))return!1}return!0}return!1}function f$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class mz{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=aA.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!xA($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new UU($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new UU($,Error("Configuration must export a valid object"),"unknown");let T={config:vz(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)aA.setWithFileCheck("file",T,$,X);return T}catch(B){throw B instanceof Error?z1.configLoad($,B):z1.configLoad($,Error(String(B)))}};if(J)return NJ.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(l8(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of A){if(!X)continue;if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)Y.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let U=new Set;return Y.filter((X)=>{if(!X||U.has(X))return!1;return U.add(X),!0})}checkFileAccess($){return R7(async()=>{return xA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!xA($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=l8($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=l8($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){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((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!xA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class dz{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await NJ.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!JK(w))throw new XU(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new XU(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.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:V7},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function L7($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class gz{fileLoader=new mz;envProcessor=new LJ;validator=new dz;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)u$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let f=Date.now()-w;throw u$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||BU.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(X$(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw z1.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${L7(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?bA($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)u$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)u$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?bA($,Y,U):Y,W=[X$(ow(),".config",$),X$(ow(),".config"),ow()];for(let f of W){if(U)u$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)u$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?bA($,A,X):A;try{let f=X$(Y,"package.json");if(!RE(f))return null;let B={};try{B=JSON.parse(ME(f,"utf8"))}catch(G){if(X)u$.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let j=B[$],z=$;if(!j&&w){let G=Array.isArray(w)?w:[w];for(let F of G){if(!F)continue;if(B[F]){j=B[F],z=F;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)u$.success(`Configuration loaded from package.json: ${z}`);return{config:vz(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)u$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:bA($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw z1.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return aA.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);aA.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,X$($,"config"),X$($,".config"),w?X$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(X$(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[X$(ow(),".config",$),X$(ow(),".config"),ow()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function bA($,w,Y=!1){let A=new LJ,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=BU.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}function pz($){return GJ.readFileSync($,"utf8")}function EJ($,w){let Y=[];function A(U){let X;try{X=GJ.readdirSync(U)}catch{return}for(let J of X){let W=E$.join(U,J);try{if(GJ.statSync(W).isDirectory())A(W);else if(J===w)Y.push(U)}catch{continue}}}return A($),Y}function V($,w,Y){if(Y||B0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function tz(){return nz.env.SUDO_PASSWORD}function Z7($){let w=$.toLowerCase();return k7.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function JU($){if(Array.isArray($))return $.map((Y)=>JU(Y));if(typeof $==="string")return D7.test($)?lj:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(Z7(Y)){w[Y]=lj;continue}w[Y]=JU(A)}return w}function GU($){return JSON.stringify(JU($))}function x7($){let w=tz();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let Y=w.replace(/'/g,"'\\''"),A=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function Bw($,w={}){let Y=x7($);try{let{stdout:A,stderr:U}=await _7(Y,{cwd:w.cwd||nz.cwd(),timeout:w.timeout||30000});return{stdout:A.trim(),stderr:U.trim()}}catch(A){let U=Error(`Failed to execute command: ${$}
|
|
127
|
+
Error: ${A.message}`);throw U.stack=A.stack,U}}function rz($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function QJ($){let w=E$.join(O7.homedir(),".stacks","ssl"),Y=$.basePath&&$.basePath.trim()!==""?$.basePath:B0.basePath&&B0.basePath.trim()!==""?B0.basePath:w,A=$.certPath?E$.isAbsolute($.certPath)?$.certPath:E$.join(Y,$.certPath):E$.join(Y,B0.certPath),U=$.keyPath?E$.isAbsolute($.keyPath)?$.keyPath:E$.join(Y,$.keyPath):E$.join(Y,B0.keyPath),X=$.caCertPath?E$.isAbsolute($.caCertPath)?$.caCertPath:E$.join(Y,$.caCertPath):E$.join(Y,B0.caCertPath);return{certPath:A,keyPath:U,caCertPath:X,basePath:Y}}function az($){let w=[],Y=new Set;if($.domain)Y.add($.domain);if($.domains?.length)$.domains.forEach((A)=>Y.add(A));for(let A of Y)w.push({type:2,value:A});if($.altNameIPs?.length)for(let A of $.altNameIPs)w.push({type:7,ip:A});if($.altNameURIs?.length)for(let A of $.altNameURIs)w.push({type:6,value:A});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return V(Q.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function OJ($){let w=$.notBeforeDays??T$.DEFAULT_NOT_BEFORE_DAYS,Y=$.validityDays??($.validityYears?$.validityYears*365:T$.DEFAULT_VALIDITY_DAYS);V(Q.CERT,"Calculating certificate validity dates",$.verbose);let A=new Date(Date.now()-86400*w*1000),U=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),U.setUTCHours(23,59,59,999),V(Q.CERT,`Validity period: ${A.toISOString()} to ${U.toISOString()}`,$.verbose),{notBefore:A,notAfter:U}}function YY($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function e0($,w){let Y=YY(w.length);return Buffer.concat([Buffer.from([$]),Y,w])}function fY($){let w=$.split(".").map(Number),Y=[];Y.push(40*w[0]+w[1]);for(let A=2;A<w.length;A++){let U=w[A],X=[];X.unshift(U&127),U>>=7;while(U>0)X.unshift(U&127|128),U>>=7;Y.push(...X)}return e0(H$.OID,Buffer.from(Y))}function KJ($){let w;if(typeof $==="bigint"){let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else w=$;if(w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return e0(H$.INTEGER,w)}function sz($,w=0){return e0(H$.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function oz($){return e0(H$.OCTET_STRING,$)}function o0(...$){return e0(H$.SEQUENCE,Buffer.concat($))}function P7(...$){return e0(H$.SET,Buffer.concat($))}function b7($){return e0(H$.PRINTABLE_STRING,Buffer.from($,"ascii"))}function u7($){return e0(H$.UTF8_STRING,Buffer.from($,"utf8"))}function i7(){return Buffer.from([H$.NULL,0])}function nj($,w,Y=!0){let A=160|$|(Y?0:0),U=YY(w.length);return Buffer.concat([Buffer.from([A]),U,w])}function pj($){let w=$.getUTCFullYear();if(w>=2050){let Y=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return e0(H$.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=(w%100).toString().padStart(2,"0"),A=($.getUTCMonth()+1).toString().padStart(2,"0"),U=$.getUTCDate().toString().padStart(2,"0"),X=$.getUTCHours().toString().padStart(2,"0"),J=$.getUTCMinutes().toString().padStart(2,"0"),W=$.getUTCSeconds().toString().padStart(2,"0"),f=`${Y}${A}${U}${X}${J}${W}Z`;return e0(H$.UTC_TIME,Buffer.from(f,"ascii"))}}function c7($,w){return o0(pj($),pj(w))}function tj($){let w=[];for(let Y of $){let A;switch(Y.shortName){case"CN":A=v0.COMMON_NAME;break;case"C":A=v0.COUNTRY;break;case"L":A=v0.LOCALITY;break;case"ST":A=v0.STATE;break;case"O":A=v0.ORGANIZATION;break;case"OU":A=v0.ORGANIZATIONAL_UNIT;break;default:continue}let U=Y.shortName==="C"?b7(Y.value):u7(Y.value),X=o0(fY(A),U);w.push(P7(X))}return o0(...w)}function ez($){return o0(fY($),i7())}function v7($){return $.export({type:"spki",format:"der"})}function m7($){if($.includes(":")){let w=$;if($.includes("::")){let U=$.split("::"),X=U[0]?U[0].split(":"):[],J=U[1]?U[1].split(":"):[],W=8-X.length-J.length,f=Array.from({length:W},()=>"0");w=[...X,...f,...J].join(":")}let Y=w.split(":"),A=Buffer.alloc(16);for(let U=0;U<8;U++){let X=Number.parseInt(Y[U]||"0",16);A.writeUInt16BE(X,U*2)}return A}else{let w=$.split(".").map((Y)=>Number.parseInt(Y,10));return Buffer.from(w)}}function d7($){let w=[];for(let Y of $)if(Y.type===2&&Y.value){let A=YY(Y.value.length);w.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=m7(Y.ip),U=YY(A.length);w.push(Buffer.concat([Buffer.from([135]),U,A]))}else if(Y.type===6&&Y.value){let A=YY(Y.value.length);w.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return o0(...w)}function g7($,w){if($){if(w!==void 0)return o0(e0(1,Buffer.from([255])),KJ(w));return o0(e0(1,Buffer.from([255])))}return o0()}function l7($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let Y=0,A=w;while(A>0&&(A&1)===0)Y++,A>>=1;if(w===0)Y=7;return sz(Buffer.from([w]),Y)}function n7($){let w=[];if($.serverAuth)w.push(fY(v0.SERVER_AUTH));if($.clientAuth)w.push(fY(v0.CLIENT_AUTH));return o0(...w)}function $Y($,w,Y){let A=[fY($)];if(w)A.push(e0(1,Buffer.from([255])));return A.push(oz(Y)),o0(...A)}function p7($){let w=[];if(w.push(nj(0,KJ(2))),w.push(KJ($.serialNumber)),w.push(ez(v0.SHA256_WITH_RSA)),w.push(tj($.issuer)),w.push(c7($.notBefore,$.notAfter)),w.push(tj($.subject)),w.push(v7($.publicKey)),$.extensions){let Y=[];if($.extensions.basicConstraints)Y.push($Y(v0.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,g7($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)Y.push($Y(v0.KEY_USAGE,$.extensions.keyUsage.critical??!0,l7($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)Y.push($Y(v0.EXTENDED_KEY_USAGE,!1,n7($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)Y.push($Y(v0.SUBJECT_ALT_NAME,!1,d7($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)Y.push($Y(v0.SUBJECT_KEY_IDENTIFIER,!1,oz($.extensions.subjectKeyIdentifier)));if(Y.length>0)w.push(nj(3,o0(...Y)))}return o0(...w)}function t7($,w){let Y=F1.createSign("SHA256");Y.update($);let A=Y.sign(w);return o0($,ez(v0.SHA256_WITH_RSA),sz(A))}function r7($,w){let Y=$.toString("base64"),A=[];for(let U=0;U<Y.length;U+=64)A.push(Y.slice(U,U+64));return`-----BEGIN ${w}-----
|
|
128
|
+
${A.join(`
|
|
129
129
|
`)}
|
|
130
130
|
-----END ${w}-----
|
|
131
|
-
`}function
|
|
132
|
-
`);for(let X of f){let[U,...W]=X.split("="),J=W.join("=");if(U&&J)Y.push({shortName:U.trim(),value:J.trim()})}return{publicKey:A,subject:Y}}async function B8($={}){M("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||N$.DEFAULT_KEY_SIZE;M("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:Y}=Sj(w),f=[{shortName:"C",value:$.countryName||W0.countryName},{shortName:"ST",value:$.stateName||W0.stateName},{shortName:"L",value:$.localityName||W0.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:X,notAfter:U}=J8({validityYears:$.validityYears||N$.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=Lj({serialNumber:W8(),notBefore:X,notAfter:U,subject:f,publicKey:Y,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:Vj(A),notBefore:X,notAfter:U}}async function E8($){if(M("ca","Generating new certificate",$.verbose),M("ca",`Options: ${eY($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=$K($.rootCA.certificate),A=e5($.rootCA.privateKey);M("ca",`Generating ${N$.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let Y=N$.DEFAULT_KEY_SIZE,{privateKey:f,publicKey:X}=Sj(Y),U=$.commonName||hj($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||W0.countryName},{shortName:"ST",value:$.stateName||W0.stateName},{shortName:"L",value:$.localityName||W0.localityName},{shortName:"O",value:$.organizationName||W0.organizationName},{shortName:"CN",value:U}],{notBefore:J,notAfter:B}=J8({validityDays:$.validityDays||N$.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),E=yj($),j=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},T=$.extKeyUsage||{serverAuth:!0},{certificate:F}=Lj({serialNumber:W8(),notBefore:J,notAfter:B,subject:W,issuer:w,publicKey:X,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:j,extendedKeyUsage:T,subjectAltName:E});return{certificate:F,privateKey:Vj(f),notBefore:J,notAfter:B}}function Oj($,w){M(C.STORAGE,`Storing certificate and private key with options: ${eY(w)}`,w?.verbose);let{certPath:A,keyPath:Y}=U8({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});M(C.STORAGE,`Certificate path: ${A}`,w?.verbose),M(C.STORAGE,`Private key path: ${Y}`,w?.verbose);let f=pU.dirname(A);if(!v$.existsSync(f))M(C.STORAGE,`Creating certificate directory: ${f}`,w?.verbose),v$.mkdirSync(f,{recursive:!0});M(C.STORAGE,"Writing certificate file",w?.verbose),v$.writeFileSync(A,$.certificate);let X=pU.dirname(Y);if(!v$.existsSync(X))M(C.STORAGE,`Creating private key directory: ${X}`,w?.verbose),v$.mkdirSync(X,{recursive:!0});return M(C.STORAGE,"Writing private key file",w?.verbose),v$.writeFileSync(Y,$.privateKey),M(C.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function _j($,w){M(C.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=U8({basePath:w?.basePath,caCertPath:w?.caCertPath});M(C.STORAGE,`CA certificate path: ${A}`,w?.verbose);let Y=pU.dirname(A);if(!v$.existsSync(Y))M(C.STORAGE,`Creating CA certificate directory: ${Y}`,w?.verbose),v$.mkdirSync(Y,{recursive:!0});return M(C.STORAGE,"Writing CA certificate file",w?.verbose),v$.writeFileSync(A,$),M(C.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function wK($,w){if(tY.platform()!=="darwin")return!1;try{let A=hE(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return M(C.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(hE("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return M(C.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return M(C.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return M(C.TRUST,`Error checking certificate trust: ${A}`,w),!1}}async function j8($,w,A){M(C.TRUST,`Adding certificate to system trust store with options: ${eY(A)}`,A?.verbose),M(C.TRUST,"Storing certificate and private key",A?.verbose);let Y=Oj($,A);M(C.TRUST,"Storing CA certificate",A?.verbose);let f=_j(w,A),X=tY.platform();M(C.TRUST,`Detected platform: ${X}`,A?.verbose);let U=XK[X];if(!U){let W=`Unsupported platform: ${X}`;throw M(C.TRUST,`Error: ${W}`,A?.verbose),Error(W)}return await U.addCertificate(f,A),M(C.TRUST,"Certificate successfully added to system trust store",A?.verbose),Y}var JG,pY,SE="https://acme-staging-v02.api.letsencrypt.org/directory",LE="https://acme-v02.api.letsencrypt.org/directory",_Y,FG="1.2.840.10045.2.1",zG="1.2.840.10045.3.1.7",GG="1.2.840.10045.4.3.2",HG="2.5.4.3",KG="1.2.840.113549.1.9.14",RG="2.5.29.17",PY,aU,BH,EH=($)=>$,TH=($,w)=>{for(var A in w)BH($,A,{get:w[A],enumerable:!0,configurable:!0,set:jH.bind(w,A)})},FH=($,w)=>()=>($&&(w=$($=0)),w),uE,rE,W1,t1,aE,uH,nH,fE,SY,iU,V0,p,vH,XE,mH,UE,dH,lH,CU,gH,JE,WE,SU,tH,pH,rH,aH,LY,sE,sH,O0,oH,eH,BE,VY,bU,G0,x,$5,EE,w5,jE,A5,Y5,LU,f5,TE,FE,X5,VU,U5,J5,W5,B5,E5,OY,oE,j5,T5="0.15.6",r0,nY,d1,cU,uU,vY,nU,vU,l1,mU,dU,Jw,eE,$j,R$,m$,wj,Aj,F5,G5,Yj,mY,my,y0,c,dy,K5,ly,R5,gy,ty,zE,py,N5,q5,ry,GE,ay,sy,oy,ey,$M,OU,h5,wM,h$,Xj,dY,Uj,Jj,f8,Wj,Bj,lY,Ej,jj,B1,V5,b$,AM,YM,fM,Rj,W0,N$,C,J1,k5,KE="[redacted]",Z5,x5,q$,b0,AK,YK,fK,XK;var Qj=E0(()=>{JG=UG(import.meta.url);pY=new v1;_Y=class _Y extends Error{problem;httpStatus;constructor($,w,A){super($);this.name="AcmeError",this.problem=w,this.httpStatus=A}};PY=new bE,aU=new cE,BH=Object.defineProperty;uE={};TH(uE,{withErrorRecovery:()=>mE,tryLoadConfig:()=>PH,loadConfigWithResult:()=>ZH,loadConfig:()=>pE,isRetryableError:()=>VH,isConfigNotFoundError:()=>LH,isBunfigError:()=>dE,globalPerformanceMonitor:()=>t1,globalCache:()=>W1,getEnvOrDefault:()=>OH,generateConfigTypes:()=>iH,defaultGeneratedDir:()=>Aj,defaultConfigDir:()=>wj,deepMergeWithArrayStrategy:()=>w8,deepMerge:()=>lE,createLibraryConfig:()=>bH,config:()=>xH,bunfigPlugin:()=>cH,applyEnvVarsToConfig:()=>u1,TypeGenerationError:()=>vU,SchemaValidationError:()=>l1,PluginError:()=>dU,PerformanceMonitor:()=>oU,FileSystemError:()=>nU,ErrorFactory:()=>Jw,EnvVarError:()=>vY,EnvProcessor:()=>aY,ConfigValidator:()=>A8,ConfigValidationError:()=>cU,ConfigNotFoundError:()=>nY,ConfigMergeError:()=>uU,ConfigLoader:()=>Y8,ConfigLoadError:()=>d1,ConfigFileLoader:()=>sY,ConfigCache:()=>sU,CacheUtils:()=>aE,BunfigError:()=>r0,BrowserConfigError:()=>mU,ArrayMergeStrategies:()=>eE});F5=FH(async()=>{rE=import.meta.require,W1=new sU,t1=new oU,aE={createKey:zH,isEquivalent:GH,estimateMemoryUsage:HH},uH=ZY(xU.cwd(),"config"),nH=ZY(xU.cwd(),"src/generated"),fE=kY.env.CLARITY_LOG_DIR||OG(NH(),"logs"),SY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:fE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},iU=await qH(),V0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},p=V0,vH=V0.red,XE=V0.green,mH=V0.yellow,UE=V0.blue,dH=V0.magenta,lH=V0.cyan,CU=V0.white,gH=V0.gray,JE=V0.bgRed,WE=V0.bgYellow,SU=V0.bold,tH=V0.dim,pH=V0.italic,rH=V0.underline,aH=V0.reset,LY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},sE={debug:"\uD83D\uDD0D",info:UE("ℹ"),success:XE("✓"),warning:WE(CU(SU(" WARN "))),error:JE(CU(SU(" ERROR ")))},sH=new bY("stacks"),O0=new bY("bunfig",{showTags:!0}),oH=P0(m1.cwd(),"config"),eH=P0(m1.cwd(),"src/generated"),BE=DY.env.CLARITY_LOG_DIR||LG(IH(),"logs"),VY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:BE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bU=await CH(),G0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},x=G0,$5=G0.red,EE=G0.green,w5=G0.yellow,jE=G0.blue,A5=G0.magenta,Y5=G0.cyan,LU=G0.white,f5=G0.gray,TE=G0.bgRed,FE=G0.bgYellow,X5=G0.bgGray,VU=G0.bold,U5=G0.dim,J5=G0.italic,W5=G0.underline,B5=G0.strikethrough,E5=G0.reset,OY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},oE={debug:"\uD83D\uDD0D",info:jE("ℹ"),success:EE("✓"),warning:FE(LU(VU(" WARN "))),error:TE(LU(VU(" ERROR ")))},j5=new uY("stacks"),r0=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},nY=class extends r0{code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A?` or alias "${A}"`:"";super(`Configuration "${$}"${Y} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},d1=class extends r0{code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}},cU=class extends r0{code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},uU=class extends r0{code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},vY=class extends r0{code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}},nU=class extends r0{code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}},vU=class extends r0{code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}},l1=class extends r0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},mU=class extends r0{code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}},dU=class extends r0{code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}},Jw={configNotFound($,w,A){return new nY($,w,A)},configLoad($,w,A){return new d1($,w,A)},configValidation($,w,A){return new cU($,w,A)},configMerge($,w,A,Y){return new uU($,w,A,Y)},envVar($,w,A,Y){return new vY($,w,A,Y)},fileSystem($,w,A){return new nU($,w,A)},typeGeneration($,w,A){return new vU($,w,A)},schemaValidation($,w,A){return new l1($,w,A)},browserConfig($,w,A,Y){return new mU($,w,A,Y)},plugin($,w,A){return new dU($,w,A)}},eE={replace:"replace",concat:"concat",smart:"smart"},$j=/^https?:\/\//,R$=new uY("bunfig",{showTags:!0}),m$=new Y8,wj=i0(yw.cwd(),"config"),Aj=i0(yw.cwd(),"src/generated")});G5=xY.env.CLARITY_LOG_DIR||sG(z5(),"logs"),Yj={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:G5,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mY={...Yj},my=(async()=>{try{let{loadConfig:$}=await F5().then(()=>uE),w=await $({name:"clarity",alias:"logging",defaultConfig:Yj,cwd:xY.cwd()});if(w)Object.assign(mY,w)}catch{}return mY})();y0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},c=y0,dy=y0.red,K5=y0.green,ly=y0.yellow,R5=y0.blue,gy=y0.magenta,ty=y0.cyan,zE=y0.white,py=y0.gray,N5=y0.bgRed,q5=y0.bgYellow,ry=y0.bgGray,GE=y0.bold,ay=y0.dim,sy=y0.italic,oy=y0.underline,ey=y0.strikethrough,$M=y0.reset,OU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},h5={debug:"\uD83D\uDD0D",info:R5("ℹ"),success:K5("✓"),warning:q5(zE(GE(" WARN "))),error:N5(zE(GE(" ERROR ")))};wM=new oY("stacks");h$=class h$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};Xj=class Xj extends h${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],f="";if(Y.length===1)f=` or alias "${Y[0]}"`;else if(Y.length>1)f=` or aliases ${Y.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${f} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};dY=class dY extends h${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};Uj=class Uj extends h${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};Jj=class Jj extends h${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};f8=class f8 extends h${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};Wj=class Wj extends h${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};Bj=class Bj extends h${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};lY=class lY extends h${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};Ej=class Ej extends h${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};jj=class jj extends h${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};B1={configNotFound($,w,A){return new Xj($,w,A)},configLoad($,w,A){return new dY($,w,A)},configValidation($,w,A){return new Uj($,w,A)},configMerge($,w,A,Y){return new Jj($,w,A,Y)},envVar($,w,A,Y){return new f8($,w,A,Y)},fileSystem($,w,A){return new Wj($,w,A)},typeGeneration($,w,A){return new Bj($,w,A)},schemaValidation($,w,A){return new lY($,w,A)},browserConfig($,w,A,Y){return new Ej($,w,A,Y)},plugin($,w,A){return new jj($,w,A)}};V5=/^https?:\/\//;b$=new oY("bunfig",{showTags:!0});AM=new Kj;YM=U$(rY.cwd(),"config"),fM=U$(rY.cwd(),"src/generated"),Rj={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:EU.join(BU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:EU.join(BU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:EU.join(BU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},W0=Rj,N$={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"},C={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},J1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};k5=D5(_5);Z5=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),x5=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;q$={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},b0={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"};AK={platform:"darwin",async addCertificate($,w){if(await wK($,w?.verbose)){M(C.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),J1.success("Certificate is already trusted in system keychain");return}M(C.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Uw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let Y=A||W0.commonName;M(C.TRUST,`Removing certificate ${Y} from macOS keychain`,w?.verbose);try{await Uw(`sudo security delete-certificate -c "${Y}" /Library/Keychains/System.keychain`),M(C.TRUST,`Removed certificate ${Y} from macOS keychain`,w?.verbose)}catch(f){throw M(C.TRUST,`Error removing certificate: ${f}`,w?.verbose),f}}},YK={platform:"win32",async addCertificate($,w){M(C.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Uw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let Y=A||W0.commonName;M(C.TRUST,`Removing certificate ${Y} from Windows certificate store`,w?.verbose);try{await Uw(`certutil -delstore -enterprise Root "${Y}"`),M(C.TRUST,`Removed certificate ${Y} from Windows certificate store`,w?.verbose)}catch(f){throw M(C.TRUST,`Error removing certificate: ${f}`,w?.verbose),f}}},fK={platform:"linux",async addCertificate($,w){M(C.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=tY.homedir(),Y=N$.LINUX_CERT_DB_FILENAME,f=N$.LINUX_TRUST_ARGS;M(C.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let X=gU(A,Y);if(X.length===0){J1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of X){M(C.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{M(C.TRUST,`Attempting to delete existing cert for ${W0.commonName}`,w?.verbose),await Uw(`certutil -d sql:${U} -D -n ${W0.commonName}`)}catch(W){M(C.TRUST,`Warning: Error deleting existing cert: ${W}`,w?.verbose),console.warn(`Error deleting existing cert: ${W}`)}M(C.TRUST,`Adding new certificate to ${U}`,w?.verbose),await Uw(`certutil -d sql:${U} -A -t ${f} -n ${W0.commonName} -i ${$}`),J1.info(`Cert added to ${U}`)}},async removeCertificate($,w,A){let Y=A||W0.commonName;M(C.TRUST,`Removing certificate ${Y} from Linux certificate store`,w?.verbose);let f=tY.homedir(),X=N$.LINUX_CERT_DB_FILENAME;M(C.TRUST,`Searching for certificate databases in ${f}`,w?.verbose);let U=gU(f,X);if(U.length===0){J1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of U){M(C.TRUST,`Processing certificate database in ${W}`,w?.verbose);try{await Uw(`certutil -d sql:${W} -D -n "${Y}"`),J1.info(`Cert removed from ${W}`)}catch(J){M(C.TRUST,`Error removing cert from ${W}: ${J}`,w?.verbose),console.warn(`Error removing cert from ${W}: ${J}`)}}}},XK={darwin:AK,win32:YK,linux:fK}});var T8=E0(()=>{Qj()});import{homedir as F8}from"node:os";import{join as z8,resolve as wI}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",UK,G8;var H8=E0(()=>{XU();UK={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:z8(F8(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:z8(F8(),".stacks","ssl","stacks.localhost.crt"),keyPath:z8(F8(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},G8=UK});import{execSync as JK}from"node:child_process";function Dj($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function $f($){try{let w=JK(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return Dj(w)}catch{return null}}var K8=()=>{};import{existsSync as kj,statSync as Zj}from"fs";import{existsSync as P8,mkdirSync as FK,readdirSync as zK,writeFileSync as GK}from"fs";import{homedir as j1}from"os";import{dirname as xj,resolve as u0}from"path";import Mw from"process";import{join as HK,relative as KK,resolve as Pj}from"path";import Kf from"process";import{existsSync as RT,mkdirSync as zI,readdirSync as GI,writeFileSync as HI}from"fs";import{homedir as R8}from"os";import{dirname as NI,resolve as c0}from"path";import r1 from"process";import{join as RK,relative as NK,resolve as ij}from"path";import Rf from"process";import{existsSync as NT,mkdirSync as II,readdirSync as CI,writeFileSync as SI}from"fs";import{dirname as VI,resolve as Nf}from"path";import i8 from"process";import{Buffer as Bw}from"buffer";import{createCipheriv as qK,createDecipheriv as hK,randomBytes as N8}from"crypto";import{closeSync as q8,createReadStream as bj,createWriteStream as yK,existsSync as h8,fsyncSync as cj,openSync as uj,writeFileSync as MK}from"fs";import{access as IK,constants as nj,mkdir as CK,readdir as wf,rename as vj,stat as T1,unlink as Af,writeFile as y8}from"fs/promises";import{join as F1}from"path";import _0 from"process";import{pipeline as SK}from"stream/promises";import{createGzip as mj}from"zlib";import z1 from"process";import g$ from"process";import{Buffer as d$}from"buffer";import{createCipheriv as LK,createDecipheriv as VK,randomBytes as M8}from"crypto";import{closeSync as I8,createReadStream as dj,createWriteStream as OK,existsSync as Yf,fsyncSync as lj,openSync as gj,writeFileSync as _K}from"fs";import{access as QK,constants as tj,mkdir as DK,readdir as ff,rename as pj,stat as G1,unlink as Xf,writeFile as C8}from"fs/promises";import{isAbsolute as kK,join as H1,resolve as ZK}from"path";import D from"process";import{pipeline as xK}from"stream/promises";import{createGzip as rj}from"zlib";import K1 from"process";import t$ from"process";import Uf from"process";import{existsSync as Jf}from"fs";import{resolve as S8}from"path";import{existsSync as PK}from"fs";import{existsSync as iK,readdirSync as bK}from"fs";import{extname as L8,resolve as aj}from"path";import cK from"process";import{join as u6,relative as n6,resolve as WT}from"path";import Sf from"process";import{Buffer as l$}from"buffer";import{createCipheriv as d6,createDecipheriv as l6,randomBytes as D8}from"crypto";import{closeSync as k8,createReadStream as BT,createWriteStream as g6,existsSync as Bf,fsyncSync as ET,openSync as jT,writeFileSync as t6}from"fs";import{access as p6,constants as TT,mkdir as r6,readdir as Ef,rename as FT,stat as R1,unlink as jf,writeFile as Z8}from"fs/promises";import{isAbsolute as a6,join as N1,resolve as s6}from"path";import k from"process";import{pipeline as o6}from"stream/promises";import{createGzip as zT}from"zlib";import q1 from"process";import p$ from"process";function EK($,w){this[$]=BK.bind(null,w)}class t8{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let f=this.generateKey($,A),X=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(f,{value:w,timestamp:new Date,ttl:X,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!kj($))return!0;return Zj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let f=kj(A)?Zj(A):null,X=f?f.mtime:new Date;this.set($,{value:w,fileTimestamp:X},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,f)=>Y+f.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,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:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class p8{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),f=new Date;try{let X=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:f,...A}),X}catch(X){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:f,...A}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((f)=>f.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((f)=>f.duration),Y=A.reduce((f,X)=>f+X,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function uK($,w={}){let Y=Object.keys(w).sort().map((f)=>`${f}:${w[f]}`).join("|");return Y?`${$}:${Y}`:$}function nK($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function vK($){return $.getStats().size*2}function r8($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let Y=[...w];for(let f of $)if($0(f)&&"name"in f){if(!Y.find((U)=>$0(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if($0(f)&&"path"in f){if(!Y.find((U)=>$0(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>qf(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!$0(w)||!$0($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if($0(f)&&$0(A[Y]))A[Y]=r8(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&$0(f[0])&&$0(A[Y][0])){let X=[...f];for(let U of A[Y])if($0(U)&&"name"in U){if(!X.find((J)=>$0(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if($0(U)&&"path"in U){if(!X.find((J)=>$0(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>qf(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function qf($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!qf($[A],w[A]))return!1;return!0}if($0($)&&$0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!qf($[f],w[f]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function mK($,w){if(!NT($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return r8(w,Y)}catch{return null}}catch{return null}}async function dK({name:$="",cwd:w,defaultConfig:A}){let Y=w||i8.cwd(),f=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of X)for(let W of f){let J=Nf(Y,`${U}${W}`),B=await mK(J,A);if(B!==null)return B}try{let U=Nf(Y,"package.json");if(NT(U)){let J=(await import(U))[$];if(J&&typeof J==="object"&&!Array.isArray(J))try{return r8(A,J)}catch{}}}catch{}return A}function lK($,w={}){let A=Rf.cwd();while(A.includes("storage"))A=ij(A,"..");let Y=ij(A,$||"");if(w?.relative)return NK(Rf.cwd(),Y);return Y}async function gK(){try{let $=await dK({name:"clarity",defaultConfig:Ff,cwd:Rf.cwd(),endpoint:"",headers:{}});return{...Ff,...$}}catch{return Ff}}function X0(){if(g$.env.NODE_ENV==="test"||g$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tK(){if(g$.env.NODE_ENV==="test"||g$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof g$<"u"){let $=g$.type;if($==="renderer"||$==="worker")return!1;return!!(g$.versions&&(g$.versions.node||g$.versions.bun))}return!1}class qT{async format($){let w=await tK(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:z1.pid,hostname:w(),environment:z1.env.NODE_ENV||"development",platform:z1.platform,version:z1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:z1.env.NODE_ENV||z1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class hf{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($,w={}){this.name=$,this.config={...c8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new qT,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...zf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...zf};return{...zf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:c8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await IK(this.config.logDirectory,nj.F_OK|nj.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await CK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Bw.from($);try{if(!h8(this.currentLogFile))await y8(this.currentLogFile,"",{mode:420});if(f=uj(this.currentLogFile,"a",420),MK(f,J,{flag:"a"}),cj(f),f!==void 0)q8(f),f=void 0;if((await T1(this.currentLogFile)).size===0){if(await y8(this.currentLogFile,J,{flag:"w",mode:420}),(await T1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{q8(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 F1(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 F1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return F1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(X0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return N8(16).toString("hex")}generateKey(){return N8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=N8(16),Y=qK("aes-256-gcm",w,A),f=Bw.concat([Y.update($,"utf8"),Y.final()]),X=Y.getAuthTag();return{encrypted:Bw.concat([A,f,X]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=mj(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(Bw.from(Bw.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(X0())return;let $=await T1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await wf(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await T1(A).catch(()=>null))try{if(await vj(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await Af(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await y8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await T1(A).catch(()=>null))await vj(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await wf(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await Af(F1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=bj($),Y=yK(w),f=mj();await SK(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),h8(this.currentLogFile))try{let $=uj(this.currentLogFile,"r+");cj($),q8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!X0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await wf(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await Af(F1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?r.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=_0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${r.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!X0()){let B=_T[$],E=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",j;switch($){case"debug":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:r.gray(U),level:$}),console.error(j);break;case"info":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j);break;case"success":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:r.green(U),level:$}),console.error(j);break;case"warning":j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.warn(j);break;case"error":if(j=this.formatConsoleMessage({timestamp:f,icon:B,tag:E,message:U,level:$}),console.error(j),W){let T=W.split(`
|
|
133
|
-
`);for(let
|
|
134
|
-
`;if(W)J+=`${W}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||X0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(X0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await wf(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=F1(this.config.logDirectory,Y);if($.before)try{if((await T1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await Af(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function Tf($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&g(w[0])&&"id"in w[0]&&w[0].id===3&&g(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(g(w)&&g($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(g($)&&"arr"in $&&Array.isArray($.arr)&&g(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&g(w[0])&&g($[0])){let Y=[...w];for(let f of $)if(g(f)&&"name"in f){if(!Y.find((U)=>g(U)&&("name"in U)&&U.name===f.name))Y.push(f)}else if(g(f)&&"path"in f){if(!Y.find((U)=>g(U)&&("path"in U)&&U.path===f.path))Y.push(f)}else if(!Y.some((X)=>yf(X,f)))Y.push(f);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}if(!g(w)||!g($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let f=w[Y];if(f===null||f===void 0)continue;else if(g(f)&&g(A[Y]))A[Y]=Tf(A[Y],f);else if(Array.isArray(f)&&Array.isArray(A[Y]))if(f.length>0&&A[Y].length>0&&g(f[0])&&g(A[Y][0])){let X=[...f];for(let U of A[Y])if(g(U)&&"name"in U){if(!X.find((J)=>g(J)&&("name"in J)&&J.name===U.name))X.push(U)}else if(g(U)&&"path"in U){if(!X.find((J)=>g(J)&&("path"in J)&&J.path===U.path))X.push(U)}else if(!X.some((W)=>yf(W,U)))X.push(U);A[Y]=X}else if(f.every((X)=>typeof X==="string")&&A[Y].every((X)=>typeof X==="string")){let X=[...f];for(let U of A[Y])if(!X.includes(U))X.push(U);A[Y]=X}else A[Y]=f;else A[Y]=f}return A}function a8($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:Tf($,w);if(Array.isArray($))return A==="replace"?w:Tf($,w);if(!g(w)||!g($))return w;let Y={...$};for(let f of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,f))continue;let X=w[f],U=Y[f];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(U))if(A==="replace")Y[f]=X;else Y[f]=Tf(U,X);else if(g(X)&&g(U))Y[f]=a8(U,X,A);else Y[f]=X}return Y}function yf($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!yf($[A],w[A]))return!1;return!0}if(g($)&&g(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!yf($[f],w[f]))return!1}return!0}return!1}function g($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Wf($,w,A="replace"){if(!RT($))return null;try{let Y=await import($),f=Y.default||Y;if(typeof f!=="object"||f===null||Array.isArray(f))return null;try{return a8(w,f,A)}catch{return null}}catch{return null}}function pK($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),f={...w};function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=(G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${j.map(T).join("_")}`,H=`${Y}_${j.map((G)=>G.toUpperCase()).join("_")}`;if(A)D0.info(`Checking environment variable ${F} for config ${$}.${j.join(".")}`);if(typeof E==="object"&&E!==null&&!Array.isArray(E))J[B]=X(E,j);else{let G=r1.env[F]||r1.env[H];if(G!==void 0){if(A)D0.info(`Using environment variable ${G?F:H} for config ${$}.${j.join(".")}`);if(typeof E==="number")J[B]=Number(G);else if(typeof E==="boolean")J[B]=G.toLowerCase()==="true";else if(Array.isArray(E))try{let K=JSON.parse(G);if(Array.isArray(K))J[B]=K;else J[B]=G.split(",").map((R)=>R.trim())}catch{J[B]=G.split(",").map((K)=>K.trim())}else J[B]=G}}}return J}return X(f)}async function rK({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:f,verbose:X=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let J=U&&typeof f==="object"&&f!==null&&!Array.isArray(f)?pK($,f,X):f,B=A||r1.cwd(),E=[".ts",".js",".mjs",".cjs",".json"];if(X)D0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let j=[$,`.${$}`].filter(Boolean),T=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],H=w?[`${w}.config`,`.${w}.config`]:[],G=Array.from(new Set([B,c0(B,"config"),c0(B,".config"),Y?c0(B,Y):void 0].filter(Boolean)));for(let K of G){if(X)D0.info(`Searching for configuration in: ${K}`);let N=[c0(B,"config"),c0(B,".config")].concat(Y?[c0(B,Y)]:[]).includes(K)?[...j,...T,...F,...H]:[...T,...j,...H,...F];for(let h of N)for(let y of E){let I=c0(K,`${h}${y}`),S=await Wf(I,J,W);if(S!==null){if(X)D0.success(`Configuration loaded from: ${I}`);return S}}}if($){let K=c0(R8(),".config",$),R=["config",`${$}.config`];if(w)R.push(`${w}.config`);if(X)D0.info(`Checking user config directory: ${K}`);for(let N of R)for(let h of E){let y=c0(K,`${N}${h}`),I=await Wf(y,J,W);if(I!==null){if(X)D0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let K=c0(R8(),".config"),R=[`.${$}.config`];if(w)R.push(`.${w}.config`);if(X)D0.info(`Checking user config directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=c0(K,`${N}${h}`),I=await Wf(y,J,W);if(I!==null){if(X)D0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let K=R8(),R=[`.${$}.config`,`.${$}`];if(w)R.push(`.${w}.config`),R.push(`.${w}`);if(X)D0.info(`Checking user home directory for dotfile configs: ${K}`);for(let N of R)for(let h of E){let y=c0(K,`${N}${h}`),I=await Wf(y,J,W);if(I!==null){if(X)D0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let K=c0(B,"package.json");if(RT(K)){let R=await import(K),N=R[$];if(!N&&w){if(N=R[w],N&&X)D0.success(`Using alias "${w}" configuration from package.json`)}if(N&&typeof N==="object"&&!Array.isArray(N))try{if(X)D0.success(`Configuration loaded from package.json: ${N===R[$]?$:w}`);return a8(J,N,W)}catch(h){if(X)D0.warn("Failed to merge package.json config:",h)}}}catch(K){if(X)D0.warn("Failed to load package.json:",K)}if(X)D0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return J}function aK($,w={}){let A=Kf.cwd();while(A.includes("storage"))A=Pj(A,"..");let Y=Pj(A,$||"");if(w?.relative)return KK(Kf.cwd(),Y);return Y}async function sK(){try{let $=await rK({name:"clarity",alias:"logging",defaultConfig:Gf,cwd:Kf.cwd()});return{...Gf,...$||{}}}catch{return Gf}}function K0(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function oK(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t$<"u"){let $=t$.type;if($==="renderer"||$==="worker")return!1;return!!(t$.versions&&(t$.versions.node||t$.versions.bun))}return!1}class hT{async format($){let w=await oK(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:K1.pid,hostname:w(),environment:K1.env.NODE_ENV||"development",platform:K1.platform,version:K1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:K1.env.NODE_ENV||K1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Mf{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...u8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new hT,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Hf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Hf};return{...Hf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:u8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!K0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await QK(this.config.logDirectory,tj.F_OK|tj.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await DK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:d$.from($);try{if(!Yf(this.currentLogFile))await C8(this.currentLogFile,"",{mode:420});if(f=gj(this.currentLogFile,"a",420),_K(f,J,{flag:"a"}),lj(f),f!==void 0)I8(f),f=void 0;if((await G1(this.currentLogFile)).size===0){if(await C8(this.currentLogFile,J,{flag:"w",mode:420}),(await G1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{I8(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 H1(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 H1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return H1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(K0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return M8(16).toString("hex")}generateKey(){return M8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=M8(16),Y=LK("aes-256-gcm",w,A),f=d$.isBuffer($)?$:d$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=d$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=rj(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(d$.from(d$.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(K0())return;if(!this.shouldWriteToFile())return;let $=await G1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await ff(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await G1(A).catch(()=>null))try{if(await pj(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await Xf(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await C8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await G1(A).catch(()=>null))await pj(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await ff(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await Xf(H1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=dj($),Y=OK(w),f=rj();await xK(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),Yf(this.currentLogFile))try{let $=gj(this.currentLogFile,"r+");lj($),I8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!K0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await ff(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await Xf(H1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||K0())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=D.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${P.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=P.underline(P.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>P.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>P.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>P.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>P.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>P.strikethrough(Y)),w}supportsHyperlinks(){if(K0())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=D.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(kK(w)||w.startsWith("./")||w.startsWith("../"))w=ZK(w);else return null;return Yf(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":QT[$],T=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:P.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:P.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
141
|
-
|
|
142
|
-
`;if(W)E+=`${W}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
`)
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
`,
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
`;
|
|
159
|
-
|
|
160
|
-
`;
|
|
161
|
-
`;return A}}function w6($,w){let A=VT("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function IT($,w,A={}){return CT($,w,A,new WeakMap)}function CT($,w,A,Y){let{arrayMergeMode:f="replace",skipNullish:X=!1,customMerger:U}=A;if(w===null||w===void 0)return X?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return ST($,w,f,Y);if(!B$(w)||!B$($))return w;return X6($,w,A,Y)}function ST($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return A6($,w);case"smart":return Y6($,w,Y);default:return w}return w}function A6($,w){let A=[...w];for(let Y of $)if(!A.some((f)=>b8(f,Y)))A.push(Y);return A}function Y6($,w,A){if(w.length===0)return $;if($.length===0)return w;if(B$(w[0])&&B$($[0]))return f6($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let f of $)if(!Y.includes(f))Y.push(f);return Y}return w}function f6($,w,A){let Y=[...w];for(let f of $){if(!B$(f)){Y.push(f);continue}let X=["id","name","key","path","type"],U=!1;for(let W of X)if(W in f){if(Y.find((B)=>B$(B)&&(W in B)&&B[W]===f[W])){U=!0;break}}if(!U)Y.push(f)}return Y}function X6($,w,A,Y){let f=w;if(B$(f)&&Y.has(f))return Y.get(f);let X={...$};if(B$(f))Y.set(f,X);for(let U in f){if(!Object.prototype.hasOwnProperty.call(f,U))continue;let W=f[U],J=X[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[U]=W;continue}if(B$(W)&&B$(J))X[U]=CT(J,W,A,Y);else if(Array.isArray(W)||Array.isArray(J))X[U]=ST(J,W,A.arrayMergeMode||"smart",Y);else X[U]=W}return X}function s8($,w,A="replace"){return IT($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function b8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!b8($[A],w[A]))return!1;return!0}if(B$($)&&B$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let f of A){if(!Object.prototype.hasOwnProperty.call(w,f))return!1;if(!b8($[f],w[f]))return!1}return!0}return!1}function B$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class Of{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:f=!0,cacheTtl:X,trackPerformance:U=!0,verbose:W=!1}=A;if(f){let B=h1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let J=async()=>{if(!Jf($))return null;try{let B=`?t=${Date.now()}`,E=await import($+B),j=E.default||E,T="default"in E,F=Object.keys(E).length>0;if(!T&&!F)throw new a1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof j!=="object"||j===null||Array.isArray(j))throw new a1($,Error("Configuration must export a valid object"),"unknown");let K={config:s8(w,j,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(f)h1.setWithFileCheck("file",K,$,X);return K}catch(B){throw B instanceof Error?Ew.configLoad($,B):Ew.configLoad($,Error(String(B)))}};if(U)return o1.track("loadFromPath",J,{path:$});return J()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let f=await this.loadFromPath(Y,w,A);if(f)return f}catch(f){if(f instanceof Error&&f.name==="ConfigLoadError")throw f;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,f)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),f=[];for(let X of Y)for(let U of this.extensions)f.push(S8(w,`${X}${U}`));return f}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return yT(async()=>{return Jf($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!Jf($))return Y;if(w||A){let f=this.generateNamePatterns(w||"",A);for(let X of f)for(let U of this.extensions){let W=S8($,`${X}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:f}=await import("fs"),X=f($);for(let U of X)if(this.looksLikeConfigFile(U)){let W=S8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){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((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!Jf($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:f}=await import("fs"),X=f($,"utf8");JSON.parse(X)}catch(f){w.push(`Invalid JSON syntax: ${f}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let f=await this.loadFromPath(Y,{},w);if(f)A.set(Y,f.config)}catch(f){if(w.verbose)console.warn(`Failed to preload ${Y}:`,f)}})),A}}class o8{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:f=!0,validateTypes:X=!0,customRules:U=[],trackPerformance:W=!0,verbose:J=!1}=A,B=async()=>{let E=[],j=[],T={stopOnFirstError:Y,validateRequired:f,validateTypes:X,customRules:U,trackPerformance:W,verbose:J};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,T);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],T);else return this.validateWithJSONSchema($,w,T)}catch(F){return E.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:E,warnings:j}}};if(W)return await o1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!PK(w))throw new s1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),f=Y.default||Y;if(Array.isArray(f))return this.validateWithRules($,f,A);else return this.validateWithJSONSchema($,f,A)}catch(Y){throw new s1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],f=[];return this.validateObjectAgainstSchema($,w,"",Y,f,A),{isValid:Y.length===0,errors:Y,warnings:f}}validateObjectAgainstSchema($,w,A,Y,f,X){if(X.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,f,X),X.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,J]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],J,B,Y,f,X),X.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let J of Object.keys(U))if(!W.has(J))f.push({path:A?`${A}.${J}`:J,message:`Additional property '${J}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],f=[];for(let X of w)try{let U=this.getValueByPath($,X.path),W=this.validateWithRule(U,X,X.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:X.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:f}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let f=Array.isArray($)?"array":typeof $;if(f!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${f}`,expected:w.type,actual:f,rule:"type"})}if(w.min!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:f,rule:"min"})}if(w.max!==void 0){let f=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(f>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:f,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let f=w.validator($);if(f)Y.push({path:A,message:w.message||f,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let f of A)if(Y&&typeof Y==="object"&&f in Y)Y=Y[f];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,f,X,U]=Y;w.push({path:f,required:!X,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.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:kT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class e8{fileLoader=new Of;envProcessor=new Vf;validator=new o8;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:f,validate:X,...U}=$;try{if(A?.enabled){let J=this.checkCache(U.name||"",U);if(J)return J}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(J){let B=U.__strictErrorHandling;if(J instanceof Error&&J.name==="ConfigNotFoundError"){if(B)throw J;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(J instanceof Error&&J.name==="ConfigLoadError"){let E=J.message.includes("EACCES")||J.message.includes("EPERM")||J.message.includes("permission denied"),j=!E&&(J.message.includes("syntax")||J.message.includes("Expected")||J.message.includes("Unexpected")||J.message.includes("BuildMessage")||J.message.includes("errors building")),T=J.message.includes("Configuration must export a valid object")||J.message.includes("Configuration file is empty and exports nothing");if(B&&(T||E))throw J;if(j&&(!B||!T))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${J.message}`]};else throw J}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${J instanceof Error?J.message:String(J)}`]}}if(f||X)await this.validateConfiguration(W.config,f,X,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let J={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(J);if(Y.slowThreshold&&J.duration>Y.slowThreshold)y$.warn(`Slow configuration loading detected: ${J.duration}ms for ${U.name}`);W.metrics=J}return W}catch(W){let J=Date.now()-w;throw y$.error(`Configuration loading failed after ${J}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:f,cwd:X,configDir:U,defaultConfig:W,checkEnv:J=!0,arrayStrategy:B="replace",verbose:E=!1}=$,j=X||Mw.cwd(),T=[],F=await this.loadLocalConfiguration(Y,f,j,U,W,B,E,J,A);if(F)return T.push(...this.getLocalSearchPaths(Y,f,j,U)),this.finalizeResult(F,T,J,Y,E);let H=await this.loadHomeConfiguration(Y,f,W,B,E,J);if(H)return T.push(...this.getHomeSearchPaths(Y,f)),this.finalizeResult(H,T,J,Y,E);let G=await this.loadPackageJsonConfiguration(Y,f,j,W,B,E,J);if(G)return T.push(u0(j,"package.json")),this.finalizeResult(G,T,J,Y,E);if(T.push(...this.getAllSearchPaths(Y,f,j,U)),w)throw Ew.configNotFound(Y,T,f);return{...await this.applyEnvironmentVariables(Y,W,J,E),warnings:[`No configuration file found for "${Y}"${f?` or alias "${f}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,f,X,U,W,J){let B=W?p1($,f,U):f,E=this.getLocalDirectories(A,Y);for(let j of E){if(U)y$.info(`Searching for configuration in: ${j}`);let T=this.fileLoader.generateConfigPaths($,j,w),F=await this.fileLoader.tryLoadFromPaths(T,B,{arrayStrategy:X,verbose:U,cacheTtl:J?.ttl,useCache:!J?.ttl||J.ttl>100});if(F){if(U)y$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,f,X){if(!$)return null;let U=X?p1($,A,f):A,W=[u0(j1(),".config",$),u0(j1(),".config"),j1()];for(let J of W){if(f)y$.info(`Checking home directory: ${J}`);let B=this.fileLoader.generateConfigPaths($,J,w),E=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:f});if(E){if(f)y$.success(`Configuration loaded from home directory: ${E.source.path}`);return E}}return null}async loadPackageJsonConfiguration($,w,A,Y,f,X,U){let W=U?p1($,Y,X):Y;try{let J=u0(A,"package.json");if(!P8(J))return null;let B=await import(J),E=B[$],j=$;if(!E&&w)E=B[w],j=w;if(E&&typeof E==="object"&&!Array.isArray(E)){if(X)y$.success(`Configuration loaded from package.json: ${j}`);return{config:s8(W,E,f),source:{type:"package.json",path:J,priority:30,timestamp:new Date}}}}catch(J){if(X)y$.warn("Failed to load package.json:",[J instanceof Error?J:Error(String(J))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:p1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,f){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let f=[];if(A){let X=A($);if(X)f.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)f.push(...X.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(f.length>0)throw Ew.configValidation(Y||"unknown",f,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return h1.get(A)||null}cacheResult($,w,A,Y){let f=this.generateCacheKey($,Y);h1.set(f,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,u0($,"config"),u0($,".config"),w?u0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let f=[];return f.push(...this.getLocalSearchPaths($,w,A,Y)),f.push(...this.getHomeSearchPaths($,w)),f.push(u0(A,"package.json")),f}getLocalSearchPaths($,w,A,Y){let f=this.getLocalDirectories(A,Y),X=[];for(let U of f)X.push(...this.fileLoader.generateConfigPaths($,U,w));return X}getHomeSearchPaths($,w){if(!$)return[];let A=[u0(j1(),".config",$),u0(j1(),".config"),j1()],Y=[];for(let f of A)Y.push(...this.fileLoader.generateConfigPaths($,f,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function sj($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function U6($){return r$.loadConfig({...$,__strictErrorHandling:!0})}async function LT($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await r$.loadConfig($);else Y=await r$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let f=Y instanceof Error?Y.name:"UnknownError",X=Y instanceof Error?Y.message:String(Y);if(!(f==="ConfigNotFoundError"||f==="ConfigLoadError"||f==="ConfigValidationError"||X.includes("config"))&&$.verbose)y$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await r$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function J6($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await r$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&sj(A)))return(await r$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await r$.loadConfig({...$,cwd:$.cwd||Mw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&sj(w)))return(await r$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function W6($,w,A="replace"){let Y=new Of;try{let f=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return f?f.config:null}catch{return null}}function p1($,w,A=!1){let Y=new Vf,f=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(U,W=[]){let J={...U};for(let[B,E]of Object.entries(U)){let j=[...W,B],T=[`${f}_${j.join("_").toUpperCase()}`,`${f}_${j.map((G)=>G.toUpperCase()).join("")}`,`${f}_${j.map((G)=>G.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,H;for(let G of T)if(F=Mw.env[G],F!==void 0){H=G;break}if(F!==void 0&&H)if(typeof E==="boolean")J[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof E==="number"){let G=Number(F);if(!Number.isNaN(G))J[B]=G}else if(Array.isArray(E))try{J[B]=JSON.parse(F)}catch{J[B]=F.split(",").map((G)=>G.trim())}else J[B]=F;else if(E&&typeof E==="object"&&!Array.isArray(E))J[B]=X(E,j)}return J}return X(w)}function B6($){let w=u0(Mw.cwd(),$.configDir),A=u0(Mw.cwd(),$.generatedDir),Y=u0(A,"config-types.ts");if(!P8(xj(Y)))FK(xj(Y),{recursive:!0,mode:511});let f=P8(w)?zK(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${b6}
|
|
162
|
-
|
|
163
|
-
`;GK(Y,X,{mode:438})}function E6($){let w=null,A=null,Y=()=>{if(!A)A=LT($).then((X)=>{return w=X,X},(X)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)y$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return U});return A},f="defaultConfig"in $?$.defaultConfig:{};return w=f,Y(),new Proxy({},{get(X,U){if(w)return w[U];let W=f[U];return Y(),W},has(X,U){return U in(w||f)},ownKeys(){return Object.keys(w||f)},getOwnPropertyDescriptor(X,U){return Object.getOwnPropertyDescriptor(w||f,U)},set(X,U,W){if(!w)w={...f};return w[U]=W,!0}})}function j6($){let w=aj(cK.cwd(),$?.configDir||"./config");function A(){if(!iK(w))return[];let f=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=bK(w).filter((J)=>f.has(L8(J))).map((J)=>({base:J.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:J})),W=new Map;for(let{base:J,file:B}of U){let E=L8(B).toLowerCase(),j=W.get(J);if(!j){W.set(J,B);continue}let T=L8(j).toLowerCase();if(X.indexOf(E)<X.indexOf(T))W.set(J,B)}return Array.from(W.entries()).map(([J,B])=>({base:J,file:B})).sort((J,B)=>J.base.localeCompare(B.base))}function Y(){let f=A(),X=f.map((B)=>B.base),U=X.length?X.map((B)=>`'${B}'`).join(" | "):"string",W=f.length?`{
|
|
164
|
-
${
|
|
131
|
+
`}function SJ(){let $=F1.randomBytes(20);return $[0]=$[0]&127||1,$}function $9($=2048){let{privateKey:w,publicKey:Y}=F1.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:Y}}function a7($){let w=$.export({type:"spki",format:"der"});return F1.createHash("sha1").update(w).digest()}function w9($){let w={serialNumber:$.serialNumber||SJ(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:a7($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let Y=p7(w),A=t7(Y,$.signingKey);return{certificate:r7(A,"CERTIFICATE"),certificateDer:A}}function Y9($){return $.export({type:"pkcs8",format:"pem"})}function s7($){return F1.createPrivateKey($)}function o7($){let w=new F1.X509Certificate($),Y=w.publicKey,A=[],U=w.subject.split(`
|
|
132
|
+
`);for(let X of U){let[J,...W]=X.split("="),f=W.join("=");if(J&&f)A.push({shortName:J.trim(),value:f.trim()})}return{publicKey:Y,subject:A}}async function _J($={}){V("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||T$.DEFAULT_KEY_SIZE;V("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:Y,publicKey:A}=$9(w),U=[{shortName:"C",value:$.countryName||B0.countryName},{shortName:"ST",value:$.stateName||B0.stateName},{shortName:"L",value:$.localityName||B0.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:X,notAfter:J}=OJ({validityYears:$.validityYears||T$.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=w9({serialNumber:SJ(),notBefore:X,notAfter:J,subject:U,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:Y9(Y),notBefore:X,notAfter:J}}async function kJ($){if(V("ca","Generating new certificate",$.verbose),V("ca",`Options: ${GU($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=o7($.rootCA.certificate),Y=s7($.rootCA.privateKey);V("ca",`Generating ${T$.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let A=T$.DEFAULT_KEY_SIZE,{privateKey:U,publicKey:X}=$9(A),J=$.commonName||rz($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||B0.countryName},{shortName:"ST",value:$.stateName||B0.stateName},{shortName:"L",value:$.localityName||B0.localityName},{shortName:"O",value:$.organizationName||B0.organizationName},{shortName:"CN",value:J}],{notBefore:f,notAfter:B}=OJ({validityDays:$.validityDays||T$.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),j=az($),z=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},G=$.extKeyUsage||{serverAuth:!0},{certificate:F}=w9({serialNumber:SJ(),notBefore:f,notAfter:B,subject:W,issuer:w,publicKey:X,signingKey:Y,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:z,extendedKeyUsage:G,subjectAltName:j});return{certificate:F,privateKey:Y9(U),notBefore:f,notAfter:B}}function A9($,w){V(Q.STORAGE,`Storing certificate and private key with options: ${GU(w)}`,w?.verbose);let{certPath:Y,keyPath:A}=QJ({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});V(Q.STORAGE,`Certificate path: ${Y}`,w?.verbose),V(Q.STORAGE,`Private key path: ${A}`,w?.verbose);let U=TJ.dirname(Y);if(!m$.existsSync(U))V(Q.STORAGE,`Creating certificate directory: ${U}`,w?.verbose),m$.mkdirSync(U,{recursive:!0});V(Q.STORAGE,"Writing certificate file",w?.verbose),m$.writeFileSync(Y,$.certificate);let X=TJ.dirname(A);if(!m$.existsSync(X))V(Q.STORAGE,`Creating private key directory: ${X}`,w?.verbose),m$.mkdirSync(X,{recursive:!0});return V(Q.STORAGE,"Writing private key file",w?.verbose),m$.writeFileSync(A,$.privateKey),V(Q.STORAGE,"Certificate and private key stored successfully",w?.verbose),Y}function U9($,w){V(Q.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:Y}=QJ({basePath:w?.basePath,caCertPath:w?.caCertPath});V(Q.STORAGE,`CA certificate path: ${Y}`,w?.verbose);let A=TJ.dirname(Y);if(!m$.existsSync(A))V(Q.STORAGE,`Creating CA certificate directory: ${A}`,w?.verbose),m$.mkdirSync(A,{recursive:!0});return V(Q.STORAGE,"Writing CA certificate file",w?.verbose),m$.writeFileSync(Y,$),V(Q.STORAGE,"CA certificate stored successfully",w?.verbose),Y}function EU($){let w;if($.startsWith("-----BEGIN CERTIFICATE-----"))w=$;else w=pz($);return new e7.X509Certificate(w)}function KU($){return EU($).fingerprint256.replace(/:/g,"").toUpperCase()}function DJ($){return X9(EU($).subject)}function $T($){let w=[],Y=$.split(`
|
|
133
|
+
`);for(let A of Y){let[U,...X]=A.split("="),J=X.join("=");if(U&&J)w.push({shortName:U.trim(),value:J.trim()})}return w}function X9($){return $T($).find((w)=>w.shortName==="CN")?.value||""}function wT($){let w=[],Y=X9($.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))w.push(Y);let A=$.subjectAltName;if(A){let U=A.split(", ");for(let X of U)if(X.startsWith("DNS:"))w.push(X.slice(4))}return[...new Set(w)]}function ZJ($,w){let Y=EU($),A=wT(Y);for(let U of A){if(U===w)return!0;if(U.startsWith("*.")){let X=U.slice(2);if(w.endsWith(X)&&w.indexOf(".")===w.lastIndexOf("."))return!0}}return!1}async function AT($,w){if(fU.platform()!=="darwin")return!1;try{let Y=KU($);if(!Y)return V(Q.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(YT("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
|
|
134
|
+
`).some((A)=>{let U=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!U&&U[1].toUpperCase()===Y}))return V(Q.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return V(Q.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(Y){return V(Q.TRUST,`Error checking certificate trust: ${Y}`,w),!1}}async function xJ($,w,Y){V(Q.TRUST,`Adding certificate to system trust store with options: ${GU(Y)}`,Y?.verbose),V(Q.TRUST,"Storing certificate and private key",Y?.verbose);let A=A9($,Y);V(Q.TRUST,"Storing CA certificate",Y?.verbose);let U=U9(w,Y),X=fU.platform();V(Q.TRUST,`Detected platform: ${X}`,Y?.verbose);let J=fT[X];if(!J){let W=`Unsupported platform: ${X}`;throw V(Q.TRUST,`Error: ${W}`,Y?.verbose),Error(W)}return await J.addCertificate(U,Y),V(Q.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var XE,WU,ej="https://acme-staging-v02.api.letsencrypt.org/directory",$z="https://acme-v02.api.letsencrypt.org/directory",gA,zE="1.2.840.10045.2.1",FE="1.2.840.10045.3.1.7",GE="1.2.840.10045.4.3.2",EE="2.5.4.3",KE="1.2.840.113549.1.9.14",TE="2.5.29.17",aA,NJ,fK,WK=($)=>$,jK=($,w)=>{for(var Y in w)fK($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:BK.bind(w,Y)})},zK=($,w)=>()=>($&&(w=$($=0)),w),Gz,Iz,j1,WY,yz,uK,iK,Dj,cA,UJ,S0,a,cK,Zj,vK,xj,mK,dK,n8,gK,Pj,bj,p8,lK,nK,pK,tK,vA,Cz,rK,_0,aK,sK,uj,mA,XJ,H0,P,oK,ij,eK,cj,$7,w7,t8,Y7,vj,mj,A7,r8,U7,X7,J7,f7,W7,dA,hz,B7,j7="0.15.6",s0,wU,XY,JJ,fJ,YU,WJ,BJ,JY,jJ,zJ,jw,Vz,Lz,K$,d$,Qz,Oz,z7,G7,Sz,AU,Ny,y0,i,qy,K7,Ry,T7,My,Iy,dj,yy,H7,N7,Cy,gj,hy,Vy,Ly,Qy,Oy,a8,q7,Sy,N$,kz,UU,Dz,Zz,VJ,xz,Pz,XU,bz,uz,z1,V7,u$,_y,ky,Dy,lz,B0,T$,Q,B1,_7,lj="[redacted]",k7,D7,H$,v0,UT,XT,JT,fT;var J9=j0(()=>{XE=UE(import.meta.url);WU=new AY;gA=class gA extends Error{problem;httpStatus;constructor($,w,Y){super($);this.name="AcmeError",this.problem=w,this.httpStatus=Y}};aA=new zz,NJ=new Fz,fK=Object.defineProperty;Gz={};jK(Gz,{withErrorRecovery:()=>Tz,tryLoadConfig:()=>ZK,loadConfigWithResult:()=>kK,loadConfig:()=>Mz,isRetryableError:()=>VK,isConfigNotFoundError:()=>hK,isBunfigError:()=>Hz,globalPerformanceMonitor:()=>WY,globalCache:()=>j1,getEnvOrDefault:()=>LK,generateConfigTypes:()=>xK,defaultGeneratedDir:()=>Oz,defaultConfigDir:()=>Qz,deepMergeWithArrayStrategy:()=>yJ,deepMerge:()=>Nz,createLibraryConfig:()=>PK,config:()=>DK,bunfigPlugin:()=>bK,applyEnvVarsToConfig:()=>wY,TypeGenerationError:()=>BJ,SchemaValidationError:()=>JY,PluginError:()=>zJ,PerformanceMonitor:()=>RJ,FileSystemError:()=>WJ,ErrorFactory:()=>jw,EnvVarError:()=>YU,EnvProcessor:()=>jU,ConfigValidator:()=>CJ,ConfigValidationError:()=>JJ,ConfigNotFoundError:()=>wU,ConfigMergeError:()=>fJ,ConfigLoader:()=>hJ,ConfigLoadError:()=>XY,ConfigFileLoader:()=>zU,ConfigCache:()=>qJ,CacheUtils:()=>yz,BunfigError:()=>s0,BrowserConfigError:()=>jJ,ArrayMergeStrategies:()=>Vz});z7=zK(async()=>{Iz=import.meta.require,j1=new qJ,WY=new RJ,yz={createKey:FK,isEquivalent:GK,estimateMemoryUsage:EK},uK=tA(YJ.cwd(),"config"),iK=tA(YJ.cwd(),"src/generated"),Dj=pA.env.CLARITY_LOG_DIR||LE(HK(),"logs"),cA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Dj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},UJ=await NK(),S0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},a=S0,cK=S0.red,Zj=S0.green,vK=S0.yellow,xj=S0.blue,mK=S0.magenta,dK=S0.cyan,n8=S0.white,gK=S0.gray,Pj=S0.bgRed,bj=S0.bgYellow,p8=S0.bold,lK=S0.dim,nK=S0.italic,pK=S0.underline,tK=S0.reset,vA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Cz={debug:"\uD83D\uDD0D",info:xj("ℹ"),success:Zj("✓"),warning:bj(n8(p8(" WARN "))),error:Pj(n8(p8(" ERROR ")))},rK=new oA("stacks"),_0=new oA("bunfig",{showTags:!0}),aK=i0(UY.cwd(),"config"),sK=i0(UY.cwd(),"src/generated"),uj=nA.env.CLARITY_LOG_DIR||hE(IK(),"logs"),mA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},XJ=await yK(),H0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=H0,oK=H0.red,ij=H0.green,eK=H0.yellow,cj=H0.blue,$7=H0.magenta,w7=H0.cyan,t8=H0.white,Y7=H0.gray,vj=H0.bgRed,mj=H0.bgYellow,A7=H0.bgGray,r8=H0.bold,U7=H0.dim,X7=H0.italic,J7=H0.underline,f7=H0.strikethrough,W7=H0.reset,dA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},hz={debug:"\uD83D\uDD0D",info:cj("ℹ"),success:ij("✓"),warning:mj(t8(r8(" WARN "))),error:vj(t8(r8(" ERROR ")))},B7=new $U("stacks"),s0=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},wU=class extends s0{code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${A} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}},XY=class extends s0{code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}},JJ=class extends s0{code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},fJ=class extends s0{code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},YU=class extends s0{code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}},WJ=class extends s0{code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},BJ=class extends s0{code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},JY=class extends s0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},jJ=class extends s0{code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}},zJ=class extends s0{code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},jw={configNotFound($,w,Y){return new wU($,w,Y)},configLoad($,w,Y){return new XY($,w,Y)},configValidation($,w,Y){return new JJ($,w,Y)},configMerge($,w,Y,A){return new fJ($,w,Y,A)},envVar($,w,Y,A){return new YU($,w,Y,A)},fileSystem($,w,Y){return new WJ($,w,Y)},typeGeneration($,w,Y){return new BJ($,w,Y)},schemaValidation($,w,Y){return new JY($,w,Y)},browserConfig($,w,Y,A){return new jJ($,w,Y,A)},plugin($,w,Y){return new zJ($,w,Y)}},Vz={replace:"replace",concat:"concat",smart:"smart"},Lz=/^https?:\/\//,K$=new $U("bunfig",{showTags:!0}),d$=new hJ,Qz=c0(Vw.cwd(),"config"),Oz=c0(Vw.cwd(),"src/generated")});G7=rA.env.CLARITY_LOG_DIR||rE(F7(),"logs"),Sz={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:G7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},AU={...Sz},Ny=(async()=>{try{let{loadConfig:$}=await z7().then(()=>Gz),w=await $({name:"clarity",alias:"logging",defaultConfig:Sz,cwd:rA.cwd()});if(w)Object.assign(AU,w)}catch{}return AU})();y0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=y0,qy=y0.red,K7=y0.green,Ry=y0.yellow,T7=y0.blue,My=y0.magenta,Iy=y0.cyan,dj=y0.white,yy=y0.gray,H7=y0.bgRed,N7=y0.bgYellow,Cy=y0.bgGray,gj=y0.bold,hy=y0.dim,Vy=y0.italic,Ly=y0.underline,Qy=y0.strikethrough,Oy=y0.reset,a8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},q7={debug:"\uD83D\uDD0D",info:T7("ℹ"),success:K7("✓"),warning:N7(dj(gj(" WARN "))),error:H7(dj(gj(" ERROR ")))};Sy=new FU("stacks");N$=class N$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};kz=class kz extends N${code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],U="";if(A.length===1)U=` or alias "${A[0]}"`;else if(A.length>1)U=` or aliases ${A.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${U} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};UU=class UU extends N${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};Dz=class Dz extends N${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};Zz=class Zz extends N${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};VJ=class VJ extends N${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};xz=class xz extends N${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};Pz=class Pz extends N${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};XU=class XU extends N${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};bz=class bz extends N${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};uz=class uz extends N${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};z1={configNotFound($,w,Y){return new kz($,w,Y)},configLoad($,w,Y){return new UU($,w,Y)},configValidation($,w,Y){return new Dz($,w,Y)},configMerge($,w,Y,A){return new Zz($,w,Y,A)},envVar($,w,Y,A){return new VJ($,w,Y,A)},fileSystem($,w,Y){return new xz($,w,Y)},typeGeneration($,w,Y){return new Pz($,w,Y)},schemaValidation($,w,Y){return new XU($,w,Y)},browserConfig($,w,Y,A){return new bz($,w,Y,A)},plugin($,w,Y){return new uz($,w,Y)}};V7=/^https?:\/\//;u$=new FU("bunfig",{showTags:!0});_y=new gz;ky=X$(BU.cwd(),"config"),Dy=X$(BU.cwd(),"src/generated"),lz={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:_8.join(S8.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:_8.join(S8.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:_8.join(S8.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},B0=lz,T$={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"},Q={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},B1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};_7=S7(Q7);k7=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),D7=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;H$={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},v0={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"};UT={platform:"darwin",async addCertificate($,w){if(await AT($,w?.verbose)){V(Q.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),B1.success("Certificate is already trusted in system keychain");return}V(Q.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Bw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,Y){let A=Y||B0.commonName;V(Q.TRUST,`Removing certificate ${A} from macOS keychain`,w?.verbose);try{await Bw(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),V(Q.TRUST,`Removed certificate ${A} from macOS keychain`,w?.verbose)}catch(U){throw V(Q.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},XT={platform:"win32",async addCertificate($,w){V(Q.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Bw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,Y){let A=Y||B0.commonName;V(Q.TRUST,`Removing certificate ${A} from Windows certificate store`,w?.verbose);try{await Bw(`certutil -delstore -enterprise Root "${A}"`),V(Q.TRUST,`Removed certificate ${A} from Windows certificate store`,w?.verbose)}catch(U){throw V(Q.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},JT={platform:"linux",async addCertificate($,w){V(Q.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let Y=fU.homedir(),A=T$.LINUX_CERT_DB_FILENAME,U=T$.LINUX_TRUST_ARGS;V(Q.TRUST,`Searching for certificate databases in ${Y}`,w?.verbose);let X=EJ(Y,A);if(X.length===0){B1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let J of X){V(Q.TRUST,`Processing certificate database in ${J}`,w?.verbose);try{V(Q.TRUST,`Attempting to delete existing cert for ${B0.commonName}`,w?.verbose),await Bw(`certutil -d sql:${J} -D -n ${B0.commonName}`)}catch(W){V(Q.TRUST,`Warning: Error deleting existing cert: ${W}`,w?.verbose),console.warn(`Error deleting existing cert: ${W}`)}V(Q.TRUST,`Adding new certificate to ${J}`,w?.verbose),await Bw(`certutil -d sql:${J} -A -t ${U} -n ${B0.commonName} -i ${$}`),B1.info(`Cert added to ${J}`)}},async removeCertificate($,w,Y){let A=Y||B0.commonName;V(Q.TRUST,`Removing certificate ${A} from Linux certificate store`,w?.verbose);let U=fU.homedir(),X=T$.LINUX_CERT_DB_FILENAME;V(Q.TRUST,`Searching for certificate databases in ${U}`,w?.verbose);let J=EJ(U,X);if(J.length===0){B1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of J){V(Q.TRUST,`Processing certificate database in ${W}`,w?.verbose);try{await Bw(`certutil -d sql:${W} -D -n "${A}"`),B1.info(`Cert removed from ${W}`)}catch(f){V(Q.TRUST,`Error removing cert from ${W}: ${f}`,w?.verbose),console.warn(`Error removing cert from ${W}: ${f}`)}}}},fT={darwin:UT,win32:XT,linux:JT}});var TU=j0(()=>{J9()});import{homedir as PJ}from"node:os";import{join as bJ,resolve as QC}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",BT,uJ;var iJ=j0(()=>{V8();BT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:bJ(PJ(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:bJ(PJ(),".stacks","ssl","stacks.localhost.crt"),keyPath:bJ(PJ(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},uJ=BT});function Lw($){try{return KU($)}catch{return null}}function cJ($){try{return DJ($)||null}catch{return null}}function HU($,w){try{return w.every((Y)=>ZJ($,Y))}catch{return!1}}var NU=j0(()=>{TU()});import{existsSync as f9,statSync as W9}from"fs";import{existsSync as Xf,mkdirSync as KT,readdirSync as TT,writeFileSync as HT}from"fs";import{homedir as G1}from"os";import{dirname as B9,resolve as d0}from"path";import Qw from"process";import{join as NT,relative as qT,resolve as j9}from"path";import xU from"process";import{existsSync as n9,mkdirSync as vC,readdirSync as mC,writeFileSync as dC}from"fs";import{homedir as vJ}from"os";import{dirname as nC,resolve as m0}from"path";import jY from"process";import{join as RT,relative as MT,resolve as z9}from"path";import PU from"process";import{existsSync as p9,mkdirSync as sC,readdirSync as oC,writeFileSync as eC}from"fs";import{dirname as wh,resolve as bU}from"path";import Jf from"process";import{Buffer as Fw}from"buffer";import{createCipheriv as IT,createDecipheriv as yT,randomBytes as mJ}from"crypto";import{closeSync as dJ,createReadStream as F9,createWriteStream as CT,existsSync as gJ,fsyncSync as G9,openSync as E9,writeFileSync as hT}from"fs";import{access as VT,constants as K9,mkdir as LT,readdir as qU,rename as T9,stat as E1,unlink as RU,writeFile as lJ}from"fs/promises";import{join as K1}from"path";import k0 from"process";import{pipeline as QT}from"stream/promises";import{createGzip as H9}from"zlib";import T1 from"process";import n$ from"process";import{Buffer as g$}from"buffer";import{createCipheriv as OT,createDecipheriv as ST,randomBytes as nJ}from"crypto";import{closeSync as pJ,createReadStream as N9,createWriteStream as _T,existsSync as MU,fsyncSync as q9,openSync as R9,writeFileSync as kT}from"fs";import{access as DT,constants as M9,mkdir as ZT,readdir as IU,rename as I9,stat as H1,unlink as yU,writeFile as tJ}from"fs/promises";import{isAbsolute as xT,join as N1,resolve as PT}from"path";import D from"process";import{pipeline as bT}from"stream/promises";import{createGzip as y9}from"zlib";import q1 from"process";import p$ from"process";import CU from"process";import{existsSync as hU}from"fs";import{resolve as rJ}from"path";import{existsSync as uT}from"fs";import{existsSync as iT,readdirSync as cT}from"fs";import{extname as aJ,resolve as C9}from"path";import vT from"process";import{join as mH,relative as dH,resolve as P9}from"path";import gU from"process";import{Buffer as l$}from"buffer";import{createCipheriv as nH,createDecipheriv as pH,randomBytes as wf}from"crypto";import{closeSync as Yf,createReadStream as b9,createWriteStream as tH,existsSync as LU,fsyncSync as u9,openSync as i9,writeFileSync as rH}from"fs";import{access as aH,constants as c9,mkdir as sH,readdir as QU,rename as v9,stat as R1,unlink as OU,writeFile as Af}from"fs/promises";import{isAbsolute as oH,join as M1,resolve as eH}from"path";import Z from"process";import{pipeline as $N}from"stream/promises";import{createGzip as m9}from"zlib";import I1 from"process";import t$ from"process";function FT($,w){this[$]=zT.bind(null,w)}class Tf{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!f9($))return!0;return W9($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=f9(Y)?W9(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,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:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Hf{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function mT($,w={}){let A=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return A?`${$}:${A}`:$}function dT($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function gT($){return $.getStats().size*2}function Nf($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&w0(w[0])&&"id"in w[0]&&w[0].id===3&&w0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(w0(w)&&w0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(w0($)&&"arr"in $&&Array.isArray($.arr)&&w0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&w0(w[0])&&w0($[0])){let A=[...w];for(let U of $)if(w0(U)&&"name"in U){if(!A.find((J)=>w0(J)&&("name"in J)&&J.name===U.name))A.push(U)}else if(w0(U)&&"path"in U){if(!A.find((J)=>w0(J)&&("path"in J)&&J.path===U.path))A.push(U)}else if(!A.some((X)=>uU(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!w0(w)||!w0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(w0(U)&&w0(Y[A]))Y[A]=Nf(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&w0(U[0])&&w0(Y[A][0])){let X=[...U];for(let J of Y[A])if(w0(J)&&"name"in J){if(!X.find((f)=>w0(f)&&("name"in f)&&f.name===J.name))X.push(J)}else if(w0(J)&&"path"in J){if(!X.find((f)=>w0(f)&&("path"in f)&&f.path===J.path))X.push(J)}else if(!X.some((W)=>uU(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function uU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!uU($[Y],w[Y]))return!1;return!0}if(w0($)&&w0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!uU($[U],w[U]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function lT($,w){if(!p9($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return Nf(w,A)}catch{return null}}catch{return null}}async function nT({name:$="",cwd:w,defaultConfig:Y}){let A=w||Jf.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let J of X)for(let W of U){let f=bU(A,`${J}${W}`),B=await lT(f,Y);if(B!==null)return B}try{let J=bU(A,"package.json");if(p9(J)){let f=(await import(J))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return Nf(Y,f)}catch{}}}catch{}return Y}function pT($,w={}){let Y=PU.cwd();while(Y.includes("storage"))Y=z9(Y,"..");let A=z9(Y,$||"");if(w?.relative)return MT(PU.cwd(),A);return A}async function tT(){try{let $=await nT({name:"clarity",defaultConfig:_U,cwd:PU.cwd(),endpoint:"",headers:{}});return{..._U,...$}}catch{return _U}}function J0(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function rT(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n$<"u"){let $=n$.type;if($==="renderer"||$==="worker")return!1;return!!(n$.versions&&(n$.versions.node||n$.versions.bun))}return!1}class t9{async format($){let w=await rT(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:T1.pid,hostname:w(),environment:T1.env.NODE_ENV||"development",platform:T1.platform,version:T1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:T1.env.NODE_ENV||T1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class iU{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($,w={}){this.name=$,this.config={...Wf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new t9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...kU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...kU};return{...kU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Wf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await VT(this.config.logDirectory,K9.F_OK|K9.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await LT(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Fw.from($);try{if(!gJ(this.currentLogFile))await lJ(this.currentLogFile,"",{mode:420});if(U=E9(this.currentLogFile,"a",420),hT(U,f,{flag:"a"}),G9(U),U!==void 0)dJ(U),U=void 0;if((await E1(this.currentLogFile)).size===0){if(await lJ(this.currentLogFile,f,{flag:"w",mode:420}),(await E1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{dJ(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,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 K1(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 K1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return K1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(J0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return mJ(16).toString("hex")}generateKey(){return mJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=mJ(16),A=IT("aes-256-gcm",w,Y),U=Fw.concat([A.update($,"utf8"),A.final()]),X=A.getAuthTag();return{encrypted:Fw.concat([Y,U,X]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=H9(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(Fw.from(Fw.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(J0())return;let $=await E1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await qU(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await E1(Y).catch(()=>null))try{if(await T9(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await RU(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await lJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await E1(Y).catch(()=>null))await T9(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await qU(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await RU(K1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=F9($),A=CT(w),U=H9();await QT(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),gJ(this.currentLogFile))try{let $=E9(this.currentLogFile,"r+");G9($),dJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!J0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await qU(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await RU(K1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?s.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=k0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${s.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);if(this.fancy&&!J0()){let B=U2[$],j=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:s.gray(J),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:s.green(J),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z),W){let G=W.split(`
|
|
135
|
+
`);for(let F of G)if(F.trim()&&!F.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:s.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!J0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let f=`${X} ${this.environment}.${$.toUpperCase()}: ${J}
|
|
136
|
+
`;if(W)f+=`${W}
|
|
137
|
+
`;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!J0()){let Y=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:s.blue("◐"),tag:Y,message:`${s.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
138
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!J0()){let j=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:s.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!J0())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new iU(w,{...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(Y),Y}createReadStream(){if(J0())throw Error("createReadStream is not supported in browser environments");if(!gJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return F9(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Fw.isBuffer($)?$:Fw.from($,"base64"),U=A.slice(0,16),X=A.slice(-16),J=A.slice(16,-16),W=yT("aes-256-gcm",Y,U);return W.setAuthTag(X),Fw.concat([W.update(J),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return J0()}isServerMode(){return!J0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}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($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!J0()){let X=$.split(`
|
|
139
|
+
`),J=Math.max(...X.map((j)=>j.length))+2,W=`┌${"─".repeat(J)}┐`,f=`└${"─".repeat(J)}┘`,B=X.map((j)=>{let z=" ".repeat(J-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:s.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(f),showTimestamp:!1}))}else if(!J0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let U=`${A} ${this.environment}.INFO: [BOX] ${$}
|
|
140
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(J0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${s.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();k0.stdin.removeListener("data",Y);try{if(typeof k0.stdin.setRawMode==="function")k0.stdin.setRawMode(!1)}catch{}k0.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof k0.stdin.setRawMode==="function")k0.stdin.setRawMode(!0)}catch{}k0.stdin.resume(),k0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,W=0;if(Y=$.replace(J,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)Y+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!J0()){let J=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",W=s.blue("◐");console.error(`${W} ${J} ${s.cyan(Y)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
|
|
141
|
+
`.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||J0()||$<=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 Y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),W!==void 0)this.activeProgressBar.message=W;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J0())return;k0.stdout.write(`${"\r".padEnd(k0.stdout.columns||80)}\r`),this.log(W,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||J0()||!k0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=s.green("━".repeat(A)),J=s.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=w||Y===100?s.green("✓"):s.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${s.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=k0.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,k0.stdout.write($.lastRenderedLine),w)k0.stdout.write(`
|
|
142
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||J0()||!k0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(J0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await qU(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=K1(this.config.logDirectory,A);if($.before)try{if((await E1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await RU(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function SU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&n(w[0])&&"id"in w[0]&&w[0].id===3&&n(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(n(w)&&n($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(n($)&&"arr"in $&&Array.isArray($.arr)&&n(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&n(w[0])&&n($[0])){let A=[...w];for(let U of $)if(n(U)&&"name"in U){if(!A.find((J)=>n(J)&&("name"in J)&&J.name===U.name))A.push(U)}else if(n(U)&&"path"in U){if(!A.find((J)=>n(J)&&("path"in J)&&J.path===U.path))A.push(U)}else if(!A.some((X)=>cU(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!n(w)||!n($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(n(U)&&n(Y[A]))Y[A]=SU(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&n(U[0])&&n(Y[A][0])){let X=[...U];for(let J of Y[A])if(n(J)&&"name"in J){if(!X.find((f)=>n(f)&&("name"in f)&&f.name===J.name))X.push(J)}else if(n(J)&&"path"in J){if(!X.find((f)=>n(f)&&("path"in f)&&f.path===J.path))X.push(J)}else if(!X.some((W)=>cU(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function qf($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:SU($,w);if(Array.isArray($))return Y==="replace"?w:SU($,w);if(!n(w)||!n($))return w;let A={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let X=w[U],J=A[U];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(J))if(Y==="replace")A[U]=X;else A[U]=SU(J,X);else if(n(X)&&n(J))A[U]=qf(J,X,Y);else A[U]=X}return A}function cU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!cU($[Y],w[Y]))return!1;return!0}if(n($)&&n(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!cU($[U],w[U]))return!1}return!0}return!1}function n($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function VU($,w,Y="replace"){if(!n9($))return null;try{let A=await import($),U=A.default||A;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return qf(w,U,Y)}catch{return null}}catch{return null}}function aT($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),U={...w};function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${z.map(G).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=X(j,z);else{let K=jY.env[F]||jY.env[T];if(K!==void 0){if(Y)Z0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((q)=>q.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return X(U)}async function sT({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:U,verbose:X=!1,checkEnv:J=!0,arrayStrategy:W="replace"}){let f=J&&typeof U==="object"&&U!==null&&!Array.isArray(U)?aT($,U,X):U,B=Y||jY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(X)Z0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),G=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,m0(B,"config"),m0(B,".config"),A?m0(B,A):void 0].filter(Boolean)));for(let H of K){if(X)Z0.info(`Searching for configuration in: ${H}`);let M=[m0(B,"config"),m0(B,".config")].concat(A?[m0(B,A)]:[]).includes(H)?[...z,...G,...F,...T]:[...G,...z,...T,...F];for(let I of M)for(let h of j){let N=m0(H,`${I}${h}`),C=await VU(N,f,W);if(C!==null){if(X)Z0.success(`Configuration loaded from: ${N}`);return C}}}if($){let H=m0(vJ(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(X)Z0.info(`Checking user config directory: ${H}`);for(let M of q)for(let I of j){let h=m0(H,`${M}${I}`),N=await VU(h,f,W);if(N!==null){if(X)Z0.success(`Configuration loaded from user config directory: ${h}`);return N}}}if($){let H=m0(vJ(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(X)Z0.info(`Checking user config directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=m0(H,`${M}${I}`),N=await VU(h,f,W);if(N!==null){if(X)Z0.success(`Configuration loaded from user config directory dotfile: ${h}`);return N}}}if($){let H=vJ(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(X)Z0.info(`Checking user home directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=m0(H,`${M}${I}`),N=await VU(h,f,W);if(N!==null){if(X)Z0.success(`Configuration loaded from user home directory: ${h}`);return N}}}try{let H=m0(B,"package.json");if(n9(H)){let q=await import(H),M=q[$];if(!M&&w){if(M=q[w],M&&X)Z0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(X)Z0.success(`Configuration loaded from package.json: ${M===q[$]?$:w}`);return qf(f,M,W)}catch(I){if(X)Z0.warn("Failed to merge package.json config:",I)}}}catch(H){if(X)Z0.warn("Failed to load package.json:",H)}if(X)Z0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function oT($,w={}){let Y=xU.cwd();while(Y.includes("storage"))Y=j9(Y,"..");let A=j9(Y,$||"");if(w?.relative)return qT(xU.cwd(),A);return A}async function eT(){try{let $=await sT({name:"clarity",alias:"logging",defaultConfig:DU,cwd:xU.cwd()});return{...DU,...$||{}}}catch{return DU}}function q0(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function $H(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p$<"u"){let $=p$.type;if($==="renderer"||$==="worker")return!1;return!!(p$.versions&&(p$.versions.node||p$.versions.bun))}return!1}class r9{async format($){let w=await $H(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:q1.pid,hostname:w(),environment:q1.env.NODE_ENV||"development",platform:q1.platform,version:q1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:q1.env.NODE_ENV||q1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class vU{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($,w={}){this.name=$,this.config={...Bf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new r9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...ZU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...ZU};return{...ZU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Bf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await DT(this.config.logDirectory,M9.F_OK|M9.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await ZT(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:g$.from($);try{if(!MU(this.currentLogFile))await tJ(this.currentLogFile,"",{mode:420});if(U=R9(this.currentLogFile,"a",420),kT(U,f,{flag:"a"}),q9(U),U!==void 0)pJ(U),U=void 0;if((await H1(this.currentLogFile)).size===0){if(await tJ(this.currentLogFile,f,{flag:"w",mode:420}),(await H1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{pJ(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,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 N1(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 N1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return N1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return nJ(16).toString("hex")}generateKey(){return nJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=nJ(16),A=OT("aes-256-gcm",w,Y),U=g$.isBuffer($)?$:g$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=g$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=y9(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(g$.from(g$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let $=await H1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await IU(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await H1(Y).catch(()=>null))try{if(await I9(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await yU(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await tJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await H1(Y).catch(()=>null))await I9(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await IU(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await yU(N1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=N9($),A=_T(w),U=y9();await bT(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),MU(this.currentLogFile))try{let $=R9(this.currentLogFile,"r+");q9($),pJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await IU(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await yU(N1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=D.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${b.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=b.underline(b.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>b.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>b.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>b.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>b.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>b.strikethrough(A)),w}supportsHyperlinks(){if(q0())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=D.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(xT(w)||w.startsWith("./")||w.startsWith("../"))w=PT(w);else return null;return MU(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":X2[$],G=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:b.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:b.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
143
|
+
`);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:b.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!q0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
144
|
+
`;if(W)j+=`${W}
|
|
145
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!q0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!q0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!q0()&&D.stdout.isTTY)D.stdout.write(`
|
|
146
|
+
`);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!q0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":b.blue("◐"),tag:Y,message:`${b.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
147
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":b.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!q0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new vU(w,{...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(Y),Y}createReadStream(){if(q0())throw Error("createReadStream is not supported in browser environments");if(!MU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return N9(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=g$.isBuffer($)?$:g$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=ST("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=g$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q0()}isServerMode(){return!q0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}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($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
148
|
+
`),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:b.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(j),showTimestamp:!1}))}else if(!q0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
|
|
149
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(q0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${b.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();D.stdin.removeListener("data",Y);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(Y=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let G=w[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<w.length)Y+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${B}${f} ${b.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
150
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=b.green("━".repeat(A)),J=b.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?b.green("✓"):b.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=D.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,D.stdout.write($.lastRenderedLine),w)D.stdout.write(`
|
|
151
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||q0()||!D.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await IU(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=N1(this.config.logDirectory,A);if($.before)try{if((await H1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await yU(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function a9($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}function s9($){return $ instanceof $$}function wH($){return $ instanceof mU}function YH($){if(s9($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class nU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return GY.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=CU.env[f]||(B?CU.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=CU.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof dU)throw z;throw Gw.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw Gw.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(CU.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
|
|
152
|
+
|
|
153
|
+
`;for(let A of $)Y+=`${A.key}
|
|
154
|
+
`,Y+=` Type: ${A.type}
|
|
155
|
+
`,Y+=` Description: ${A.description}
|
|
156
|
+
`,Y+=` Example: ${A.example}
|
|
157
|
+
|
|
158
|
+
`;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
|
|
159
|
+
|
|
160
|
+
`;Y+=`| Variable | Type | Description | Example |
|
|
161
|
+
`,Y+=`|----------|------|-------------|----------|
|
|
162
|
+
`;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
|
|
163
|
+
`;return Y}}function AH($,w){let Y=Y2("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function o9($,w,Y={}){return e9($,w,Y,new WeakMap)}function e9($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return $2($,w,U,A);if(!W$(w)||!W$($))return w;return fH($,w,Y,A)}function $2($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return UH($,w);case"smart":return XH($,w,A);default:return w}return w}function UH($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>ff(U,A)))Y.push(A);return Y}function XH($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(W$(w[0])&&W$($[0]))return JH($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function JH($,w,Y){let A=[...w];for(let U of $){if(!W$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((B)=>W$(B)&&(W in B)&&B[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function fH($,w,Y,A){let U=w;if(W$(U)&&A.has(U))return A.get(U);let X={...$};if(W$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(W$(W)&&W$(f))X[J]=e9(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=$2(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function Rf($,w,Y="replace"){return o9($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function ff($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!ff($[Y],w[Y]))return!1;return!0}if(W$($)&&W$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!ff($[U],w[U]))return!1}return!0}return!1}function W$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class pU{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=y1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!hU($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new zY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new zY($,Error("Configuration must export a valid object"),"unknown");let H={config:Rf(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)y1.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?Gw.configLoad($,B):Gw.configLoad($,Error(String(B)))}};if(J)return GY.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(rJ(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return a9(async()=>{return hU($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!hU($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=rJ($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=rJ($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){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((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!hU($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class Mf{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await GY.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!uT(w))throw new FY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new FY(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.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:f2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class If{fileLoader=new pU;envProcessor=new nU;validator=new Mf;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)q$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw q$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||Qw.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(d0(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw Gw.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?BY($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)q$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)q$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?BY($,Y,U):Y,W=[d0(G1(),".config",$),d0(G1(),".config"),G1()];for(let f of W){if(U)q$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)q$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?BY($,A,X):A;try{let f=d0(Y,"package.json");if(!Xf(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)q$.success(`Configuration loaded from package.json: ${z}`);return{config:Rf(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)q$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:BY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw Gw.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return y1.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);y1.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,d0($,"config"),d0($,".config"),w?d0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(d0(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[d0(G1(),".config",$),d0(G1(),".config"),G1()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function h9($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function WH($){return r$.loadConfig({...$,__strictErrorHandling:!0})}async function w2($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await r$.loadConfig($);else A=await r$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}catch(A){let U=A instanceof Error?A.name:"UnknownError",X=A instanceof Error?A.message:String(A);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||X.includes("config"))&&$.verbose)q$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await r$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function BH($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await r$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&h9(Y)))return(await r$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await r$.loadConfig({...$,cwd:$.cwd||Qw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&h9(w)))return(await r$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function jH($,w,Y="replace"){let A=new pU;try{let U=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function BY($,w,Y=!1){let A=new nU,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=Qw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}function zH($){let w=d0(Qw.cwd(),$.configDir),Y=d0(Qw.cwd(),$.generatedDir),A=d0(Y,"config-types.ts");if(!Xf(B9(A)))KT(B9(A),{recursive:!0,mode:511});let U=Xf(w)?TT(w).map((J)=>J.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${cH}
|
|
164
|
+
export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
|
|
165
|
+
`;HT(A,X,{mode:438})}function FH($){let w=null,Y=null,A=()=>{if(!Y)Y=w2($).then((X)=>{return w=X,X},(X)=>{let J="defaultConfig"in $?$.defaultConfig:{};if(w=J,"verbose"in $&&$.verbose)q$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return J});return Y},U="defaultConfig"in $?$.defaultConfig:{};return w=U,A(),new Proxy({},{get(X,J){if(w)return w[J];let W=U[J];return A(),W},has(X,J){return J in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(X,J){return Object.getOwnPropertyDescriptor(w||U,J)},set(X,J,W){if(!w)w={...U};return w[J]=W,!0}})}function GH($){let w=C9(vT.cwd(),$?.configDir||"./config");function Y(){if(!iT(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],J=cT(w).filter((f)=>U.has(aJ(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),W=new Map;for(let{base:f,file:B}of J){let j=aJ(B).toLowerCase(),z=W.get(f);if(!z){W.set(f,B);continue}let G=aJ(z).toLowerCase();if(X.indexOf(j)<X.indexOf(G))W.set(f,B)}return Array.from(W.entries()).map(([f,B])=>({base:f,file:B})).sort((f,B)=>f.base.localeCompare(B.base))}function A(){let U=Y(),X=U.map((B)=>B.base),J=X.length?X.map((B)=>`'${B}'`).join(" | "):"string",W=U.length?`{
|
|
166
|
+
${U.map((B)=>{let j=C9(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
|
|
165
167
|
`)}
|
|
166
|
-
}`:"Record<string, any>";return`export type ConfigNames = ${
|
|
168
|
+
}`:"Record<string, any>";return`export type ConfigNames = ${J}
|
|
167
169
|
export type ConfigByName = ${W}
|
|
168
170
|
export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
|
|
169
171
|
export type ConfigOf = Config
|
|
170
|
-
`}return{name:"bunfig-plugin",setup(f){f.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),f.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:Y(),loader:"ts"}})}}}function v6($,w={}){let A=Sf.cwd();while(A.includes("storage"))A=WT(A,"..");let Y=WT(A,$||"");if(w?.relative)return n6(Sf.cwd(),Y);return Y}function N0(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function e6(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p$<"u"){let $=p$.type;if($==="renderer"||$==="worker")return!1;return!!(p$.versions&&(p$.versions.node||p$.versions.bun))}return!1}class iT{async format($){let w=await e6(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:q1.pid,hostname:w(),environment:q1.env.NODE_ENV||"development",platform:q1.platform,version:q1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:q1.env.NODE_ENV||q1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Iw{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($,w={}){this.name=$,this.config={...Lf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new iT,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let f=this.generateKeyId(),X=this.generateKey();this.currentKeyId=f,this.keys.set(f,X),this.encryptionKeys.set(f,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...x8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...x8};return{...x8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Lf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let f,X=0,U=3,W=1000;while(X<U)try{try{try{await p6(this.config.logDirectory,TT.F_OK|TT.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await r6(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let J=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:l$.from($);try{if(!Bf(this.currentLogFile))await Z8(this.currentLogFile,"",{mode:420});if(f=jT(this.currentLogFile,"a",420),t6(f,J,{flag:"a"}),ET(f),f!==void 0)k8(f),f=void 0;if((await R1(this.currentLogFile)).size===0){if(await Z8(this.currentLogFile,J,{flag:"w",mode:420}),(await R1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let E=B;if(E.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(E.code)){if(X<U-1){let j=typeof E.message==="string"?E.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${U}:`,j);let T=W*2**X;await new Promise((F)=>setTimeout(F,T)),X++;continue}}if(E?.code&&["ENOSPC","EDQUOT"].includes(E.code))throw Error(`Disk quota exceeded or no space left on device: ${E.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",E),E}finally{if(f!==void 0)try{k8(f)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(J){if(X===U-1){let E=J,j=typeof E.message==="string"?E.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),J}X++;let B=W*2**(X-1);await new Promise((E)=>setTimeout(E,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(f){throw console.error("Debug: [writeToFile] Error in operation:",f),f}finally{this.pendingOperations.splice(Y,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 N1(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 N1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return N1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((f)=>{console.error("Error rotating keys:",f)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let f=Array.from(this.encryptionKeys.entries()).sort(([,W],[,J])=>J.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,X);if(f.length>U)for(let[W]of f.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return D8(16).toString("hex")}generateKey(){return D8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=D8(16),Y=d6("aes-256-gcm",w,A),f=l$.isBuffer($)?$:l$.from($,"utf8"),X=Y.update(f),U=Y.final(),W=X.length+U.length,J=Y.getAuthTag(),B=l$.allocUnsafe(16+W+16);return A.copy(B,0),X.copy(B,16),U.copy(B,16+X.length),J.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=zT(),f=[];Y.on("data",(X)=>f.push(X)),Y.on("end",()=>w(l$.from(l$.concat(f)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let $=await R1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let f=await Ef(this.config.logDirectory),X=f.filter((J)=>J.startsWith(this.name)&&/\.log\.\d+$/.test(J)).sort((J,B)=>{let E=Number.parseInt(J.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-E}),U=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await R1(A).catch(()=>null))try{if(await FT(A,W),w.compress)try{let J=`${W}.gz`;await this.compressLogFile(W,J),await jf(W)}catch(J){console.error("Error compressing rotated file:",J)}if(X.length===0&&!f.some((J)=>J.endsWith(".log.1")))try{let J=`${A}.1`;await Z8(J,"")}catch(J){console.error("Error creating backup file:",J)}}catch(J){console.error(`Error during rotation: ${J instanceof Error?J.message:String(J)}`)}}else{let f=new Date().toISOString().replace(/[:.]/g,"-"),X=A.replace(/\.log$/,`-${f}.log`);if(await R1(A).catch(()=>null))await FT(A,X)}if(this.currentLogFile=Y,w.maxFiles){let X=(await Ef(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of X.slice(w.maxFiles))await jf(N1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=BT($),Y=g6(w),f=zT();await o6(A,f,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),Bf(this.currentLogFile))try{let $=jT(this.currentLogFile,"r+");ET($),k8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await Ef(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await jf(N1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:f,level:X,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(f),F.join(" ")}let J=k.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${A} ${f}`;else if(X==="info"||X==="success")B=`${A} ${Y} ${f}`;else B=`${A} ${Y} ${u.cyan(f)}`;if(!U)return B.trim();let E=W(B).trim().length,j=W(w).length,T=Math.max(1,J-2-E-j);return`${B.trim()}${" ".repeat(T)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):X});let A=/%([sdijfo%])/g,Y=0,f=$.replace(A,(X,U)=>{if(U==="%")return"%";if(Y>=w.length)return X;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(Y<w.length)f+=` ${w.slice(Y).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return f}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,f)=>{let X=u.underline(u.blue(Y)),U=this.toAbsoluteFilePath(f);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,J="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${f}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(A,Y)=>u.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>u.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>u.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>u.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>u.strikethrough(Y)),w}supportsHyperlinks(){if(N0())return!1;let $=k.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=k.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(a6(w)||w.startsWith("./")||w.startsWith("../"))w=s6(w);else return null;return Bf(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,f=this.formatConsoleTimestamp(Y),X=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:J,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let j=this.options.showIcons===!1?"":f7[$],T=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:u.gray(J),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:u.green(J),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:f,icon:j,tag:T,message:J,level:$}),console.error(F),W){let H=W.split(`
|
|
171
|
-
`);for(let
|
|
172
|
-
`;if(W)
|
|
173
|
-
`;if(
|
|
174
|
-
`);if(this[
|
|
175
|
-
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let
|
|
176
|
-
`),
|
|
177
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(
|
|
178
|
-
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!
|
|
179
|
-
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||N0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(N0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await Ef(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=N1(this.config.logDirectory,Y);if($.before)try{if((await R1(X)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${X}:`,U);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await jf(Y),console.warn(`Deleted log file: ${Y}`)}catch(f){console.error(`Failed to delete log file ${Y}:`,f)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var WK,BK=($)=>$,jK=($,w)=>{for(var A in w)WK($,A,{get:w[A],enumerable:!0,configurable:!0,set:EK.bind(w,A)})},TK=($,w)=>()=>($&&(w=$($=0)),w),KT,VT,h1,o1,OT,T6,F6,oj,Ff,c8,Q0,r,z6,ej,G6,$T,H6,K6,V8,R6,wT,AT,O8,N6,q6,h6,y6,zf,_T,M6,D0,I6,C6,YT,Gf,u8,R0,P,S6,fT,L6,XT,V6,O6,_8,_6,UT,JT,Q6,Q8,D6,k6,Z6,x6,P6,Hf,QT,i6,b6="0.15.6",o0,If,a1,n8,v8,Cf,m8,d8,s1,l8,g8,Ew,DT,kT,y$,r$,ZT,xT,c6,m6,PT,Lf,XC,M0,u,HC,$7,KC,w7,RC,NC,GT,qC,A7,Y7,hC,HT,yC,MC,IC,CC,SC,x8,f7,LC;var $J=E0(()=>{WK=Object.defineProperty;KT={};jK(KT,{withErrorRecovery:()=>yT,tryLoadConfig:()=>W6,loadConfigWithResult:()=>U6,loadConfig:()=>LT,isRetryableError:()=>$6,isConfigNotFoundError:()=>eK,isBunfigError:()=>MT,globalPerformanceMonitor:()=>o1,globalCache:()=>h1,getEnvOrDefault:()=>w6,generateConfigTypes:()=>B6,defaultGeneratedDir:()=>xT,defaultConfigDir:()=>ZT,deepMergeWithArrayStrategy:()=>s8,deepMerge:()=>IT,createLibraryConfig:()=>E6,config:()=>J6,bunfigPlugin:()=>j6,applyEnvVarsToConfig:()=>p1,TypeGenerationError:()=>d8,SchemaValidationError:()=>s1,PluginError:()=>g8,PerformanceMonitor:()=>p8,FileSystemError:()=>m8,ErrorFactory:()=>Ew,EnvVarError:()=>Cf,EnvProcessor:()=>Vf,ConfigValidator:()=>o8,ConfigValidationError:()=>n8,ConfigNotFoundError:()=>If,ConfigMergeError:()=>v8,ConfigLoader:()=>e8,ConfigLoadError:()=>a1,ConfigFileLoader:()=>Of,ConfigCache:()=>t8,CacheUtils:()=>OT,BunfigError:()=>o0,BrowserConfigError:()=>l8,ArrayMergeStrategies:()=>DT});c6=TK(async()=>{VT=import.meta.require,h1=new t8,o1=new p8,OT={createKey:uK,isEquivalent:nK,estimateMemoryUsage:vK},T6=Nf(i8.cwd(),"config"),F6=Nf(i8.cwd(),"src/generated"),oj=Rf.env.CLARITY_LOG_DIR||RK(lK(),"logs"),Ff={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:oj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},c8=await gK(),Q0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},r=Q0,z6=Q0.red,ej=Q0.green,G6=Q0.yellow,$T=Q0.blue,H6=Q0.magenta,K6=Q0.cyan,V8=Q0.white,R6=Q0.gray,wT=Q0.bgRed,AT=Q0.bgYellow,O8=Q0.bold,N6=Q0.dim,q6=Q0.italic,h6=Q0.underline,y6=Q0.reset,zf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_T={debug:"\uD83D\uDD0D",info:$T("ℹ"),success:ej("✓"),warning:AT(V8(O8(" WARN "))),error:wT(V8(O8(" ERROR ")))},M6=new hf("stacks"),D0=new hf("bunfig",{showTags:!0}),I6=c0(r1.cwd(),"config"),C6=c0(r1.cwd(),"src/generated"),YT=Kf.env.CLARITY_LOG_DIR||HK(aK(),"logs"),Gf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:YT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},u8=await sK(),R0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=R0,S6=R0.red,fT=R0.green,L6=R0.yellow,XT=R0.blue,V6=R0.magenta,O6=R0.cyan,_8=R0.white,_6=R0.gray,UT=R0.bgRed,JT=R0.bgYellow,Q6=R0.bgGray,Q8=R0.bold,D6=R0.dim,k6=R0.italic,Z6=R0.underline,x6=R0.strikethrough,P6=R0.reset,Hf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},QT={debug:"\uD83D\uDD0D",info:XT("ℹ"),success:fT("✓"),warning:JT(_8(Q8(" WARN "))),error:UT(_8(Q8(" ERROR ")))},i6=new Mf("stacks"),o0=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},If=class extends o0{code="CONFIG_NOT_FOUND";constructor(w,A,Y){let f=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${f} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},a1=class extends o0{code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},n8=class extends o0{code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},v8=class extends o0{code="CONFIG_MERGE_ERROR";constructor(w,A,Y,f){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:f,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Cf=class extends o0{code="ENV_VAR_ERROR";constructor(w,A,Y,f){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:f})}},m8=class extends o0{code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},d8=class extends o0{code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},s1=class extends o0{code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},l8=class extends o0{code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,f){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:f})}},g8=class extends o0{code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Ew={configNotFound($,w,A){return new If($,w,A)},configLoad($,w,A){return new a1($,w,A)},configValidation($,w,A){return new n8($,w,A)},configMerge($,w,A,Y){return new v8($,w,A,Y)},envVar($,w,A,Y){return new Cf($,w,A,Y)},fileSystem($,w,A){return new m8($,w,A)},typeGeneration($,w,A){return new d8($,w,A)},schemaValidation($,w,A){return new s1($,w,A)},browserConfig($,w,A,Y){return new l8($,w,A,Y)},plugin($,w,A){return new g8($,w,A)}},DT={replace:"replace",concat:"concat",smart:"smart"},kT=/^https?:\/\//,y$=new Mf("bunfig",{showTags:!0}),r$=new e8,ZT=u0(Mw.cwd(),"config"),xT=u0(Mw.cwd(),"src/generated")});m6=Sf.env.CLARITY_LOG_DIR||u6(v6(),"logs"),PT={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:m6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Lf={...PT},XC=(async()=>{try{let{loadConfig:$}=await c6().then(()=>KT),w=await $({name:"clarity",alias:"logging",defaultConfig:PT,cwd:Sf.cwd()});if(w)Object.assign(Lf,w)}catch{}return Lf})();M0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},u=M0,HC=M0.red,$7=M0.green,KC=M0.yellow,w7=M0.blue,RC=M0.magenta,NC=M0.cyan,GT=M0.white,qC=M0.gray,A7=M0.bgRed,Y7=M0.bgYellow,hC=M0.bgGray,HT=M0.bold,yC=M0.dim,MC=M0.italic,IC=M0.underline,CC=M0.strikethrough,SC=M0.reset,x8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},f7={debug:"\uD83D\uDD0D",info:w7("ℹ"),success:$7("✓"),warning:Y7(GT(HT(" WARN "))),error:A7(GT(HT(" ERROR ")))};LC=new Iw("stacks")});var y1={};lJ(y1,{safeStringify:()=>E$,safeDeleteFile:()=>YJ,resolvePathRewrite:()=>AJ,redactSensitive:()=>_f,isValidRootCA:()=>wJ,isSingleProxyOptions:()=>$A,isSingleProxyConfig:()=>E7,isMultiProxyOptions:()=>Sw,isMultiProxyConfig:()=>nT,getSudoPassword:()=>Cw,getPrimaryDomain:()=>Qf,extractHostname:()=>B7,execSudoSync:()=>e1,debugLog:()=>z});import{execSync as bT}from"node:child_process";import*as uT from"node:fs/promises";function Cw(){return process.env.SUDO_PASSWORD}function e1($){let w=Cw(),A=$.replace(/'/g,"'\\''");if(w)return bT(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return bT(`sudo -n sh -c '${A}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function z($,w,A){if(A)X7.debug(`[rpx:${$}] ${w}`)}function W7($){let w=$.toLowerCase();return U7.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function _f($){if(Array.isArray($))return $.map((A)=>_f(A));if(typeof $==="string")return J7.test($)?cT:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(W7(A)){w[A]=cT;continue}w[A]=_f(Y)}return w}function E$($,w){return JSON.stringify(_f($),null,w)}function B7($){if(Sw($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if($A($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function wJ($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function Qf($){if(!$)return"stacks.localhost";if(Sw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if($A($))return $.to||"stacks.localhost";return"stacks.localhost"}function nT($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function Sw($){return"proxies"in $&&Array.isArray($.proxies)}function $A($){return"to"in $&&typeof $.to==="string"}function E7($){return!!($&&("to"in $)&&!("proxies"in $))}function AJ($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let Y=A.to.startsWith("http")?new URL(A.to).host:A.to,f=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:Y,targetPath:f}}return null}async function YJ($,w){try{await uT.unlink($),z("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")z("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var X7,cT="[redacted]",U7,J7;var U0=E0(()=>{$J();X7=new Iw("rpx",{showTags:!1});U7=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),J7=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as Df}from"node:child_process";import{homedir as j7}from"node:os";import{join as T7}from"node:path";function kf(){return T7(j7(),"Library/Keychains/login.keychain-db")}function XJ(){return[I1,kf()]}function vT($,w=fJ){let A=Df(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),Y=[];for(let f of A.split(`
|
|
180
|
-
`)){let X=
|
|
181
|
-
`))if(X.toUpperCase().includes("SHA-256")){if(X.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===
|
|
172
|
+
`}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function gH($,w={}){let Y=gU.cwd();while(Y.includes("storage"))Y=P9(Y,"..");let A=P9(Y,$||"");if(w?.relative)return dH(gU.cwd(),A);return A}function M0(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wN(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t$<"u"){let $=t$.type;if($==="renderer"||$==="worker")return!1;return!!(t$.versions&&(t$.versions.node||t$.versions.bun))}return!1}class z2{async format($){let w=await wN(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:I1.pid,hostname:w(),environment:I1.env.NODE_ENV||"development",platform:I1.platform,version:I1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:I1.env.NODE_ENV||I1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ow{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($,w={}){this.name=$,this.config={...lU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new z2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Uf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Uf};return{...Uf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:lU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await aH(this.config.logDirectory,c9.F_OK|c9.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await sH(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:l$.from($);try{if(!LU(this.currentLogFile))await Af(this.currentLogFile,"",{mode:420});if(U=i9(this.currentLogFile,"a",420),rH(U,f,{flag:"a"}),u9(U),U!==void 0)Yf(U),U=void 0;if((await R1(this.currentLogFile)).size===0){if(await Af(this.currentLogFile,f,{flag:"w",mode:420}),(await R1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{Yf(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,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 M1(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 M1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return M1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return wf(16).toString("hex")}generateKey(){return wf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=wf(16),A=nH("aes-256-gcm",w,Y),U=l$.isBuffer($)?$:l$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=l$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=m9(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(l$.from(l$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let $=await R1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await QU(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await R1(Y).catch(()=>null))try{if(await v9(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await OU(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await Af(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await R1(Y).catch(()=>null))await v9(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await QU(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await OU(M1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=b9($),A=tH(w),U=m9();await $N(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),LU(this.currentLogFile))try{let $=i9(this.currentLogFile,"r+");u9($),Yf($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await QU(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await OU(M1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let $=typeof Z.env.NO_COLOR<"u",w=Z.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof Z.stderr<"u"&&Z.stderr.isTTY||typeof Z.stdout<"u"&&Z.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=Z.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${c.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=c.underline(c.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),w}supportsHyperlinks(){if(M0())return!1;let $=Z.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=Z.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(oH(w)||w.startsWith("./")||w.startsWith("../"))w=eH(w);else return null;return LU(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":JN[$],G=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:c.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:c.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
|
|
173
|
+
`);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:c.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
|
|
174
|
+
`;if(W)j+=`${W}
|
|
175
|
+
`;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!M0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!M0()&&Z.stdout.isTTY)Z.stdout.write(`
|
|
176
|
+
`);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":c.blue("◐"),tag:Y,message:`${c.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
|
|
177
|
+
`,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":c.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new Ow(w,{...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(Y),Y}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!LU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return b9(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=l$.isBuffer($)?$:l$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=pH("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=l$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}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($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
|
|
178
|
+
`),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(j),showTimestamp:!1}))}else if(!M0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
|
|
179
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(M0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${c.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();Z.stdin.removeListener("data",Y);try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!1)}catch{}Z.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!0)}catch{}Z.stdin.resume(),Z.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(Y=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let G=w[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<w.length)Y+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${B}${f} ${c.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
|
|
180
|
+
`.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!Z.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=c.green("━".repeat(A)),J=c.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?c.green("✓"):c.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=Z.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,Z.stdout.write($.lastRenderedLine),w)Z.stdout.write(`
|
|
181
|
+
`)}finishProgressBar($,w){if(!this.enabled||!this.fancy||M0()||!Z.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await QU(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=M1(this.config.logDirectory,A);if($.before)try{if((await R1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await OU(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var jT,zT=($)=>$,GT=($,w)=>{for(var Y in w)jT($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:FT.bind(w,Y)})},ET=($,w)=>()=>($&&(w=$($=0)),w),l9,Y2,y1,GY,A2,EH,KH,V9,_U,Wf,D0,s,TH,L9,HH,Q9,NH,qH,sJ,RH,O9,S9,oJ,MH,IH,yH,CH,kU,U2,hH,Z0,VH,LH,_9,DU,Bf,R0,b,QH,k9,OH,D9,SH,_H,eJ,kH,Z9,x9,DH,$f,ZH,xH,PH,bH,uH,ZU,X2,iH,cH="0.15.6",$$,mU,zY,jf,zf,dU,Ff,Gf,FY,Ef,Kf,Gw,J2,f2,q$,r$,W2,B2,vH,lH,j2,lU,kh,C0,c,dh,YN,gh,AN,lh,nh,d9,ph,UN,XN,th,g9,rh,ah,sh,oh,eh,Uf,JN,$V;var yf=j0(()=>{jT=Object.defineProperty;l9={};GT(l9,{withErrorRecovery:()=>a9,tryLoadConfig:()=>jH,loadConfigWithResult:()=>WH,loadConfig:()=>w2,isRetryableError:()=>YH,isConfigNotFoundError:()=>wH,isBunfigError:()=>s9,globalPerformanceMonitor:()=>GY,globalCache:()=>y1,getEnvOrDefault:()=>AH,generateConfigTypes:()=>zH,defaultGeneratedDir:()=>B2,defaultConfigDir:()=>W2,deepMergeWithArrayStrategy:()=>Rf,deepMerge:()=>o9,createLibraryConfig:()=>FH,config:()=>BH,bunfigPlugin:()=>GH,applyEnvVarsToConfig:()=>BY,TypeGenerationError:()=>Gf,SchemaValidationError:()=>FY,PluginError:()=>Kf,PerformanceMonitor:()=>Hf,FileSystemError:()=>Ff,ErrorFactory:()=>Gw,EnvVarError:()=>dU,EnvProcessor:()=>nU,ConfigValidator:()=>Mf,ConfigValidationError:()=>jf,ConfigNotFoundError:()=>mU,ConfigMergeError:()=>zf,ConfigLoader:()=>If,ConfigLoadError:()=>zY,ConfigFileLoader:()=>pU,ConfigCache:()=>Tf,CacheUtils:()=>A2,BunfigError:()=>$$,BrowserConfigError:()=>Ef,ArrayMergeStrategies:()=>J2});vH=ET(async()=>{Y2=import.meta.require,y1=new Tf,GY=new Hf,A2={createKey:mT,isEquivalent:dT,estimateMemoryUsage:gT},EH=bU(Jf.cwd(),"config"),KH=bU(Jf.cwd(),"src/generated"),V9=PU.env.CLARITY_LOG_DIR||RT(pT(),"logs"),_U={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:V9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Wf=await tT(),D0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},s=D0,TH=D0.red,L9=D0.green,HH=D0.yellow,Q9=D0.blue,NH=D0.magenta,qH=D0.cyan,sJ=D0.white,RH=D0.gray,O9=D0.bgRed,S9=D0.bgYellow,oJ=D0.bold,MH=D0.dim,IH=D0.italic,yH=D0.underline,CH=D0.reset,kU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},U2={debug:"\uD83D\uDD0D",info:Q9("ℹ"),success:L9("✓"),warning:S9(sJ(oJ(" WARN "))),error:O9(sJ(oJ(" ERROR ")))},hH=new iU("stacks"),Z0=new iU("bunfig",{showTags:!0}),VH=m0(jY.cwd(),"config"),LH=m0(jY.cwd(),"src/generated"),_9=xU.env.CLARITY_LOG_DIR||NT(oT(),"logs"),DU={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Bf=await eT(),R0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},b=R0,QH=R0.red,k9=R0.green,OH=R0.yellow,D9=R0.blue,SH=R0.magenta,_H=R0.cyan,eJ=R0.white,kH=R0.gray,Z9=R0.bgRed,x9=R0.bgYellow,DH=R0.bgGray,$f=R0.bold,ZH=R0.dim,xH=R0.italic,PH=R0.underline,bH=R0.strikethrough,uH=R0.reset,ZU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},X2={debug:"\uD83D\uDD0D",info:D9("ℹ"),success:k9("✓"),warning:x9(eJ($f(" WARN "))),error:Z9(eJ($f(" ERROR ")))},iH=new vU("stacks"),$$=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,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 w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},mU=class extends $${code="CONFIG_NOT_FOUND";constructor(w,Y,A){let U=A?` or alias "${A}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},zY=class extends $${code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},jf=class extends $${code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},zf=class extends $${code="CONFIG_MERGE_ERROR";constructor(w,Y,A,U){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:U,originalError:A.name,originalMessage:A.message});this.cause=A}},dU=class extends $${code="ENV_VAR_ERROR";constructor(w,Y,A,U){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:U})}},Ff=class extends $${code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Gf=class extends $${code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},FY=class extends $${code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},Ef=class extends $${code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,U){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:U})}},Kf=class extends $${code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Gw={configNotFound($,w,Y){return new mU($,w,Y)},configLoad($,w,Y){return new zY($,w,Y)},configValidation($,w,Y){return new jf($,w,Y)},configMerge($,w,Y,A){return new zf($,w,Y,A)},envVar($,w,Y,A){return new dU($,w,Y,A)},fileSystem($,w,Y){return new Ff($,w,Y)},typeGeneration($,w,Y){return new Gf($,w,Y)},schemaValidation($,w,Y){return new FY($,w,Y)},browserConfig($,w,Y,A){return new Ef($,w,Y,A)},plugin($,w,Y){return new Kf($,w,Y)}},J2={replace:"replace",concat:"concat",smart:"smart"},f2=/^https?:\/\//,q$=new vU("bunfig",{showTags:!0}),r$=new If,W2=d0(Qw.cwd(),"config"),B2=d0(Qw.cwd(),"src/generated")});lH=gU.env.CLARITY_LOG_DIR||mH(gH(),"logs"),j2={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:lH,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},lU={...j2},kh=(async()=>{try{let{loadConfig:$}=await vH().then(()=>l9),w=await $({name:"clarity",alias:"logging",defaultConfig:j2,cwd:gU.cwd()});if(w)Object.assign(lU,w)}catch{}return lU})();C0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},c=C0,dh=C0.red,YN=C0.green,gh=C0.yellow,AN=C0.blue,lh=C0.magenta,nh=C0.cyan,d9=C0.white,ph=C0.gray,UN=C0.bgRed,XN=C0.bgYellow,th=C0.bgGray,g9=C0.bold,rh=C0.dim,ah=C0.italic,sh=C0.underline,oh=C0.strikethrough,eh=C0.reset,Uf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},JN={debug:"\uD83D\uDD0D",info:AN("ℹ"),success:YN("✓"),warning:XN(d9(g9(" WARN "))),error:UN(d9(g9(" ERROR ")))};$V=new Ow("stacks")});var h1={};RW(h1,{shouldReusePort:()=>C1,safeStringify:()=>R$,safeDeleteFile:()=>Lf,resolvePathRewrite:()=>Vf,redactSensitive:()=>tU,isValidRootCA:()=>hf,isSingleProxyOptions:()=>KY,isSingleProxyConfig:()=>FN,isProcessElevated:()=>rU,isMultiProxyOptions:()=>_w,isMultiProxyConfig:()=>E2,getSudoPassword:()=>Sw,getPrimaryDomain:()=>aU,extractHostname:()=>zN,execSudoSync:()=>EY,debugLog:()=>E});import{execSync as Cf}from"node:child_process";import*as G2 from"node:fs/promises";function Sw(){return process.env.SUDO_PASSWORD}function rU(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function EY($){if(rU())return Cf($,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let w=Sw(),Y=$.replace(/'/g,"'\\''");if(w)return Cf(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return Cf(`sudo -n sh -c '${Y}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function E($,w,Y){if(Y)fN.debug(`[rpx:${$}] ${w}`)}function C1(){let $=process.env.RPX_REUSE_PORT;return $==="1"||$==="true"}function jN($){let w=$.toLowerCase();return WN.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function tU($){if(Array.isArray($))return $.map((Y)=>tU(Y));if(typeof $==="string")return BN.test($)?F2:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(jN(Y)){w[Y]=F2;continue}w[Y]=tU(A)}return w}function R$($,w){return JSON.stringify(tU($),null,w)}function zN($){if(_w($))return $.proxies.map((w)=>{let Y=w.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(KY($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function hf($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function aU($){if(!$)return"stacks.localhost";if(_w($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(KY($))return $.to||"stacks.localhost";return"stacks.localhost"}function E2($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function _w($){return"proxies"in $&&Array.isArray($.proxies)}function KY($){return"to"in $&&typeof $.to==="string"}function FN($){return!!($&&("to"in $)&&!("proxies"in $))}function Vf($,w){if(!w||w.length===0)return null;for(let Y of w)if($===Y.from||$.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,U=Y.stripPrefix===!0?$.slice(Y.from.length)||"/":$;return{targetHost:A,targetPath:U}}return null}async function Lf($,w){try{await G2.unlink($),E("certificates",`Successfully deleted: ${$}`,w)}catch(Y){if(Y.code!=="ENOENT")E("certificates",`Warning: Could not delete ${$}: ${Y}`,w)}}var fN,F2="[redacted]",WN,BN;var f0=j0(()=>{yf();fN=new Ow("rpx",{showTags:!1});WN=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),BN=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as sU}from"node:child_process";import{homedir as GN}from"node:os";import{join as EN}from"node:path";function oU(){return EN(GN(),"Library/Keychains/login.keychain-db")}function Of(){return[L1,oU()]}function K2($,w=Qf){let Y=sU(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let U of Y.split(`
|
|
182
|
+
`)){let X=U.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(X)A.push(X[1].toUpperCase())}return A}function Sf($){if(process.platform!=="darwin")return;let w=Lw($.caPath);if(!w)return;let Y=$.commonName??Qf,A=$.keychains??Of();for(let U of A)for(let X of K2(U,Y)){if(X===w)continue;try{if(U.startsWith("/Library"))EY(`security delete-certificate -Z ${X} "${U}"`);else sU(`security delete-certificate -Z ${X} "${U}"`,{stdio:"ignore"});E("ssl",`Removed stale Root CA ${X} from ${U}`,$.verbose)}catch{}}}function _f($,w,Y){if(process.platform!=="darwin")return eU($,Y);try{let U=sU(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return E("ssl",`verify-cert ${w}: ${U?"trusted":"not trusted"}`,Y?.verbose),U}catch{return!1}}function eU($,w){let Y=Lw($);if(!Y)return!1;for(let A of Of())try{let U=sU(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let X of U.split(`
|
|
183
|
+
`))if(X.toUpperCase().includes("SHA-256")){if(X.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return E("ssl",`Root CA fingerprint found in ${A}`,w?.verbose),!0}}catch{}return!1}var V1="-d -r trustRoot -p ssl -p basic",L1="/Library/Keychains/System.keychain",Qf="rpx.localhost";var kf=j0(()=>{NU();f0()});import{execSync as Df}from"node:child_process";import z0 from"node:fs/promises";import*as Zf from"node:os";import{homedir as Q1}from"node:os";import*as N2 from"node:path";import{join as F0}from"node:path";import*as Ew from"node:process";function xf($,w){return[...new Set($.filter(Boolean))].map((Y)=>({serverName:Y,cert:w.cert,key:w.key}))}function Pf($,w,Y){let A=F0(Q1(),".stacks","ssl"),U=[...new Set([w,...$,"rpx.localhost"])];return{https:{certPath:$X,keyPath:F0(A,"rpx.localhost.key"),caCertPath:F0(A,"rpx.localhost.ca.crt"),commonName:w},verbose:Y,regenerateUntrustedCerts:!0,proxies:U.map((X)=>({from:"localhost:1",to:X,cleanUrls:!1}))}}function q2($){return{caCertPath:F0($,TN),caKeyPath:F0($,HN)}}async function NN($,w){try{let[Y,A]=await Promise.all([z0.readFile($.caCertPath,"utf8"),z0.readFile($.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return E("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:Y,privateKey:A}}catch(Y){return E("ssl",`No existing Root CA at ${$.caCertPath} (${Y.code||Y}), will create one`,w),null}}function T2($){let w=new Set;w.add($);let Y=$.split(".");if(Y.length>=2)w.add(`*.${Y.slice(1).join(".")}`);return Array.from(w)}function R2($){let Y=aU($).replace(/\*/g,"wildcard"),A=F0(Q1(),".stacks","ssl"),U=A;if(typeof $?.https==="object")return U=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:A,{caCertPath:$.https.caCertPath||F0(U,`${Y}.ca.crt`),certPath:$.https.certPath||F0(U,`${Y}.crt`),keyPath:$.https.keyPath||F0(U,`${Y}.key`)};return{caCertPath:F0(U,`${Y}.ca.crt`),certPath:F0(U,`${Y}.crt`),keyPath:F0(U,`${Y}.key`)}}function H2($){let w=new Set;if(_w($))$.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";T2(A).forEach((U)=>w.add(U))});else if(KY($)){let Y=$.to||"rpx.localhost";T2(Y).forEach((A)=>w.add(A))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function O1($){if(Kw&&!$.forceRegenerate){E("ssl","Using cached SSL configuration",$.verbose);return}wX();let w=_w($)?$.proxies.map((j)=>j.to):[$.to];E("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let Y=TY($,$.verbose),A=Y.basePath||F0(Q1(),".stacks","ssl");await z0.mkdir(A,{recursive:!0});let U=q2(A),X=await NN(U,$.verbose),J=!1;if(!X){if($.verbose)R.info("Generating Root CA certificate (one-time)...");X=await _J(Y);try{await Promise.all([z0.writeFile(U.caCertPath,X.certificate),z0.writeFile(U.caKeyPath,X.privateKey,{mode:384})]),J=!0,E("ssl",`Persisted Root CA at ${U.caCertPath}`,$.verbose)}catch(j){throw E("ssl",`Error saving Root CA files: ${j}`,$.verbose),Error(`Failed to save Root CA files: ${j}`)}}else E("ssl",`Reusing existing Root CA from ${U.caCertPath}`,$.verbose);if($.verbose)R.info(`Generating host certificate for: ${w.join(", ")}`);let W=await kJ({...Y,rootCA:{certificate:X.certificate,privateKey:X.privateKey}});try{await Promise.all([z0.writeFile(Y.certPath,W.certificate),z0.writeFile(Y.keyPath,W.privateKey),z0.writeFile(Y.caCertPath,X.certificate)]),E("ssl","Certificate files saved successfully",$.verbose)}catch(j){throw E("ssl",`Error saving certificate files: ${j}`,$.verbose),Error(`Failed to save certificate files: ${j}`)}if(J?!1:await I2(U.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(E("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)R.success("Root CA is already trusted in system trust store");if(Kw={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)R.info("Adding certificate to system trust store (may require sudo permission)...");let B=!1;if(Ew.platform==="darwin")try{Sf({caPath:U.caCertPath,verbose:$.verbose});let j=oU();try{Df(`security add-trusted-cert ${V1} -k "${j}" "${U.caCertPath}"`,{stdio:"ignore"})}catch{}if(EY(`security add-trusted-cert ${V1} -k ${L1} "${U.caCertPath}"`),$.verbose)R.success("Successfully added Root CA to system trust store");B=!0;let z=F0(A,"trust-rpx-cert.sh"),G=`#!/bin/bash
|
|
182
184
|
echo "Trusting RPX Root CA"
|
|
183
|
-
sudo security add-trusted-cert ${
|
|
185
|
+
sudo security add-trusted-cert ${V1} -k ${L1} "${U.caCertPath}"
|
|
184
186
|
echo "Root CA trusted! Please restart your browser."
|
|
185
187
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
186
|
-
`;await
|
|
188
|
+
`;await z0.writeFile(z,G,{mode:493})}catch(j){if($.verbose)R.warn(`Could not add Root CA to trust store automatically: ${j}`);let z=F0(A,"trust-rpx-cert.sh"),G=`#!/bin/bash
|
|
187
189
|
echo "Trusting RPX Root CA"
|
|
188
|
-
sudo security add-trusted-cert ${
|
|
190
|
+
sudo security add-trusted-cert ${V1} -k ${L1} "${U.caCertPath}"
|
|
189
191
|
echo "Root CA trusted! Please restart your browser."
|
|
190
192
|
echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
|
|
191
|
-
`;if(await
|
|
193
|
+
`;if(await z0.writeFile(z,G,{mode:493}),$.verbose)R.info(`Created a trust helper script at: ${z}`),R.info(`If you're still having certificate issues, run: sh ${z}`)}else if(Ew.platform==="linux")try{let{exec:j}=await import("node:child_process"),z="/usr/local/share/ca-certificates/rpx",G=`
|
|
192
194
|
mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
|
|
193
|
-
cp "${
|
|
195
|
+
cp "${U.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
|
|
194
196
|
update-ca-certificates
|
|
195
197
|
echo "RPX Root CA installed. Please restart your browser."
|
|
196
|
-
`,F=
|
|
197
|
-
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${
|
|
198
|
+
`,F=F0(Zf.tmpdir(),`rpx-trust-${Date.now()}.sh`);await z0.writeFile(F,G,{mode:493}),await new Promise((T)=>{j(`sudo bash "${F}"`,(K)=>{if(K){if($.verbose)R.warn(`Could not trust certificates: ${K}`);T(!1)}else{if($.verbose)R.success("Successfully added certificates to system trust store");T(!0)}})}),await z0.unlink(F).catch(()=>{}),B=!0}catch(j){if($.verbose)R.warn(`Failed to trust certificates: ${j}`)}else if(Ew.platform==="win32")try{let j=`
|
|
199
|
+
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${U.caCertPath.replace(/\//g,"\\")}")
|
|
198
200
|
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
|
|
199
201
|
$store.Open("ReadWrite")
|
|
200
202
|
$store.Add($cert)
|
|
201
203
|
$store.Close()
|
|
202
204
|
Write-Host "Root CA trusted successfully!"
|
|
203
|
-
`,j=k0(BJ.tmpdir(),"rpx-trust.ps1");if(await q0.writeFile(j,E),C1(`powershell -ExecutionPolicy Bypass -File "${j}"`),$.verbose)q.success("Successfully added certificate to Windows trust store");B=!0}catch(E){if($.verbose)q.warn(`Could not trust certificate: ${E}`)}else try{await j8(W,X.certificate,A),B=!0}catch(E){if($.verbose)q.warn(`Could not add certificate to trust store: ${E}`)}if(Tw={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)q.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!B&&$.verbose)q.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),q.warn("This will bypass the warning and you should only need to do it once")}function K7(){Tw=null}async function a$($){if(!$)return null;if(Tw)return Tw;let w=wA($);try{let[A,Y,f]=await Promise.all([q0.access(w.keyPath).then(()=>!0).catch(()=>!1),q0.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?q0.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!A||!Y)return z("ssl",`Certificate files don't exist: key=${A}, cert=${Y}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let X="regenerateUntrustedCerts"in $,U=$.regenerateUntrustedCerts,W=X?U!==!1:!0;z("ssl",`Trust check: hasFlag=${X}, flagValue=${U}, shouldCheckTrust=${W}`,$.verbose);let J=w.basePath||k0(xf(),".stacks","ssl"),B=lT(J);if(!(W?await pT(B.caCertPath,$):!0))return z("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[j,T,F]=await Promise.all([q0.readFile(w.keyPath,"utf8"),q0.readFile(w.certPath,"utf8"),f&&w.caCertPath?q0.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return z("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(Sw($))try{let{X509Certificate:H}=await import("node:crypto"),K=new H(T).subjectAltName||"",N=$.proxies.map((h)=>h.to).filter((h)=>!K.includes(`DNS:${h}`));if(N.length>0)return z("ssl",`Certificate missing SANs for: ${N.join(", ")}, will regenerate`,$.verbose),null}catch(H){z("ssl",`Could not verify cert SANs: ${H}`,$.verbose)}return z("ssl","Successfully loaded existing certificates",$.verbose),Tw={key:j,cert:T,ca:F},Tw}catch(A){return z("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function wA($,w){let A=Qf($);z("ssl",`Primary domain: ${A}`,w);let Y=gT($),f=k0(xf(),".stacks","ssl");if(typeof $.https==="object"){let X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:f,U={domain:A,hostCertCN:A,basePath:X,caCertPath:$.https.caCertPath||Y.caCertPath,certPath:$.https.certPath||Y.certPath,keyPath:$.https.keyPath||Y.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||A,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(dT($)).map((W)=>({type:2,value:W}))};if(wJ($.https.rootCA))U.rootCA=$.https.rootCA;return U}return{domain:A,hostCertCN:A,basePath:f,...Y,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:A,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:w||!1,subjectAltNames:Array.from(dT($)).map((X)=>({type:2,value:X}))}}async function tT($,w){let A=gT({to:$,verbose:w}),Y=[A.caCertPath,A.certPath,A.keyPath];z("certificates","Attempting to clean up relating certificates",w),await Promise.all(Y.map((f)=>YJ(f,w)))}async function pT($,w){try{if(z("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),jw.platform==="darwin"){if(w?.serverName)return JJ($,w.serverName,{verbose:w?.verbose});return Zf($,{verbose:w?.verbose})}else if(jw.platform==="win32")try{let Y=C1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!Y)return z("ssl","Could not extract certificate subject",w?.verbose),!1;let f=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(C1(f).toString().includes(Y))return z("ssl","Certificate found in trusted root store",w?.verbose),!0;return z("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if(jw.platform==="linux")try{let Y=C1(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",f=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of f)try{if(C1(`find ${X} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${Y}"`).toString().includes(Y))return z("ssl",`Certificate fingerprint found in ${X}`,w?.verbose),!0}catch{}return z("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return z("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return z("ssl",`Platform ${jw.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return z("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}var Tw=null,z7="rpx-root-ca.crt",G7="rpx-root-ca.key";var Pf=E0(()=>{T8();fw();H8();WJ();U0();WJ();K8()});import*as j$ from"node:path";function AA($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function N7($){let w=j$.extname($).toLowerCase();return R7[w]??"application/octet-stream"}function q7($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let A=j$.posix.normalize(`/${w}`);if(A.includes(".."))return null;return A.replace(/^\/+/,"")}function h7($,w){let A=q7($);if(A===null)return null;let Y=j$.posix.extname(A);if(w.cleanUrls&&Y===".html"){let f=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:j$.join(w.dir,A),redirectTo:f||"/"}}if(A===""||$.endsWith("/"))return{filePath:j$.join(w.dir,A,"index.html")};if(Y!=="")return{filePath:j$.join(w.dir,A)};if(w.pathRewriteStyle==="flat")return{filePath:j$.join(w.dir,`${A}.html`)};return{filePath:j$.join(w.dir,A,"index.html")}}async function rT($,w){let A=h7($,w);if(!A)return new Response("Forbidden",{status:403});if(A.redirectTo)return new Response(null,{status:301,headers:{Location:A.redirectTo}});let Y=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",f=Bun.file(A.filePath);if(await f.exists())return new Response(f,{status:200,headers:{"Content-Type":N7(A.filePath),"Cache-Control":Y}});if(w.spa){let X=j$.join(w.dir,"index.html"),U=Bun.file(X);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var R7;var YA=E0(()=>{R7={".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 M7($){return($.headers.get("host")||"").split(":")[0]}function sT($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let A=$.slice(w.length);return A===""?"/":A}return $}function aT($,w,A){let Y=new URL($.url),f=w.sourceHost??"",U=w.stripBasePathPrefix??!1?sT(Y.pathname,w.basePath):Y.pathname,W=AJ(U,w.pathRewrites);if(W)f=W.targetHost,U=W.targetPath,z("request",`Path rewrite: ${Y.pathname} → ${f}${U}`,A);return{targetHost:f,targetPath:U,search:Y.search}}function fA($,w){return async(A,Y)=>{let f=new URL(A.url),X=M7(A),U=$(X,f.pathname);if(!U)return z("request",`No route found for host: ${X}`,w),new Response(`No proxy configured for ${X}`,{status:404});if(U.static){let T=U.stripBasePathPrefix??!0?sT(f.pathname,U.basePath):f.pathname;return rT(T,U.static)}if(A.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!Y||!U.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:j,targetPath:T,search:F}=aT(A,U,w),H=`ws://${j}${T}${F}`,G={};for(let[N,h]of A.headers)if(!y7.has(N.toLowerCase())&&N.toLowerCase()!=="host")G[N]=h;G.host=j,G["x-forwarded-for"]="127.0.0.1",G["x-forwarded-proto"]="https",G["x-forwarded-host"]=X;let K={targetUrl:H,forwardHeaders:G};if(Y.upgrade(A,{data:K})){z("ws",`upgraded ${X}${T} → ${H}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!U.sourceHost)return new Response(`No upstream configured for ${X}`,{status:502});let{targetHost:W,targetPath:J,search:B}=aT(A,U,w),E=`http://${W}${J}${B}`;try{let j=new Headers(A.headers);if(j.set("host",W),U.changeOrigin)j.set("origin",`http://${U.sourceHost}`);j.set("x-forwarded-for","127.0.0.1"),j.set("x-forwarded-proto","https"),j.set("x-forwarded-host",X);let T=await fetch(E,{method:A.method,headers:j,body:A.body,redirect:"manual"});if(U.cleanUrls&&f.pathname.endsWith(".html")){let H=f.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:H}})}let F=new Headers(T.headers);return new Response(T.body,{status:T.status,statusText:T.statusText,headers:F})}catch(j){return z("request",`Proxy error for ${X}: ${j}`,w),new Response(`Proxy Error: ${j}`,{status:502})}}}function XA($){let w=new WeakMap;return{open(A){let{targetUrl:Y,forwardHeaders:f}=A.data,X;try{X=new WebSocket(Y,{headers:f})}catch(W){z("ws",`failed to open upstream ${Y}: ${W}`,$),A.close(1011,"upstream connect failed");return}X.binaryType="arraybuffer";let U={upstream:X,upstreamOpen:!1,pending:[]};w.set(A,U),X.addEventListener("open",()=>{U.upstreamOpen=!0;for(let W of U.pending)X.send(W);U.pending=[]}),X.addEventListener("message",(W)=>{A.send(W.data)}),X.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),X.addEventListener("error",()=>{z("ws",`upstream error for ${Y}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,Y){let f=w.get(A);if(!f)return;let X=typeof Y==="string"?Y:new Uint8Array(Y);if(f.upstreamOpen)f.upstream.send(X);else f.pending.push(X)},close(A,Y,f){let X=w.get(A);if(!X)return;w.delete(A);try{X.upstream.close(Y||1000,f||"")}catch{}}}}var y7;var bf=E0(()=>{YA();U0();y7=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function UA($){return $.startsWith("*.")}function cf($,w){if(!UA(w))return!1;let A=w.slice(1);return $.length>A.length&&$.endsWith(A)}function L1($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function C7($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function JA($){let w=new Map;for(let Y of $){let f=L1(Y.path),X=w.get(Y.host);if(!X)X=new Map,w.set(Y.host,X);X.set(f,Y.route)}let A=new Map;for(let[Y,f]of w){let X=[];for(let[U,W]of f)X.push({path:U,route:W});X.sort((U,W)=>W.path.length-U.path.length),A.set(Y,X)}return A}function S7($,w){let A=$.get(w);if(A!==void 0)return A;let Y,f=-1;for(let[X,U]of $){if(!UA(X))continue;if(cf(w,X)){let W=X.length-1;if(W>f)f=W,Y=U}}return Y}function WA($,w,A){let Y=S7($,w);if(!Y)return;for(let f of Y)if(C7(A,f.path))return f.route;return}var uf=()=>{};import*as BA from"node:fs/promises";import*as EJ from"node:path";function L7($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function V7($,w,A,Y){try{let[f,X]=await Promise.all([BA.readFile(w,"utf8"),BA.readFile(A,"utf8")]);return{serverName:$,cert:f,key:X}}catch(f){return z("sni",`skipping ${$}: ${f.message}`,Y),null}}async function jJ($,w){let A=new Map;if($.certsDir){let f=[];try{f=await BA.readdir($.certsDir)}catch(X){z("sni",`certsDir read failed (${$.certsDir}): ${X.message}`,w)}for(let X of f){let U=L7(X);if(!U)continue;let W=X.slice(0,-4);A.set(U,{certPath:EJ.join($.certsDir,X),keyPath:EJ.join($.certsDir,`${W}.key`)})}}if($.domains)for(let[f,X]of Object.entries($.domains))A.set(f,X);let Y=[];for(let[f,X]of A){let U=await V7(f,X.certPath,X.keyPath,w);if(U)Y.push(U)}return Y}var TJ=E0(()=>{U0()});import*as Fw from"node:fs/promises";import*as FJ from"node:path";function _7($,w){if(!w||w.length===0)return!1;return w.some((A)=>{let Y=A.startsWith(".")?A.slice(1):A;return $===Y||$.endsWith(`.${Y}`)})}function Q7($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class nf{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??pY,this.issuer=$.issuer??rU,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??O7;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!Q7($))return!1;if(_7($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return z("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;let w=this.inFlight.get($);if(w)return w;let A=this.negativeCache.get($);if(A!==void 0&&Date.now()<A)return z("on-demand",`${$} negatively cached for ${A-Date.now()}ms`,this.verbose),!1;let Y=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,Y),Y}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return z("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),!1;try{z("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let A={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,A),this.negativeCache.delete($),z("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.negativeCache.set($,Date.now()+this.negativeCacheMs),z("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}async loadFromDisk($){let{certPath:w,keyPath:A}=this.pathsFor($);try{let[Y,f]=await Promise.all([Fw.readFile(w,"utf8"),Fw.readFile(A,"utf8")]),X={serverName:$,cert:Y,key:f};return this.certs.set($,X),z("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:FJ.join(this.certsDir,`${$}.crt`),keyPath:FJ.join(this.certsDir,`${$}.key`)}}async persist($,w,A){await Fw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:Y,keyPath:f}=this.pathsFor($);await Promise.all([Fw.writeFile(Y,w,"utf8"),Fw.writeFile(f,A,{encoding:"utf8",mode:384})])}}var O7=60000;var zJ=E0(()=>{T8();U0()});import*as vf from"node:fs";import*as n0 from"node:fs/promises";import{homedir as D7}from"node:os";import*as GJ from"node:path";import*as mf from"node:process";function zw(){return GJ.join(D7(),".stacks","rpx","registry.d")}function EA($){return typeof $==="string"&&$.length>0&&$.length<=128&&k7.test($)}function HJ($,w){if(!EA(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return GJ.join($,`${w}.json`)}function l0($){if(!Number.isInteger($)||$<=0)return!1;try{return mf.kill($,0),!0}catch(w){return w.code==="EPERM"}}function oT($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,f=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&EA(w.id)&&(Y||f)&&typeof w.to==="string"&&w.to.length>0&&X&&A&&typeof w.createdAt==="string"}async function Z7($){await n0.mkdir($,{recursive:!0})}async function eT($,w=zw(),A){if(!oT($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await Z7(w);let Y=HJ(w,$.id),f=`${Y}.tmp.${mf.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await n0.writeFile(f,X,{encoding:"utf8",mode:420}),await n0.rename(f,Y),z("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await n0.unlink(f).catch(()=>{}),U}}async function KJ($,w=zw(),A){let Y=HJ(w,$);try{await n0.unlink(Y),z("registry",`removed entry ${$}`,A)}catch(f){if(f.code!=="ENOENT")throw f}}async function x7($,w=zw(),A){let Y=HJ(w,$);try{let f=await n0.readFile(Y,"utf8"),X=JSON.parse(f);if(!oT(X))return z("registry",`entry ${$} failed validation, removing`,A),await n0.unlink(Y).catch(()=>{}),null;return X}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await n0.unlink(Y).catch(()=>{}),null;throw f}}async function Lw($=zw(),w){let A;try{A=await n0.readdir($)}catch(f){if(f.code==="ENOENT")return[];throw f}let Y=[];for(let f of A){if(!f.endsWith(".json"))continue;let X=f.slice(0,-5);if(!EA(X))continue;let U=await x7(X,$,w);if(U)Y.push(U)}return Y}async function df($=zw(),w){let A=await Lw($,w),Y=0;for(let f of A){if(f.pid===void 0)continue;if(!l0(f.pid))z("registry",`GC: pid ${f.pid} for ${f.id} is dead, removing`,w),await KJ(f.id,$,w).catch(()=>{}),Y++}return Y}function RJ($,w={}){let A=w.dir??zw(),Y=w.debounceMs??100,f=w.pollMs??Math.max(Y*2,250),X=w.verbose;vf.mkdirSync(A,{recursive:!0});let U=null,W=!1,J=null,B=!1,E=(K)=>{return JSON.stringify(K.map((R)=>({id:R.id,from:R.from,to:R.to,path:R.path,pid:R.pid,pathRewrites:R.pathRewrites,cleanUrls:R.cleanUrls,changeOrigin:R.changeOrigin,static:R.static})).sort((R,N)=>R.id.localeCompare(N.id)))},j=()=>{if(U=null,W)return;Lw(A,X).then((K)=>{return J=E(K),$(K)}).catch((K)=>{z("registry",`watcher onChange failed: ${K}`,X)})},T=()=>{if(W)return;if(U)clearTimeout(U);U=setTimeout(j,Y)},H=setInterval(()=>{if(W||B)return;B=!0,Lw(A,X).then((K)=>{if(E(K)!==J)T()}).catch((K)=>{z("registry",`watcher poll failed: ${K}`,X)}).finally(()=>{B=!1})},f),G=vf.watch(A,{persistent:!0},(K,R)=>{if(R&&/\.tmp\.\d+\.\d+$/.test(R))return;T()});return G.on("error",(K)=>{z("registry",`watcher error: ${K}`,X)}),T(),{close:()=>{if(W=!0,U)clearTimeout(U);clearInterval(H),G.close()}}}var k7;var jA=E0(()=>{U0();k7=/^[a-zA-Z0-9._-]+$/});import{spawn as P7}from"node:child_process";import*as Vw from"node:fs/promises";import{homedir as i7}from"node:os";import*as TA from"node:path";import*as v0 from"node:process";function s$(){return TA.join(i7(),".stacks","rpx")}function wF($=s$()){return TA.join($,"daemon.pid")}async function $F($=s$()){try{let w=await Vw.readFile(wF($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function b7($=s$()){await Vw.unlink(wF($)).catch(()=>{})}function c7(){let $=v0.execPath,w=TA.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&v0.argv[1])return[$,v0.argv[1],"daemon:start"];return[$,"daemon:start"]}async function AF($={}){let w=$.rpxDir??s$(),A=$.verbose??!1;await Gw({rpxDir:w,verbose:A}).catch((E)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let Y=await $F(w);if(Y!==null&&l0(Y))return z("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await b7(w);await Vw.mkdir(w,{recursive:!0});let f=$.spawnCommand??c7();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${f.join(" ")}`,A);let X=P7(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??v0.cwd(),env:$.spawnEnv?{...v0.env,...$.spawnEnv}:v0.env});X.unref();let U=null;X.once("error",(E)=>{U=E});let W=$.startupTimeoutMs??5000,J=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let E=await $F(w);if(E!==null&&l0(E))return z("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((j)=>setTimeout(j,J))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var NJ=E0(()=>{fw();Pf();bf();uf();TJ();zJ();YA();jA();V1();U0()});import*as Hw from"node:fs/promises";import{homedir as u7}from"node:os";import*as qJ from"node:path";function fF(){return qJ.join(u7(),".stacks","rpx")}function hJ($=fF()){return qJ.join($,n7)}async function gf($=fF()){try{let w=await Hw.readFile(hJ($),"utf8"),A=JSON.parse(w);if(A.version!==lf||!Array.isArray(A.resolvers))return null;return{version:lf,resolvers:A.resolvers.filter((Y)=>typeof Y==="string"),domains:Array.isArray(A.domains)?A.domains.filter((Y)=>typeof Y==="string"):[],ownerPid:typeof A.ownerPid==="number"?A.ownerPid:null,updatedAt:typeof A.updatedAt==="string"?A.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function XF($,w){await Hw.mkdir($,{recursive:!0}),await Hw.writeFile(hJ($),`${JSON.stringify(w,null,2)}
|
|
204
|
-
|
|
205
|
+
`,z=F0(Zf.tmpdir(),"rpx-trust.ps1");if(await z0.writeFile(z,j),Df(`powershell -ExecutionPolicy Bypass -File "${z}"`),$.verbose)R.success("Successfully added certificate to Windows trust store");B=!0}catch(j){if($.verbose)R.warn(`Could not trust certificate: ${j}`)}else try{await xJ(W,X.certificate,Y),B=!0}catch(j){if($.verbose)R.warn(`Could not add certificate to trust store: ${j}`)}if(Kw={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!B&&$.verbose)R.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),R.warn("This will bypass the warning and you should only need to do it once")}function wX(){Kw=null}async function a$($){if(!$)return null;if(Kw)return Kw;let w=TY($);try{let[Y,A,U]=await Promise.all([z0.access(w.keyPath).then(()=>!0).catch(()=>!1),z0.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?z0.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return E("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let X="regenerateUntrustedCerts"in $,J=$.regenerateUntrustedCerts,W=X?J!==!1:!0;E("ssl",`Trust check: hasFlag=${X}, flagValue=${J}, shouldCheckTrust=${W}`,$.verbose);let f=w.basePath||F0(Q1(),".stacks","ssl"),B=q2(f);if(!(W?await I2(B.caCertPath,$):!0))return E("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[z,G,F]=await Promise.all([z0.readFile(w.keyPath,"utf8"),z0.readFile(w.certPath,"utf8"),U&&w.caCertPath?z0.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return E("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(_w($))try{let{X509Certificate:T}=await import("node:crypto"),H=new T(G).subjectAltName||"",M=$.proxies.map((I)=>I.to).filter((I)=>!H.includes(`DNS:${I}`));if(M.length>0)return E("ssl",`Certificate missing SANs for: ${M.join(", ")}, will regenerate`,$.verbose),null}catch(T){E("ssl",`Could not verify cert SANs: ${T}`,$.verbose)}return E("ssl","Successfully loaded existing certificates",$.verbose),Kw={key:z,cert:G,ca:F},Kw}catch(Y){return E("ssl",`Error checking existing certificates: ${Y}`,$.verbose),null}}function TY($,w){let Y=aU($);E("ssl",`Primary domain: ${Y}`,w);let A=R2($),U=F0(Q1(),".stacks","ssl");if(typeof $.https==="object"){let X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:U,J={domain:Y,hostCertCN:Y,basePath:X,caCertPath:$.https.caCertPath||A.caCertPath,certPath:$.https.certPath||A.certPath,keyPath:$.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||Y,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(H2($)).map((W)=>({type:2,value:W}))};if(hf($.https.rootCA))J.rootCA=$.https.rootCA;return J}return{domain:Y,hostCertCN:Y,basePath:U,...A,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:Y,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:w||!1,subjectAltNames:Array.from(H2($)).map((X)=>({type:2,value:X}))}}async function M2($,w){let Y=R2({to:$,verbose:w}),A=[Y.caCertPath,Y.certPath,Y.keyPath];E("certificates","Attempting to clean up relating certificates",w),await Promise.all(A.map((U)=>Lf(U,w)))}async function I2($,w){try{if(E("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),Ew.platform==="darwin"){if(w?.serverName)return _f($,w.serverName,{verbose:w?.verbose});return eU($,{verbose:w?.verbose})}else if(Ew.platform==="win32")try{let Y=cJ($)||"";if(!Y)return E("ssl","Could not extract certificate subject",w?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(Df(A).toString().includes(Y))return E("ssl","Certificate found in trusted root store",w?.verbose),!0;return E("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Windows: ${Y}`,w?.verbose),!1}else if(Ew.platform==="linux")try{let Y=Lw($);if(!Y)return E("ssl","Could not extract certificate fingerprint",w?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let U of A){let X;try{X=await z0.readdir(U)}catch{continue}for(let J of X){let W=Lw(N2.join(U,J));if(W&&W===Y)return E("ssl",`Certificate fingerprint found in ${U}`,w?.verbose),!0}}return E("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Linux: ${Y}`,w?.verbose),!1}return E("ssl",`Platform ${Ew.platform} not supported for certificate trust check`,w?.verbose),!1}catch(Y){return E("ssl",`Error checking if certificate is trusted: ${Y}`,w?.verbose),!1}}var Kw=null,$X,TN="rpx-root-ca.crt",HN="rpx-root-ca.key";var YX=j0(()=>{TU();fw();iJ();kf();f0();kf();NU();NU();$X=F0(Q1(),".stacks","ssl","rpx.localhost.crt")});function MN($){return RN.has($.toUpperCase())}function IN(){let $=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite($)&&$>0?$:30000}function yN($){let w=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(w)&&w>0?w:$*8}function CN(){let $=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite($)&&$>0?$:0}function hN(){let $=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite($)&&$>0?$:0}function VN(){let $=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite($)&&$>0?$:256}class Q2{socket=null;buf=new Uint8Array(LN);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll($){let w=this.socket,Y=w.write($);while(Y<$.length){if(this.closed)throw AX;await new Promise((A)=>{this.drainWaiter=A}),Y+=w.write($.subarray(Y))}}wakeDrain(){let $=this.drainWaiter;if($)this.drainWaiter=null,$()}push($){if(this.bodyQueue){let w=$.length<=this.bodyRemaining?$.length:this.bodyRemaining;if(w>0)this.bodyQueue.push($.slice(0,w)),this.queuedBytes+=w;if(this.bodyRemaining-=w,w<$.length)this.appendToBuf($.subarray(w));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf($),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>QN)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=ON)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf($){let w=this.len+$.length;if(w>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,w));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set($,this.len),this.len=w}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let $=this.waiter;if($)this.waiter=null,$()}waitForData($){if(this.len>$||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class O2{host;port;maxTotal;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=IN();maxWaiters;checkoutIdleMs=CN();inUse=new Set;constructor($,w,Y){this.host=$;this.port=w;this.maxTotal=Y;this.maxWaiters=yN(Y)}trackCheckout($){if($.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add($),this.ensureSweeper()}dial(){let $=new Q2;return qN({hostname:this.host,port:this.port,socket:{data:(w,Y)=>$.push(Y),drain:()=>$.wakeDrain(),close:()=>$.markClosed(),end:()=>$.markClosed(),error:()=>$.markClosed(),connectError:()=>$.markClosed(),timeout:()=>$.markTimedOut()}}).then((w)=>{let Y=w;Y.setNoDelay?.(!0);let A=hN();if(A>0)Y.timeout?.(A);return $.socket=w,$})}acquireIdleSync(){while(this.idle.length){let $=this.idle.pop();if(!$.closed)return $.socket?.ref(),$.pos=0,$.len=0,this.trackCheckout($),$;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw kw;let $=await this.waitForSlot();if($===kw)throw kw;if($)return $.pos=0,$.len=0,this.trackCheckout($),$}this.open++;try{let $=await this.dial();return this.trackCheckout($),$}catch($){throw this.open--,this.wakeWaiter(),$}}waitForSlot(){return new Promise(($)=>{let w=!1,Y=(X)=>{if(w)return;w=!0,clearTimeout(U),$(X)},A=(X)=>Y(X),U=setTimeout(()=>{let X=this.waiters.indexOf(A);if(X!==-1)this.waiters.splice(X,1);Y(kw)},this.queueWaitMs);U.unref?.(),this.waiters.push(A)})}release($){if(this.inUse.delete($),$.closed){this.open--,this.wakeWaiter();return}$.clearStreaming(),$.compact(),$.fresh=!1;let w=this.waiters.shift();if(w){$.socket?.ref(),this.trackCheckout($),w($);return}$.idleSince=Date.now(),$.socket?.unref(),this.idle.push($),this.ensureSweeper()}destroy($){this.inUse.delete($),$.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let $=this.waiters.shift();if($)$(null)}ensureSweeper(){if(this.sweeper)return;let $=this.checkoutIdleMs>0?Math.min(bf,this.checkoutIdleMs):bf;this.sweeper=setInterval(()=>this.sweep(),$),this.sweeper.unref?.()}sweep(){let $=Date.now(),w=$-bf;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=w)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=$-this.checkoutIdleMs;for(let A of this.inUse)if(!A.closed&&A.lastActivityAt>0&&A.lastActivityAt<=Y)A.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper)clearInterval(this.sweeper),this.sweeper=null}}function ZN($,w){let Y=y2.get($);if(!Y){let A=$.lastIndexOf(":"),U=A===-1?$:$.slice(0,A),X=A===-1?80:Number($.slice(A+1));Y=new O2(U,X,w),y2.set($,Y)}return Y}function C2($,w,Y){for(let A=Y+3;A<w;A++)if($[A]===10&&$[A-1]===13&&$[A-2]===10&&$[A-3]===13)return A-3;return-1}function xN($,w,Y){let A=L2.decode($.subarray(w,Y)),U=A.indexOf(`\r
|
|
206
|
+
`),X=U===-1?A:A.slice(0,U),J=X.indexOf(" "),W=Number.parseInt(X.slice(J+1,J+5),10),f=X.startsWith("HTTP/1.0"),B=[],j=-1,z=!1,G=f,F=!1,T=!1,K=U===-1?A.length:U+2;while(K<A.length){let H=A.indexOf(`\r
|
|
207
|
+
`,K);if(H===-1)H=A.length;let q=A.slice(K,H);if(K=H+2,q==="")continue;let M=q.indexOf(":");if(M===-1)continue;let I=q.slice(0,M),h=q.slice(M+1).trim(),N=I.charCodeAt(0)|32;if(N===99||N===116||N===107){let C=I.toLowerCase();if(C==="content-length"){let O=/^\d+$/.test(h)?Number(h):Number.NaN;if(!Number.isSafeInteger(O)||j>=0&&j!==O)T=!0;else j=O;continue}if(C==="transfer-encoding"){if(h.toLowerCase().includes("chunked"))z=!0;continue}if(C==="connection"){let O=h.toLowerCase();if(O.includes("close"))G=!0;if(O.includes("keep-alive"))F=!0;continue}if(C==="keep-alive")continue}B.push([I,h])}if(f&&F)G=!1;if(z&&j>=0)j=-1;return{status:W,headerEnd:Y,headers:B,contentLength:j,chunked:z,closeConn:G,malformed:T}}function PN($,w){return w||$===204||$===304}async function S2($){let{hostPort:w,method:Y,path:A,reqHeaders:U,forwardedHost:X,originOverride:J,body:W}=$,f=Y==="HEAD";if(U.get("expect")||U.get("upgrade"))throw HY;let B=null;if(W){let F=U.get("content-length"),T=F?Number.parseInt(F,10):Number.NaN;if(Number.isNaN(T)||T>h2)throw HY;if(B=await dN(W),B===null)throw HY}let j=mN(Y,A,U,w,X,J,B),z=j;if(B&&B.length)z=new Uint8Array(j.length+B.length),z.set(j),z.set(B,j.length);let G=ZN(w,$.maxPerHost??VN());for(let F=0;;F++){if(F>0)await new Promise((K)=>{setTimeout(K,F)});let T;try{T=G.acquireIdleSync()??await G.acquireOrDial()}catch(K){if(K!==kw&&F<4)continue;throw K}try{let K=T.socket.write(z);if(K<z.length)await T.writeAll(z.subarray(K));return await uN(G,T,f)}catch(K){let H=K===AX&&F<4&&(T.fresh||MN(Y));if(G.destroy(T),H)continue;if(K===AX)throw Error("upstream closed connection");throw K}}}async function bN($){let w=C2($.buf,$.len,$.pos);while(w===-1){if($.closed){if($.timedOut)throw uf;if($.len===$.pos)throw AX;throw Error("upstream closed mid-header")}if($.len-$.pos>V2)throw Error("upstream header block too large");await $.waitForData($.len),w=C2($.buf,$.len,$.pos)}return w}async function uN($,w,Y){let A;for(;;){let X=await bN(w);if(A=xN(w.buf,w.pos,X),w.pos=X+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw $.destroy(w),Error("upstream sent malformed response framing");let U=A.headers;if(PN(A.status,Y))return _2($,w,A.closeConn),new Response(null,{status:A.status,headers:U});if(A.chunked)return new Response(vN($,w,A.closeConn),{status:A.status,headers:U});if(A.contentLength>=0){if(w.len-w.pos>=A.contentLength){let J=w.pos+A.contentLength,W=w.len>J,f=null;if(A.contentLength>=SN)f=w.buf.subarray(w.pos,J),w.buf=new Uint8Array(_N);else if(A.contentLength>0)f=w.buf.slice(w.pos,J);if(w.pos=0,w.len=0,A.closeConn||W)$.destroy(w);else $.release(w);return new Response(f,{status:A.status,headers:U})}return new Response(iN($,w,A.contentLength,A.closeConn),{status:A.status,headers:U})}return new Response(cN(w),{status:A.status,headers:U})}function _2($,w,Y){if(Y||w.pos!==w.len)$.destroy(w);else $.release(w)}function iN($,w,Y,A){let U=w.len-w.pos,X=U>0?w.buf.slice(w.pos,w.len):null;w.pos=0,w.len=0,w.bodyQueue=[],w.bodyRemaining=Y-U,w.queuedBytes=0,w.streamingBody=!0;let J=(W)=>{if(w.bodyQueue=null,A||w.len>0)$.destroy(w);else $.release(w);W.close()};return new ReadableStream({start(W){if(X)W.enqueue(X);if(w.bodyRemaining===0&&w.bodyQueue.length===0)J(W)},async pull(W){for(;;){let f=w.bodyQueue;if(f&&f.length>0){let B=f.shift();if(w.queuedBytes-=B.length,w.resumeIfDrained(),W.enqueue(B),w.bodyRemaining===0&&f.length===0)J(W);return}if(w.bodyRemaining===0){if(w.bodyQueue)J(W);return}if(w.closed){w.bodyQueue=null,$.destroy(w),W.error(Error("upstream closed mid-body"));return}await w.waitForBody()}},cancel(){w.bodyQueue=null,$.destroy(w)}})}function cN($){return $.streamingBody=!0,new ReadableStream({async pull(w){for(;;){if($.len>$.pos){w.enqueue($.buf.slice($.pos,$.len)),$.pos=$.len,$.resumeIfDrained();return}if($.closed){$.destroy(),w.close();return}await $.waitForData($.len)}},cancel(){$.destroy()}})}function vN($,w,Y){w.streamingBody=!0;let A=0,U=!1;async function X(){for(;;){for(let J=w.pos;J+1<w.len;J++)if(w.buf[J]===13&&w.buf[J+1]===10){let W=L2.decode(w.buf.subarray(w.pos,J));return w.pos=J+2,W}if(w.closed)throw Error("upstream closed mid-chunk-header");if(w.len-w.pos>V2)throw Error("upstream chunk header too large");await w.waitForData(w.len)}}return new ReadableStream({async pull(J){for(;;){if(A>0){if(w.len===w.pos){if(w.closed){$.destroy(w),J.error(Error("upstream closed mid-chunk"));return}await w.waitForData(w.len);continue}let j=Math.min(A,w.len-w.pos);if(J.enqueue(w.buf.slice(w.pos,w.pos+j)),w.pos+=j,A-=j,w.resumeIfDrained(),A===0)U=!0;return}if(U)await X(),U=!1;let W=await X(),f=W.indexOf(";"),B=Number.parseInt(f===-1?W:W.slice(0,f),16);if(!Number.isInteger(B)||B<0){$.destroy(w),J.error(Error("upstream sent malformed chunk size"));return}if(B===0){for(;;)if(await X()==="")break;_2($,w,Y),J.close();return}A=B}},cancel(){$.destroy(w)}})}function mN($,w,Y,A,U,X,J){let W=`${$} ${w} HTTP/1.1\r
|
|
208
|
+
host: ${A}\r
|
|
209
|
+
x-forwarded-for: 127.0.0.1\r
|
|
210
|
+
x-forwarded-proto: https\r
|
|
211
|
+
x-forwarded-host: ${U}\r
|
|
212
|
+
`;if(X!==void 0)W+=`origin: ${X}\r
|
|
213
|
+
`;let f=!1;for(let[B,j]of Y){let z=B.toLowerCase();if(DN.has(z))continue;if(X!==void 0&&z==="origin")continue;if(z==="content-length")f=!0;W+=`${B}: ${j}\r
|
|
214
|
+
`}if(W+=`connection: keep-alive\r
|
|
215
|
+
`,J&&!f)W+=`content-length: ${J.length}\r
|
|
216
|
+
`;return W+=`\r
|
|
217
|
+
`,kN.encode(W)}async function dN($){let w=$.getReader(),Y=[],A=0;for(;;){let{done:J,value:W}=await w.read();if(J)break;if(W){if(A+=W.length,A>h2)return w.cancel().catch(()=>{}),null;Y.push(W)}}if(Y.length===1)return Y[0];let U=new Uint8Array(A),X=0;for(let J of Y)U.set(J,X),X+=J.length;return U}var qN,HY,AX,RN,uf,kw,h2=1048576,bf=30000,LN=16384,V2=262144,QN=2097152,ON=524288,SN=8192,_N=4096,kN,L2,DN,y2;var k2=j0(()=>{({connect:qN}=Bun),HY=Symbol("rpx.pool.fallback"),AX=Symbol("rpx.pool.stale"),RN=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);uf=Symbol("rpx.pool.timeout"),kw=Symbol("rpx.pool.busy");kN=new TextEncoder,L2=new TextDecoder,DN=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);y2=new Map});import*as B$ from"node:path";function NY($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function lN($){let w=B$.extname($).toLowerCase();return gN[w]??"application/octet-stream"}function nN($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let Y=B$.posix.normalize(`/${w}`);if(Y.includes(".."))return null;return Y.replace(/^\/+/,"")}function pN($,w){let Y=nN($);if(Y===null)return null;let A=B$.posix.extname(Y);if(w.cleanUrls&&A===".html"){let U=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:B$.join(w.dir,Y),redirectTo:U||"/"}}if(Y===""||$.endsWith("/"))return{filePath:B$.join(w.dir,Y,"index.html")};if(A!=="")return{filePath:B$.join(w.dir,Y)};if(w.pathRewriteStyle==="flat")return{filePath:B$.join(w.dir,`${Y}.html`)};return{filePath:B$.join(w.dir,Y,"index.html")}}async function D2($,w){let Y=pN($,w);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",U=Bun.file(Y.filePath);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":lN(Y.filePath),"Cache-Control":A}});if(w.spa){let X=B$.join(w.dir,"index.html"),J=Bun.file(X);if(await J.exists())return new Response(J,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var gN;var qY=j0(()=>{gN={".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 rN($){let w=$.headers.get("host")||"",Y=w.indexOf(":");return Y===-1?w:w.slice(0,Y)}function x2($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let Y=$.slice(w.length);return Y===""?"/":Y}return $}function Z2($,w,Y){let A=w.sourceHost??"",X=w.stripBasePathPrefix??!1?x2($,w.basePath):$,J=Vf(X,w.pathRewrites);if(J)A=J.targetHost,X=J.targetPath,E("request",`Path rewrite: ${$} → ${A}${X}`,Y);return{targetHost:A,targetPath:X}}function aN($){let w=$.indexOf("://"),Y=w===-1?$.indexOf("/"):$.indexOf("/",w+3);if(Y===-1)return{pathname:"/",search:""};let A=$.indexOf("?",Y);if(A===-1)return{pathname:$.slice(Y),search:""};return{pathname:$.slice(Y,A),search:$.slice(A)}}function S1($,w){let Y=async(A,U)=>{let{pathname:X,search:J}=aN(A.url),W=rN(A),f=$(W,X);if(!f)return E("request",`No route found for host: ${W}`,w),new Response(`No proxy configured for ${W}`,{status:404});if(f.static){let T=f.stripBasePathPrefix??!0?x2(X,f.basePath):X;return D2(T,f.static)}if(A.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!U||!f.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:F,targetPath:T}=Z2(X,f,w),K=`ws://${F}${T}${J}`,H={};for(let[I,h]of A.headers)if(!tN.has(I.toLowerCase())&&I.toLowerCase()!=="host")H[I]=h;H.host=F,H["x-forwarded-for"]="127.0.0.1",H["x-forwarded-proto"]="https",H["x-forwarded-host"]=W;let q={targetUrl:K,forwardHeaders:H};if(U.upgrade(A,{data:q})){E("ws",`upgraded ${W}${T} → ${K}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!f.sourceHost)return new Response(`No upstream configured for ${W}`,{status:502});if(f.cleanUrls&&X.endsWith(".html")){let F=X.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:F}})}let{targetHost:B,targetPath:j}=Z2(X,f,w),z=f.changeOrigin?`http://${f.sourceHost}`:void 0,G=A.body!=null&&A.method!=="GET"&&A.method!=="HEAD";try{return await S2({hostPort:B,method:A.method,path:`${j}${J}`,reqHeaders:A.headers,forwardedHost:W,originOverride:z,body:A.body})}catch(F){if(F===uf)return E("request",`Upstream timeout for ${W}`,w),new Response("Gateway Timeout",{status:504});if(F===kw)return E("request",`Upstream pool saturated for ${W}`,w),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(F===HY||!G)try{let T=new Headers(A.headers);if(T.set("host",B),T.set("x-forwarded-for","127.0.0.1"),T.set("x-forwarded-proto","https"),T.set("x-forwarded-host",W),z!==void 0)T.set("origin",z);return await fetch(`http://${B}${j}${J}`,{method:A.method,headers:T,body:A.body,redirect:"manual"})}catch(T){return E("request",`Proxy error for ${W}: ${T}`,w),new Response(`Proxy Error: ${T}`,{status:502})}return E("request",`Proxy error for ${W}: ${F}`,w),new Response(`Proxy Error: ${F}`,{status:502})}};return async(A,U)=>{try{return await Y(A,U)}catch(X){return E("request",`Unhandled proxy handler error: ${X}`,w),new Response("Bad Gateway",{status:502})}}}function _1($){let w=new WeakMap;return{open(Y){let{targetUrl:A,forwardHeaders:U}=Y.data,X;try{X=new WebSocket(A,{headers:U})}catch(W){E("ws",`failed to open upstream ${A}: ${W}`,$),Y.close(1011,"upstream connect failed");return}X.binaryType="arraybuffer";let J={upstream:X,upstreamOpen:!1,pending:[]};w.set(Y,J),X.addEventListener("open",()=>{J.upstreamOpen=!0;for(let W of J.pending)X.send(W);J.pending=[]}),X.addEventListener("message",(W)=>{Y.send(W.data)}),X.addEventListener("close",(W)=>{try{Y.close(W.code||1000,W.reason||"")}catch{}}),X.addEventListener("error",()=>{E("ws",`upstream error for ${A}`,$);try{Y.close(1011,"upstream error")}catch{}})},message(Y,A){let U=w.get(Y);if(!U)return;let X=typeof A==="string"?A:new Uint8Array(A);if(U.upstreamOpen)U.upstream.send(X);else U.pending.push(X)},close(Y,A,U){let X=w.get(Y);if(!X)return;w.delete(Y);try{X.upstream.close(A||1000,U||"")}catch{}}}}var tN;var UX=j0(()=>{k2();qY();f0();tN=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function RY($){return $.startsWith("*.")}function XX($,w){if(!RY(w))return!1;let Y=w.slice(1);return $.length>Y.length&&$.endsWith(Y)}function k1($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function oN($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function D1($){let w=new Map;for(let A of $){let U=k1(A.path),X=w.get(A.host);if(!X)X=new Map,w.set(A.host,X);X.set(U,A.route)}let Y=new Map;for(let[A,U]of w){let X=[];for(let[J,W]of U)X.push({path:J,route:W});X.sort((J,W)=>W.path.length-J.path.length),Y.set(A,X)}return Y}function eN($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,U=-1;for(let[X,J]of $){if(!RY(X))continue;if(XX(w,X)){let W=X.length-1;if(W>U)U=W,A=J}}return A}function Z1($,w,Y){let A=eN($,w);if(!A)return;for(let U of A)if(oN(Y,U.path))return U.route;return}var JX=()=>{};import*as MY from"node:fs/promises";import*as cf from"node:path";function $q($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function wq($,w,Y,A){try{let[U,X]=await Promise.all([MY.readFile(w,"utf8"),MY.readFile(Y,"utf8")]);return{serverName:$,cert:U,key:X}}catch(U){return E("sni",`skipping ${$}: ${U.message}`,A),null}}async function x1($,w){let Y=new Map;if($.certsDir){let U=[];try{U=await MY.readdir($.certsDir)}catch(X){E("sni",`certsDir read failed (${$.certsDir}): ${X.message}`,w)}for(let X of U){let J=$q(X);if(!J)continue;let W=X.slice(0,-4);Y.set(J,{certPath:cf.join($.certsDir,X),keyPath:cf.join($.certsDir,`${W}.key`)})}}if($.domains)for(let[U,X]of Object.entries($.domains))Y.set(U,X);let A=[];for(let[U,X]of Y){let J=await wq(U,X.certPath,X.keyPath,w);if(J)A.push(J)}return A}var fX=j0(()=>{f0()});import*as Tw from"node:fs/promises";import*as vf from"node:path";function Aq($,w){if(!w||w.length===0)return!1;return w.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return $===A||$.endsWith(`.${A}`)})}function b2($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class IY{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??WU,this.issuer=$.issuer??HJ,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??Yq;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!b2($))return!1;if(Aq($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return E("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;if(!b2($))return!1;let w=this.inFlight.get($);if(w)return w;let Y=this.negativeCache.get($);if(Y!==void 0&&Date.now()<Y)return E("on-demand",`${$} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1;let A=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,A),A}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return E("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),this.cacheNegative($),!1;try{E("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let Y={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,Y),this.negativeCache.delete($),E("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.cacheNegative($),E("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}cacheNegative($){if(this.negativeCache.size>=P2){let w=Date.now();for(let[Y,A]of this.negativeCache)if(A<=w)this.negativeCache.delete(Y);if(this.negativeCache.size>=P2){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set($,Date.now()+this.negativeCacheMs)}async loadFromDisk($){let{certPath:w,keyPath:Y}=this.pathsFor($);try{let[A,U]=await Promise.all([Tw.readFile(w,"utf8"),Tw.readFile(Y,"utf8")]),X={serverName:$,cert:A,key:U};return this.certs.set($,X),E("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:vf.join(this.certsDir,`${$}.crt`),keyPath:vf.join(this.certsDir,`${$}.key`)}}async persist($,w,Y){await Tw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:U}=this.pathsFor($);await Promise.all([Tw.writeFile(A,w,"utf8"),Tw.writeFile(U,Y,{encoding:"utf8",mode:384})])}}var Yq=60000,P2=4096;var mf=j0(()=>{TU();f0()});import*as WX from"node:fs";import*as g0 from"node:fs/promises";import{homedir as Uq}from"node:os";import*as df from"node:path";import*as BX from"node:process";function Hw(){return df.join(Uq(),".stacks","rpx","registry.d")}function yY($){return typeof $==="string"&&$.length>0&&$.length<=128&&Xq.test($)}function gf($,w){if(!yY(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return df.join($,`${w}.json`)}function p0($){if(!Number.isInteger($)||$<=0)return!1;try{return BX.kill($,0),!0}catch(w){return w.code==="EPERM"}}function u2($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0,U=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&yY(w.id)&&(A||U)&&typeof w.to==="string"&&w.to.length>0&&X&&Y&&typeof w.createdAt==="string"}async function Jq($){await g0.mkdir($,{recursive:!0})}async function i2($,w=Hw(),Y){if(!u2($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await Jq(w);let A=gf(w,$.id),U=`${A}.tmp.${BX.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await g0.writeFile(U,X,{encoding:"utf8",mode:420}),await g0.rename(U,A),E("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(J){throw await g0.unlink(U).catch(()=>{}),J}}async function lf($,w=Hw(),Y){let A=gf(w,$);try{await g0.unlink(A),E("registry",`removed entry ${$}`,Y)}catch(U){if(U.code!=="ENOENT")throw U}}async function fq($,w=Hw(),Y){let A=gf(w,$);try{let U=await g0.readFile(A,"utf8"),X=JSON.parse(U);if(!u2(X))return E("registry",`entry ${$} failed validation, removing`,Y),await g0.unlink(A).catch(()=>{}),null;return X}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return E("registry",`entry ${$} has invalid JSON, removing`,Y),await g0.unlink(A).catch(()=>{}),null;throw U}}async function s$($=Hw(),w){let Y;try{Y=await g0.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let A=[];for(let U of Y){if(!U.endsWith(".json"))continue;let X=U.slice(0,-5);if(!yY(X))continue;let J=await fq(X,$,w);if(J)A.push(J)}return A}async function P1($=Hw(),w){let Y=await s$($,w),A=0;for(let U of Y){if(U.pid===void 0)continue;if(!p0(U.pid))E("registry",`GC: pid ${U.pid} for ${U.id} is dead, removing`,w),await lf(U.id,$,w).catch(()=>{}),A++}return A}function CY($,w={}){let Y=w.dir??Hw(),A=w.debounceMs??100,U=w.pollMs??Math.max(A*2,250),X=w.verbose;WX.mkdirSync(Y,{recursive:!0});let J=null,W=!1,f=null,B=!1,j=(H)=>{return JSON.stringify(H.map((q)=>({id:q.id,from:q.from,to:q.to,path:q.path,pid:q.pid,pathRewrites:q.pathRewrites,cleanUrls:q.cleanUrls,changeOrigin:q.changeOrigin,static:q.static})).sort((q,M)=>q.id.localeCompare(M.id)))},z=()=>{if(J=null,W)return;s$(Y,X).then((H)=>{return f=j(H),$(H)}).catch((H)=>{E("registry",`watcher onChange failed: ${H}`,X)})},G=()=>{if(W)return;if(J)clearTimeout(J);J=setTimeout(z,A)},T=setInterval(()=>{if(W||B)return;B=!0,s$(Y,X).then((H)=>{if(j(H)!==f)G()}).catch((H)=>{E("registry",`watcher poll failed: ${H}`,X)}).finally(()=>{B=!1})},U),K=WX.watch(Y,{persistent:!0},(H,q)=>{if(q&&/\.tmp\.\d+\.\d+$/.test(q))return;G()});return K.on("error",(H)=>{E("registry",`watcher error: ${H}`,X)}),G(),{close:()=>{if(W=!0,J)clearTimeout(J);clearInterval(T),K.close()}}}var Xq;var hY=j0(()=>{f0();Xq=/^[a-zA-Z0-9._-]+$/});import{spawn as Wq}from"node:child_process";import*as o$ from"node:fs/promises";import{homedir as Bq}from"node:os";import*as VY from"node:path";import*as h0 from"node:process";function e$(){return VY.join(Bq(),".stacks","rpx")}function v2($=e$()){return VY.join($,"daemon.pid")}async function c2($=e$()){try{let w=await o$.readFile(v2($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function jq($=e$()){await o$.unlink(v2($)).catch(()=>{})}function zq(){let $=h0.execPath,w=VY.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&h0.argv[1])return[$,h0.argv[1],"daemon:start"];return[$,"daemon:start"]}async function m2($={}){let w=$.rpxDir??e$(),Y=$.verbose??!1;await $w({rpxDir:w,verbose:Y}).catch((j)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,Y)});let A=await c2(w);if(A!==null&&p0(A))return E("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)E("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await jq(w);await o$.mkdir(w,{recursive:!0});let U=$.spawnCommand??zq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${U.join(" ")}`,Y);let X=Wq(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??h0.cwd(),env:$.spawnEnv?{...h0.env,...$.spawnEnv}:h0.env});X.unref();let J=null;X.once("error",(j)=>{J=j});let W=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(J)throw J;let j=await c2(w);if(j!==null&&p0(j))return E("daemon",`daemon registered with pid=${j}`,Y),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,f))}if(J)throw J;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var nf=j0(()=>{fw();YX();UX();JX();fX();mf();qY();hY();b1();f0()});import*as qw from"node:fs/promises";import{homedir as Fq}from"node:os";import*as pf from"node:path";function g2(){return pf.join(Fq(),".stacks","rpx")}function tf($=g2()){return pf.join($,Gq)}async function zX($=g2()){try{let w=await qw.readFile(tf($),"utf8"),Y=JSON.parse(w);if(Y.version!==jX||!Array.isArray(Y.resolvers))return null;return{version:jX,resolvers:Y.resolvers.filter((A)=>typeof A==="string"),domains:Array.isArray(Y.domains)?Y.domains.filter((A)=>typeof A==="string"):[],ownerPid:typeof Y.ownerPid==="number"?Y.ownerPid:null,updatedAt:typeof Y.updatedAt==="string"?Y.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function l2($,w){await qw.mkdir($,{recursive:!0}),await qw.writeFile(tf($),`${JSON.stringify(w,null,2)}
|
|
218
|
+
`,"utf8")}async function rf($){await qw.rm(tf($),{force:!0})}function n2($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;if(!/^[a-z0-9.-]+$/.test(w))return null;return w}function Eq($){let w=n2($);if(!w)return null;let Y=w.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function af($){let w=new Set;for(let Y of $){let A=Eq(Y);if(A)w.add(A)}return Array.from(w).sort()}function sf($){let w=new Set;for(let Y of $){let A=n2(Y);if(A)w.add(A)}return Array.from(w).sort()}var jX=1,Gq="dns-state.json",d2;var p2=j0(()=>{d2=["com","test","dev","app","page","local","localhost","example","invalid"]});var GX={};RW(GX,{tearDownDevelopmentDns:()=>Nw,syncDevelopmentDnsFromRegistry:()=>Dw,stopDnsServer:()=>of,startDnsServer:()=>wF,setupResolver:()=>Cq,setupDevelopmentDns:()=>YW,resolverFilePath:()=>u1,removeResolver:()=>Vq,removeLegacyTldResolvers:()=>wW,reconcileStaleDevelopmentDns:()=>$w,isRpxDevelopmentDnsAnswering:()=>YF,isDnsServerRunning:()=>Nq,contentLooksLikeRpxResolver:()=>AF,RPX_RESOLVER_MARKER:()=>s2,DNS_PORT:()=>QY});import t2 from"node:dgram";import*as r2 from"node:fs/promises";import*as a2 from"node:path";import*as ww from"node:process";function e2($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function $F($,w,Y=0){let A=[],U=w,X=0;while(!0){if(U>=$.length||++X>128)break;let J=$[U];if(J===0){U++;break}if((J&192)===192){if(U+1>=$.length||Y>=10)break;let W=$.readUInt16BE(U)&16383,{name:f}=$F($,W,Y+1);if(f)A.push(f);U+=2;break}if(U++,U+J>$.length)break;A.push($.subarray(U,U+J).toString("ascii")),U+=J}return{name:A.join("."),newOffset:U}}function Kq($,w){let{name:Y,newOffset:A}=$F($,w),U=$.readUInt16BE(A),X=$.readUInt16BE(A+2);return{question:{name:Y,type:U,class:X},newOffset:A+4}}function LY($){let w=$.split("."),Y=[];for(let A of w)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function Tq($,w,Y){let A=[],U=Buffer.alloc(12);U.writeUInt16BE($,0),U.writeUInt16BE(33152,2),U.writeUInt16BE(1,4),U.writeUInt16BE(1,6),U.writeUInt16BE(0,8),U.writeUInt16BE(0,10),A.push(U),A.push(LY(w.name));let X=Buffer.alloc(4);X.writeUInt16BE(w.type,0),X.writeUInt16BE(w.class,2),A.push(X),A.push(LY(w.name));let J=Buffer.alloc(10);if(J.writeUInt16BE(w.type,0),J.writeUInt16BE(1,2),J.writeUInt32BE(300,4),w.type===1){J.writeUInt16BE(4,8),A.push(J);let W=Y.split(".").map((f)=>Number.parseInt(f,10));A.push(Buffer.from(W))}else if(w.type===28)J.writeUInt16BE(16,8),A.push(J),A.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return U.writeUInt16BE(33155,2),U.writeUInt16BE(0,6),Buffer.concat([U,LY(w.name),X]);return Buffer.concat(A)}function Hq($,w){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE($,0),A.writeUInt16BE(33155,2),A.writeUInt16BE(1,4),A.writeUInt16BE(0,6),A.writeUInt16BE(0,8),A.writeUInt16BE(0,10),Y.push(A),Y.push(LY(w.name));let U=Buffer.alloc(4);return U.writeUInt16BE(w.type,0),U.writeUInt16BE(w.class,2),Y.push(U),Buffer.concat(Y)}async function wF($,w){if(ww.platform!=="darwin")return!1;let Y=sf($);if(Y.length===0)return!1;if(t0){for(let A of Y)FX.add(A);return E("dns","DNS server already running — merged domains",w),!0}return FX=new Set(Y),new Promise((A)=>{t0=t2.createSocket("udp4"),t0.on("error",(U)=>{E("dns",`DNS server error: ${U.message}`,w),t0?.close(),t0=null,A(!1)}),t0.on("message",(U,X)=>{try{let J=e2(U),{question:W}=Kq(U,12);E("dns",`Query for ${W.name} type ${W.type} from ${X.address}`,w);let f=W.name.toLowerCase(),B=!1;for(let z of FX)if(f===z||f.endsWith(`.${z}`)){B=!0;break}let j;if(B&&(W.type===1||W.type===28))j=Tq(J.id,W,"127.0.0.1"),E("dns",`Responding with localhost for ${W.name}`,w);else j=Hq(J.id,W),E("dns",`NXDOMAIN for ${W.name}`,w);t0?.send(j,X.port,X.address)}catch(J){E("dns",`Error processing DNS query: ${J}`,w)}}),t0.on("listening",()=>{let U=t0?.address();E("dns",`DNS server listening on ${U?.address}:${U?.port}`,w),A(!0)});try{t0.bind(QY,"127.0.0.1")}catch(U){E("dns",`Failed to bind DNS server: ${U}`,w),A(!1)}})}function of($){if(t0)E("dns","Stopping DNS server",$),t0.close(),t0=null,FX=new Set}function Nq(){return t0!==null}async function YF($,w=500){let Y=$.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let U=t2.createSocket("udp4"),X=setTimeout(()=>{U.close(),A(!1)},w);U.on("message",(W)=>{clearTimeout(X),U.close();try{let f=e2(W);A(f.ancount>0)}catch{A(!1)}}),U.on("error",()=>{clearTimeout(X),U.close(),A(!1)});let J=qq(Y,1);U.send(J,QY,"127.0.0.1",(W)=>{if(W)clearTimeout(X),U.close(),A(!1)})})}function qq($,w){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([LY($),Buffer.from([0,w,0,1])]);return Buffer.concat([Y,A])}function Rq(){return`${s2}
|
|
205
219
|
nameserver 127.0.0.1
|
|
206
|
-
port ${
|
|
207
|
-
`}function
|
|
220
|
+
port ${QY}
|
|
221
|
+
`}function u1($){return a2.join(o2,$)}function AF($){return $.includes("127.0.0.1")&&$.includes(String(QY))}async function Mq($){try{return await r2.readFile(u1($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function ef($){if(ww.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),h1));if(!A()&&!Y()){E("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),E("dns","DNS cache flushed",$)}catch(U){E("dns",`Could not flush DNS cache: ${U}`,$)}}function UF($){if(!/^[a-z0-9.-]+$/.test($))throw Error(`refusing unsafe resolver basename: ${JSON.stringify($)}`)}async function Iq($,w){UF($);let{execSudoSync:Y}=await Promise.resolve().then(() => (f0(),h1)),A=Rq().replace(/\n/g,"\\n"),U=`bash -c 'mkdir -p ${o2} && printf "%b" "${A}" > ${u1($)}'`;Y(U),E("dns",`Created ${u1($)}`,w)}async function yq($,w){UF($);let{execSudoSync:Y}=await Promise.resolve().then(() => (f0(),h1));Y(`rm -f ${u1($)}`),E("dns",`Removed ${u1($)}`,w)}async function Cq($,w){return YW({domains:w??[],verbose:$})}async function hq($,w){if(ww.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),h1));if(!A()&&!Y())return E("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let U of $)await Iq(U,w);return await ef(w),!0}catch(U){return E("dns",`Failed to create resolver file: ${U}`,w),!1}}async function $W($,w){if(ww.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),h1));if(!A()&&!Y())return;try{for(let U of $)await yq(U,w);await ef(w)}catch(U){E("dns",`Failed to remove resolver files: ${U}`,w)}}async function wW($){if(ww.platform!=="darwin")return[];let w=[];for(let Y of d2){let A=await Mq(Y);if(A&&AF(A))await $W([Y],$),w.push(Y)}return w}async function YW($){let w=$.rpxDir??e$(),Y=sf($.domains);if(Y.length===0)return!1;let A=af(Y),U=await wF(Y,$.verbose);if(!U){let W=Y[0];if(W&&await YF(W))U=!0;else E("dns","Dev DNS server not available on 127.0.0.1:15353",$.verbose)}if(!U)return!1;if(!await hq(A,$.verbose))return!1;let J={version:jX,resolvers:A,domains:Y,ownerPid:$.ownerPid??ww.pid,updatedAt:new Date().toISOString()};return await l2(w,J),!0}async function Dw($,w={}){let Y=$.map((f)=>f.to).filter(Boolean),A=w.rpxDir??e$(),U=af(Y),W=((await zX(A))?.resolvers??[]).filter((f)=>!U.includes(f));if(W.length>0)await $W(W,w.verbose);if(U.length===0){of(w.verbose),await rf(A);return}await YW({domains:Y,rpxDir:A,verbose:w.verbose,ownerPid:w.ownerPid??ww.pid})}async function Nw($={}){let w=$.rpxDir??e$();of($.verbose);let A=(await zX(w))?.resolvers??[];await $W(A,$.verbose),await wW($.verbose),await rf(w)}async function Vq($){await Nw({verbose:$})}async function $w($={}){let w=$.rpxDir??e$(),Y=await zX(w),A=Y?.ownerPid!=null&&p0(Y.ownerPid);if(Y&&!A){E("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,$.verbose),await Nw($);return}let U=await wW($.verbose);if(U.length>0)E("dns",`reconcile: removed legacy TLD resolvers: ${U.join(", ")}`,$.verbose);await ef($.verbose)}var QY=15353,s2="# managed-by: rpx",o2="/etc/resolver",t0=null,FX;var b1=j0(()=>{nf();p2();hY();f0();FX=new Set});import{dirname as wR,join as YR}from"path";import*as n0 from"process";import{fileURLToPath as AR}from"url";import{existsSync as gF}from"node:fs";import OX from"node:fs/promises";import MW from"node:os";import SX from"node:path";import yw from"node:process";import{EventEmitter as lF}from"node:events";import Aw from"node:process";import IW from"node:process";import ZX from"node:process";import bY from"node:process";import t1 from"node:process";import hW from"node:tty";import k5,{stdin as yR,stdout as CR}from"node:process";import LW,{stdin as x5,stdout as P5}from"node:process";import b5 from"node:readline";class OW{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=MW.homedir(),w=SX.join($,".config","clapp");this.configPath=SX.join(w,"telemetry.json")}async isEnabled(){if(yw.env.DO_NOT_TRACK==="1"||yw.env.DO_NOT_TRACK==="true")return!1;if(yw.env.NO_TELEMETRY==="1"||yw.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let A={event:$,...w,timestamp:Date.now(),platform:MW.platform(),nodeVersion:yw.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:yw.env.DO_NOT_TRACK==="1"||yw.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(gF(this.configPath)){let $=await OX.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=SX.dirname(this.configPath);await OX.mkdir(w,{recursive:!0}),await OX.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var zR=new OW;function nF($,w={}){let Y={_:[]},A=w.alias||{},U=new Set(w.boolean||[]),X={};for(let W of Object.keys(A))for(let f of A[W])X[f]=W;for(let W of U)if(A[W])for(let f of A[W])U.add(f);function J(W,f){let B=X[W]||W;if(Y[B]=f,A[B])for(let j of A[B])Y[j]=f;if(X[W]&&A[X[W]])for(let j of A[X[W]])Y[j]=f;Y[W]=f}for(let W=0;W<$.length;W++){let f=$[W];if(f==="--"){Y._.push(...$.slice(W+1));break}if(f.startsWith("--")){let B=f.indexOf("=");if(B!==-1){let j=f.slice(2,B),z=f.slice(B+1);J(j,z)}else{let j=f.slice(2);if(j.startsWith("no-")){let G=j.slice(3);J(G,!1);continue}let z=X[j]||j;if(U.has(z)||U.has(j))J(j,!0);else{let G=$[W+1];if(G!==void 0&&!G.startsWith("-"))J(j,G),W++;else J(j,!0)}}}else if(f.startsWith("-")&&f.length>1){let B=f.slice(1);for(let j=0;j<B.length;j++){let z=B[j],G=X[z]||z;if(j===B.length-1&&!U.has(G)&&!U.has(z)){let F=$[W+1];if(F!==void 0&&!F.startsWith("-"))J(z,F),W++;else J(z,!0)}else J(z,!0)}}else Y._.push(f)}return Y}function DX($){return $.replace(/[<[].+/,"").trim()}function pF($){let w=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],U=(W)=>{let f=!1,B=W[1];if(B.startsWith("..."))B=B.slice(3),f=!0;return{required:W[0].startsWith("<"),value:B,variadic:f}},X;while(X=w.exec($))A.push(U(X));let J;while(J=Y.exec($))A.push(U(J));return A}function tF($){let w={alias:{},boolean:[]};for(let[Y,A]of $.entries()){if(A.names.length>1)w.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!$.some((X,J)=>{return J!==Y&&X.names.some((W)=>A.names.includes(W))&&typeof X.required==="boolean"}))w.boolean.push(A.names[0])}else w.boolean.push(A.names[0])}return w}function yW($){return $.reduce((w,Y)=>w.length>=Y.length?w:Y,"")}function _X($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function rF($){return $.replace(/([a-z])-([a-z])/g,(w,Y,A)=>{return Y+A.toUpperCase()})}function aF($,w,Y){let A=0,U=w.length,X=$,J;for(;A<U;++A)J=X[w[A]],X=X[w[A]]=A===U-1?Y:J!=null?J:!!~w[A+1].indexOf(".")||!(+w[A+1]>-1)?{}:[]}function sF($,w){for(let Y of Object.keys(w)){let A=w[Y];if(A.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof A.transformFunction==="function")$[Y]=$[Y].map(A.transformFunction)}}}function oF($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function SW($){return $.split(".").map((w,Y)=>{return Y===0?rF(w):w}).join(".")}class PY extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
|
|
208
222
|
|
|
209
223
|
Stack trace:
|
|
210
|
-
${this.stack}`;return this.message}}function
|
|
211
|
-
`);let
|
|
224
|
+
${this.stack}`;return this.message}}function eF(){let{env:$}=IW,{TERM:w,TERM_PROGRAM:Y}=$;if(IW.platform!=="win32")return w!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||w==="xterm-256color"||w==="alacritty"||w==="rxvt-unicode"||w==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var cY="\x1B",W0=`${cY}[`;var Q$={to($,w){if(!w)return`${W0}${$+1}G`;return`${W0}${w+1};${$+1}H`},move($,w){let Y="";if($<0)Y+=`${W0}${-$}D`;else if($>0)Y+=`${W0}${$}C`;if(w<0)Y+=`${W0}${-w}A`;else if(w>0)Y+=`${W0}${w}B`;return Y},up:($=1)=>`${W0}${$}A`,down:($=1)=>`${W0}${$}B`,forward:($=1)=>`${W0}${$}C`,backward:($=1)=>`${W0}${$}D`,nextLine:($=1)=>`${W0}E`.repeat($),prevLine:($=1)=>`${W0}F`.repeat($),left:`${W0}G`,hide:`${W0}?25l`,show:`${W0}?25h`,save:`${cY}7`,restore:`${cY}8`};var kX={screen:`${W0}2J`,up:($=1)=>`${W0}1J`.repeat($),down:($=1)=>`${W0}J`.repeat($),line:`${W0}2K`,lineEnd:`${W0}K`,lineStart:`${W0}1K`,lines($){let w="";for(let Y=0;Y<$;Y++)w+=this.line+(Y<$-1?Q$.up():"");if($)w+=Q$.left;return w}},KR={screen:`${cY}c`};function $5($,w){let Y=[];for(let A=0;A<=w.length;A++)Y[A]=[A];for(let A=0;A<=$.length;A++)Y[0][A]=A;for(let A=1;A<=w.length;A++)for(let U=1;U<=$.length;U++)if(w.charAt(A-1)===$.charAt(U-1))Y[A][U]=Y[A-1][U-1];else Y[A][U]=Math.min(Y[A-1][U-1]+1,Y[A][U-1]+1,Y[A-1][U]+1);return Y[w.length][$.length]}function _W($,w,Y=2,A=3){return w.map((U)=>({cmd:U,distance:$5($,U)})).filter(({distance:U})=>U<=Y).sort((U,X)=>U.distance-X.distance).slice(0,A).map(({cmd:U})=>U)}class kW{rawName;description;name;names;isBoolean;required;config;negated;constructor($,w,Y){if(this.rawName=$,this.description=w,this.config=Object.assign({},Y),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=DX($).split(",").map((A)=>{let U=A.trim().replace(/^-{1,2}/,"");if(U.startsWith("no-"))this.negated=!0,U=U.replace(/^no-/,"");return SW(U)}).sort((A,U)=>A.length>U.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var HR=ZX.argv,w5=`${ZX.platform}-${ZX.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,CW=bY.argv,Y5=`${bY.platform}-${bY.arch} node-${bY.version}`;class xX{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,Y,A){this.rawName=$,this.description=w,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=DX($);let U=DX($),X=U.indexOf(":");if(X>0)this.namespace=U.substring(0,X),this.name=U.substring(X+1);if(this.args=pF($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,Y){let A=new kW($,w,Y);return this.options.push(A),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof PX}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){return $=$.split(".")[0],!!this.options.find((w)=>{return w.names.includes($)})}outputHelp(){let{name:$,commands:w}=this.cli,{versionNumber:Y,options:A,helpCallback:U}=this.cli.globalCommand,X=[{body:`${$}${Y?`/${Y}`:""}`}];if(X.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let f=yW(w.map((F)=>F.rawName)),B=new Map,j=[];for(let F of w)if(F.namespace){if(!B.has(F.namespace))B.set(F.namespace,[]);B.get(F.namespace).push(F)}else j.push(F);let z="";if(j.length>0)z+=j.map((F)=>{return` ${_X(F.rawName,f.length)} ${F.description}`}).join(`
|
|
225
|
+
`);let G=Array.from(B.keys()).sort();for(let F of G){let T=B.get(F);if(z.length>0)z+=`
|
|
212
226
|
|
|
213
|
-
`;
|
|
214
|
-
`,
|
|
215
|
-
`)}X.push({title:"Commands",body:
|
|
216
|
-
`)})}let W=this.isGlobalCommand?
|
|
217
|
-
`)})}if(this.examples.length>0)X.push({title:"Examples",body:this.examples.map((
|
|
218
|
-
`)});if(
|
|
219
|
-
${
|
|
227
|
+
`;z+=` ${F}:
|
|
228
|
+
`,z+=T.map((K)=>{return` ${_X(K.rawName,f.length-2)} ${K.description}`}).join(`
|
|
229
|
+
`)}X.push({title:"Commands",body:z}),X.push({title:"For more info, run any command with the `--help` flag",body:w.map((F)=>` $ ${$}${F.displayName===""?"":` ${F.displayName}`} --help`).join(`
|
|
230
|
+
`)})}let W=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)W=W.filter((f)=>f.name!=="version");if(W.length>0){let f=yW(W.map((B)=>B.rawName));X.push({title:"Options",body:W.map((B)=>{return` ${_X(B.rawName,f.length)} ${B.description} ${B.config.default===void 0?"":`(default: ${B.config.default})`}`}).join(`
|
|
231
|
+
`)})}if(this.examples.length>0)X.push({title:"Examples",body:this.examples.map((f)=>{if(typeof f==="function")return f($);return f}).join(`
|
|
232
|
+
`)});if(U)X=U(X)||X;console.log(X.map((f)=>{return f.title?`${f.title}:
|
|
233
|
+
${f.body}`:f.body}).join(`
|
|
220
234
|
|
|
221
|
-
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?
|
|
235
|
+
`))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?w5:Y5}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let Y=this.args.filter((U)=>U.required).slice(this.cli.args.length),A=Y.map((U)=>`<${U.value}>`).join(" ");throw new PY(`Missing required argument${Y.length>1?"s":""}: ${A}
|
|
222
236
|
|
|
223
|
-
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let
|
|
237
|
+
Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys($))if(Y!=="--"&&!this.hasOption(Y)&&!w.hasOption(Y)){let U=[...w.options,...this.options].flatMap((f)=>f.names),X=Y.length>1?`--${Y}`:`-${Y}`,J=_W(Y,U),W=`Unknown option \`${X}\``;if(J.length>0)W+=`
|
|
224
238
|
|
|
225
|
-
Did you mean one of these?`,
|
|
239
|
+
Did you mean one of these?`,J.forEach((f)=>{let B=f.length>1?`--${f}`:`-${f}`;W+=`
|
|
226
240
|
• ${B}`});throw W+=`
|
|
227
241
|
|
|
228
|
-
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new
|
|
242
|
+
Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new PY(W)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,Y=[...w.options,...this.options];for(let A of Y){let U=$[A.name.split(".")[0]];if(A.required){let X=Y.some((J)=>J.negated&&J.names.includes(A.name));if(U===!0||U===!1&&!X)throw new PY(`Option \`${A.rawName}\` requires a value.
|
|
229
243
|
|
|
230
|
-
Example: ${this.cli.name} ${this.rawName} ${
|
|
244
|
+
Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class PX extends xX{constructor($){super("@@global@@","",{},$)}}var A5=xX,Uw={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var n1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function U5(){return!0}function X5(){let $={};$.supportsColor=U5();function w(A,U=[]){let X=A===""?[]:[...U,A],J=function(f){if(!$.supportsColor)return f;let B="",j="";for(let z of X)if(z in n1&&n1[z]in Uw){let G=n1[z];B+=Uw[G][0],j=Uw[G][1]+j}else if(z in Uw)B+=Uw[z][0],j=Uw[z][1]+j;return B+f+j},W=[...Object.keys(Uw),...Object.keys(n1)];for(let f of W)if(!(f in J))Object.defineProperty(J,f,{get(){return w(f,X)}});return J}let Y=[...Object.keys(Uw),...Object.keys(n1)];for(let A of Y)if(!(A in $))Object.defineProperty($,A,{get(){return w(A)}});return $}var p1=X5();class bX extends lF{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new PX(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(Y)=>{if(console.log(`
|
|
231
245
|
|
|
232
|
-
Received ${
|
|
246
|
+
Received ${Y}, cleaning up...`),$)try{await $()}catch(A){console.error("Error during cleanup:",A)}Aw.exit(0)};return Aw.on("SIGINT",()=>w("SIGINT")),Aw.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,Y){if(!Y)Y={};let A=new A5($,w||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option($,w,Y){return this.globalCommand.option($,w,Y),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,w="-v, --version"){return this.globalCommand.version($,w),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:w},Y,A){if(this.args=$,this.options=w,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(p1.red(`
|
|
233
247
|
✗ Command "${$}" not found.
|
|
234
|
-
`)),this.enableDidYouMean){let w=[];for(let
|
|
235
|
-
Run \`${this.name??"cli"} --help\` for usage
|
|
236
|
-
`)
|
|
237
|
-
`),
|
|
238
|
-
`),
|
|
239
|
-
`),
|
|
240
|
-
`)}class
|
|
241
|
-
`),
|
|
242
|
-
`).length-1;this.output.write(
|
|
243
|
-
`);this.output.write(Y
|
|
244
|
-
`).slice(
|
|
245
|
-
`)),this._prevFrame=$;return}this.output.write(
|
|
246
|
-
`)}finally{await
|
|
247
|
-
`),B.stdin.end();B.unref();let T=Rw($),F=Date.now()+15000;while(Date.now()<F){if(E)throw E;let H=await Kw($);if(H!==null&&l0(H)){if(Y)q.success(`rpx daemon elevated to root (pid=${H}, https on :${w})`);return{httpsPort:w,httpPort:A,pidPath:T,done:Promise.resolve(),stop:async()=>{try{i.kill(H,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if(j!==null&&j!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${j}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((G)=>setTimeout(G,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}async function HF($={}){let w=$.verbose??!1,A=$.rpxDir??F$(),Y=$.registryDir??T$.join(A,"registry.d"),f=$.httpsPort??443,X=$.httpPort??80,U=$.hostname??"0.0.0.0",W=$.gcIntervalMs??AR,J=f>0&&f<1024||X>0&&X<1024,B=typeof i.getuid==="function"&&i.getuid()===0;if(i.platform!=="win32"&&J&&!B)return JR(A,f,X,w);let E=await YR(A),j=new Map,T=(L,a)=>WA(j,L,a);function F(L){j=JA(L.map((w$)=>({host:w$.to,path:w$.path,route:fR(w$)})));let a=Array.from(j.keys());z("daemon",`routing table now covers ${a.length} host(s): ${a.join(", ")||"<empty>"}`,w)}await df(Y,w).catch((L)=>{z("daemon",`initial gc failed: ${L}`,w)});let H=await Lw(Y,w);F(H),await Gw({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS reconcile on start failed: ${L}`,w)}),await FA(H,{rpxDir:A,verbose:w,ownerPid:i.pid}).catch((L)=>{z("daemon",`DNS setup on start failed: ${L}`,w)});let G=[];if($.productionCerts){if(G=await jJ($.productionCerts,w),w&&G.length>0)q.info(`SNI: serving ${G.length} real cert(s): ${G.map((L)=>L.serverName).join(", ")}`)}let K=fA(T,w),R=XA(w),N=null;if(G.length===0)N=await UR($,Y);let h=$.onDemandTls,y=h?.enabled?new nf({config:h,certsDir:h.certsDir??$.productionCerts?.certsDir??T$.join(A,"on-demand-certs"),initial:G,verbose:w,onCertAdded:(L)=>{V(L)}}):null;function I(L){if(L.length>0)return L.map((a)=>({serverName:a.serverName,cert:a.cert,key:a.key}));return{key:N.key,cert:N.cert,ca:N.ca,requestCert:!1,rejectUnauthorized:!1}}function S(L){return Bun.serve({port:f,hostname:U,tls:I(L),fetch(a,w$){return K(a,w$)},websocket:R,error(a){return z("daemon",`https server error: ${a}`,w),new Response(`Server Error: ${a.message}`,{status:500})}})}let B0=S(y?y.sniEntries():G);async function V(L){if(S$)return;z("daemon",`rebuilding :443 with ${L.length} SNI cert(s)`,w),B0.stop(!1);let a;for(let w$=0;w$<20&&!S$;w$++)try{B0=S(L);return}catch(qA){a=qA,await new Promise((nF)=>setTimeout(nF,25))}q.error(`rpx: failed to rebuild :443 after issuing cert: ${a?.message}`)}let O=null;if(X>0)O=Bun.serve({port:X,hostname:U,fetch(L){let a=new URL(L.url),w$=(L.headers.get("host")??a.hostname).split(":")[0];if(y&&a.pathname.startsWith("/.well-known/acme-challenge/")){let qA=y.challengeStore.handlePath(a.pathname);if(qA!==void 0)return new Response(qA,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(y&&!y.hasCert(w$))y.ensureCert(w$).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${w$}${a.pathname}${a.search}`}})}});if(w)q.success(`rpx daemon listening on https://${U}:${f}${O?` (http→https on :${X})`:""}`),q.info(`pid file: ${E}`),q.info(`registry: ${Y}`);let e0=RJ((L)=>{F(L),FA(L,{rpxDir:A,verbose:w,ownerPid:i.pid}).catch((a)=>{z("daemon",`DNS sync on registry change failed: ${a}`,w)})},{dir:Y,verbose:w}),$$=setInterval(()=>{df(Y,w).then((L)=>{if(L>0)z("daemon",`gc reaped ${L} stale entries`,w)}).catch((L)=>{z("daemon",`periodic gc failed: ${L}`,w)})},W);if(typeof $$.unref==="function")$$.unref();let S$=!1,L$,e$=new Promise((L)=>{L$=L});async function mJ(){if(S$)return e$;if(S$=!0,clearInterval($$),e0.close(),B0.stop(!1),O?.stop(!1),await Ow({rpxDir:A,verbose:w}).catch((L)=>{z("daemon",`DNS teardown failed: ${L}`,w)}),await zA(A),w)q.info("rpx daemon stopped");return L$(),e$}let dJ=(L)=>{z("daemon",`received ${L}, shutting down`,w),mJ().catch(()=>{})};return i.once("SIGINT",dJ),i.once("SIGTERM",dJ),{stop:mJ,done:e$,httpsPort:typeof B0.port==="number"?B0.port:f,httpPort:O&&typeof O.port==="number"?O.port:X,pidPath:E,ensureCert:(L)=>y?y.ensureCert(L):Promise.resolve(!1)}}function WR(){let $=i.execPath,w=T$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&i.argv[1])return[$,i.argv[1],"daemon:start"];return[$,"daemon:start"]}async function KF($={}){let w=$.rpxDir??F$(),A=$.verbose??!1;await Gw({rpxDir:w,verbose:A}).catch((E)=>{z("daemon",`DNS reconcile before ensureDaemonRunning: ${E}`,A)});let Y=await Kw(w);if(Y!==null&&l0(Y))return z("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)z("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await zA(w);await M$.mkdir(w,{recursive:!0});let f=$.spawnCommand??WR();if(f.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");z("daemon",`spawning daemon: ${f.join(" ")}`,A);let X=GF(f[0],f.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??i.cwd(),env:$.spawnEnv?{...i.env,...$.spawnEnv}:i.env});X.unref();let U=null;X.once("error",(E)=>{U=E});let W=$.startupTimeoutMs??5000,J=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let E=await Kw(w);if(E!==null&&l0(E))return z("daemon",`daemon registered with pid=${E}`,A),{pid:E,spawned:!0};await new Promise((j)=>setTimeout(j,J))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function RF($={}){let w=$.rpxDir??F$(),A=$.verbose??!1,Y=$.timeoutMs??5000,f=$.pollIntervalMs??50,X=$.forceAfterTimeout??!0,U=await Kw(w);if(U===null||!l0(U)){if(U!==null)await zA(w);return await Gw({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{i.kill(U,"SIGTERM")}catch(J){if(J.code==="ESRCH")return await zA(w),{stopped:!1,pid:U,forced:!1};throw J}let W=Date.now()+Y;while(Date.now()<W){if(!l0(U))return z("daemon",`daemon pid=${U} stopped cleanly`,A),{stopped:!0,pid:U,forced:!1};await new Promise((J)=>setTimeout(J,f))}if(!X)throw Error(`rpx daemon (pid=${U}) did not exit within ${Y}ms`);z("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,A);try{i.kill(U,"SIGKILL")}catch(J){if(J.code!=="ESRCH")throw J}return await zA(w),await Ow({rpxDir:w,verbose:A}).catch((J)=>{z("daemon",`DNS teardown after SIGKILL: ${J}`,A)}),{stopped:!0,pid:U,forced:!0}}async function NF($={}){let w=$.rpxDir??F$();if(await sf(w))return;await Gw({rpxDir:w,verbose:$.verbose})}fw();U0();import{spawn as BR}from"node:child_process";import*as _w from"node:process";class qF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){z("start",`Process ${$} is already running`,A);return}let[Y,...f]=w.command.split(" "),X=w.cwd||_w.cwd();z("start",`Starting process ${$}:`,A),z("start",` Command: ${Y} ${f.join(" ")}`,A),z("start",` Working directory: ${X}`,A),z("start",` Environment variables: ${E$(w.env)}`,A);let U=BR(Y,f,{cwd:X,env:{..._w.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:U,env:w.env}),new Promise((W,J)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)z("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),J(B),_w.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)z("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),J(Error(`Process ${$} exited with code ${B}`)),_w.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{z("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{z("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),J(Error(`Process ${$} was killed during startup`));else z("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){z("start",`No process found for ${$}`,w);return}return z("start",`Stopping process ${$}`,w),new Promise((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),z("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){z("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(f){}}},3000)}catch(f){z("start",`Error stopping process ${$}: ${f}`,w),this.processes.delete($),Y()}})}async stopAll($){if(this.isShuttingDown){z("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,z("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var of=new qF;U0();import*as m0 from"node:fs/promises";import{homedir as ER}from"node:os";import*as QJ from"node:path";import*as DJ from"node:process";var jR=/^[a-zA-Z0-9._-]+$/;function Qw(){return QJ.join(ER(),".stacks","rpx","registry.d")}function _1($){return typeof $==="string"&&$.length>0&&$.length<=128&&jR.test($)}function kJ($,w){if(!_1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return QJ.join($,`${w}.json`)}function hF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,f=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&_1(w.id)&&(Y||f)&&typeof w.to==="string"&&w.to.length>0&&X&&A&&typeof w.createdAt==="string"}async function TR($){await m0.mkdir($,{recursive:!0})}async function yF($,w=Qw(),A){if(!hF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await TR(w);let Y=kJ(w,$.id),f=`${Y}.tmp.${DJ.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await m0.writeFile(f,X,{encoding:"utf8",mode:420}),await m0.rename(f,Y),z("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await m0.unlink(f).catch(()=>{}),U}}async function MF($,w=Qw(),A){let Y=kJ(w,$);try{await m0.unlink(Y),z("registry",`removed entry ${$}`,A)}catch(f){if(f.code!=="ENOENT")throw f}}async function ZJ($,w=Qw(),A){let Y=kJ(w,$);try{let f=await m0.readFile(Y,"utf8"),X=JSON.parse(f);if(!hF(X))return z("registry",`entry ${$} failed validation, removing`,A),await m0.unlink(Y).catch(()=>{}),null;return X}catch(f){if(f.code==="ENOENT")return null;if(f instanceof SyntaxError)return z("registry",`entry ${$} has invalid JSON, removing`,A),await m0.unlink(Y).catch(()=>{}),null;throw f}}async function IF($=Qw(),w){let A;try{A=await m0.readdir($)}catch(f){if(f.code==="ENOENT")return[];throw f}let Y=[];for(let f of A){if(!f.endsWith(".json"))continue;let X=f.slice(0,-5);if(!_1(X))continue;let U=await ZJ(X,$,w);if(U)Y.push(U)}return Y}fw();import{execSync as qR}from"node:child_process";import*as xw from"node:http";import*as kF from"node:http2";import*as ZF from"node:net";import*as A0 from"node:process";var ef=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,I$={bold:ef(1,22),dim:ef(2,22),green:ef(32,39),cyan:ef(36,39)};H8();NJ();fw();jA();U0();import*as CF from"node:fs";import*as SF from"node:path";import*as C$ from"node:process";function FR($,w){let Y=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return Y.length>0?Y:"rpx"}async function xJ($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,Y=new Set,f=$.proxies.map((T)=>{let F=T.id??FR(T.to,T.path);if(!EA(F))throw Error(`invalid registry id "${F}" derived from to="${T.to}"`);if(Y.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return Y.add(F),{...T,id:F}}),X=new Date().toISOString();for(let T of f)await eT({id:T.id,from:T.from,to:T.to,path:T.path,pid:$.persistent?void 0:C$.pid,cwd:C$.cwd(),createdAt:X,cleanUrls:T.cleanUrls,changeOrigin:T.changeOrigin,pathRewrites:T.pathRewrites,static:T.static},A,w);let U=await AF({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let T of f){let F=T.static?`static ${typeof T.static==="string"?T.static:T.static.dir}`:T.from;q.success(`https://${T.to} → ${F}`)}if(q.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,J=A??zw(),B=f.map((T)=>T.id),E=async()=>{if(W)return;W=!0;for(let T of B)await KJ(T,A,w).catch((F)=>{z("runner",`removeEntry(${T}) failed: ${F}`,w)})},j=(T)=>{z("runner",`received ${T}, unregistering ${B.length} entries`,w),E().finally(()=>C$.exit(0))};C$.once("SIGINT",j),C$.once("SIGTERM",j),C$.once("exit",()=>{if(W)return;for(let T of B)try{CF.unlinkSync(SF.join(J,`${T}.json`))}catch{}}),await new Promise(()=>{})}U0();import{exec as zR}from"node:child_process";import Dw from"node:fs";import VF from"node:os";import iJ from"node:path";import*as GA from"node:process";import{promisify as GR}from"node:util";var $X=GR(zR);function LF($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var z$=GA.platform==="win32"?iJ.join(GA.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",PJ=!1;async function wX($){if(GA.platform==="win32")throw Error("Administrator privileges required on Windows");let w=Cw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:Y}=await $X(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return PJ=!0,Y}if(PJ)try{let{stdout:Y}=await $X(`sudo -n sh -c '${A}'`);return Y}catch(Y){z("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:Y}=await $X(`sudo -n sh -c '${A}'`);return PJ=!0,Y}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(Y){throw Error(`Failed to execute sudo command: ${Y.message}`)}}async function HA($,w){let A=$.filter((f)=>!LF(f)),Y=$.filter((f)=>LF(f));if(Y.length>0)z("hosts",`Skipping /etc/hosts for loopback dev names: ${Y.join(", ")}`,w);if(A.length===0)return;z("hosts",`Adding hosts: ${A.join(", ")}`,w),z("hosts",`Using hosts file at: ${z$}`,w);try{let f;try{f=await Dw.promises.readFile(z$,"utf-8")}catch{z("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{f=await wX(`cat "${z$}"`)}catch(J){throw console.log(" Could not read hosts file — skipping hosts setup"),z("hosts",`sudo read also failed: ${J}`,w),Error(`Cannot read hosts file: ${J}`)}}let X=A.filter((J)=>{let B=`127.0.0.1 ${J}`,E=`::1 ${J}`;return!f.includes(B)&&!f.includes(E)});if(X.length===0){z("hosts","All hosts already exist in hosts file",w);return}let U=X.map((J)=>`
|
|
248
|
+
`)),this.enableDidYouMean){let w=[];for(let A of this.commands){if(A.displayName)w.push(A.displayName);if(A.aliasNames)w.push(...A.aliasNames)}let Y=_W($,w);if(Y.length>0)console.log(p1.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${p1.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(p1.dim("Run"),`${this.name} --help`,p1.dim("to see all available commands")),Aw.exit(1)}async parse($=CW,w={}){let{run:Y=!0,exitOnError:A=!1}=w;if(A)try{return await this.parse($,{run:Y})}catch(f){throw this.handleUsageError(f),f}if(this.rawArgs=$,!this.name)this.name=$[1]?oF($[1]):"cli";let U=!0,X=$.slice(2),J=X[0];if(J&&!J.startsWith("-")){for(let f of this.commands)if(f.isMatched(J)){let B=this.mri(X,f);U=!1;let j={...B,args:B.args.slice(1)};this.setParsedInfo(j,f,J),this.emit(`command:${J}`,f);break}}if(U){for(let f of this.commands)if(f.name===""){U=!1;let B=this.mri(X,f);this.setParsedInfo(B,f),this.emit("command:!",f);break}}if(U){let f=this.mri($.slice(2));this.setParsedInfo(f)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),Y=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Y=!1,this.unsetMatchedCommand();let W={args:this.args,options:this.options};if(Y)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return W}mri($,w){let Y=[...this.globalCommand.options,...w?w.options:[]],A=tF(Y),U=[],X=$.indexOf("--");if(X>-1)U=$.slice(X+1),$=$.slice(0,X);let J=nF($,A),W={_:J._};for(let G of Object.keys(J))if(G!=="_")W[SW(G)]=J[G];let f=W._,B={"--":U},j=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,z=Object.create(null);for(let G of Y){if(!j&&G.config.default!==void 0)for(let F of G.names)B[F]=G.config.default;if(Array.isArray(G.config.type)){if(z[G.name]===void 0)z[G.name]={shouldTransform:!0,transformFunction:G.config.type[0]}}}for(let G of Object.keys(W))if(G!=="_"){let F=G.split(".");aF(B,F,W[G]),sF(B,z)}return{args:f,options:B}}async run($=CW){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let A=$,U=A.message??"command-line error",X=this.name?`${this.name}: `:"",J=/--help/.test(U)?"":`
|
|
249
|
+
Run \`${this.name??"cli"} --help\` for usage.`;Aw.stderr.write(`${X}${U}${J}
|
|
250
|
+
`),Aw.exit(A.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((W,f)=>{if(W.variadic)A.push($.slice(f));else A.push($[f])}),A.push(w);let U={command:Y,args:A,options:w};for(let W of Y.beforeHooks)await W(U);let X,J=async()=>{let W=Y.commandAction.apply(this,A);if(W instanceof Promise)X=await W;else X=W;return X};if(Y.middleware.length>0){let W=0,f=async()=>{if(W<Y.middleware.length){let B=Y.middleware[W++];await B({...U,next:f})}else await J()};await f()}else await J();for(let W of Y.afterHooks)await W(U);return X}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return Aw.removeAllListeners("SIGINT"),Aw.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class DW{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let w=this.cache.get($);if(!w){this.misses++;return}if(Date.now()-w.timestamp>w.ttl){this.cache.delete($),this.misses++;return}return this.hits++,w.value}set($,w,Y=5000){if(!this.enabled)return;this.cache.set($,{value:w,timestamp:Date.now(),ttl:Y})}has($){if(!this.enabled)return!1;let w=this.cache.get($);if(!w)return!1;if(Date.now()-w.timestamp>w.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[w,Y]of this.cache.entries())if($-Y.timestamp>Y.ttl)this.cache.delete(w)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var qR=new DW;function J5(){if("FORCE_COLOR"in t1.env)return t1.env.FORCE_COLOR!=="0";if("NO_COLOR"in t1.env||t1.env.TERM==="dumb")return!1;if(t1.platform==="win32")return!0;return hW.isatty(1)&&hW.isatty(2)}var ZW=J5();function Y0($,w){if(!ZW)return(Y)=>Y;return(Y)=>$+Y+w}var f5=Y0("\x1B[0m","\x1B[0m"),W5=Y0("\x1B[31m","\x1B[39m"),B5=Y0("\x1B[32m","\x1B[39m"),j5=Y0("\x1B[33m","\x1B[39m"),z5=Y0("\x1B[34m","\x1B[39m"),F5=Y0("\x1B[35m","\x1B[39m"),G5=Y0("\x1B[36m","\x1B[39m"),E5=Y0("\x1B[37m","\x1B[39m"),K5=Y0("\x1B[90m","\x1B[39m"),T5=Y0("\x1B[1m","\x1B[22m"),H5=Y0("\x1B[3m","\x1B[23m"),N5=Y0("\x1B[4m","\x1B[24m"),q5=Y0("\x1B[2m","\x1B[22m"),R5=Y0("\x1B[7m","\x1B[27m"),M5=Y0("\x1B[8m","\x1B[28m"),I5=Y0("\x1B[9m","\x1B[29m"),y5=Y0("\x1B[41m","\x1B[49m"),C5=Y0("\x1B[42m","\x1B[49m"),h5=Y0("\x1B[43m","\x1B[49m"),V5=Y0("\x1B[44m","\x1B[49m"),L5=Y0("\x1B[45m","\x1B[49m"),Q5=Y0("\x1B[46m","\x1B[49m"),O5=Y0("\x1B[47m","\x1B[49m"),S5=ZW,_5={reset:f5,red:W5,green:B5,yellow:j5,blue:z5,magenta:F5,cyan:G5,white:E5,gray:K5,bold:T5,italic:H5,underline:N5,dim:q5,inverse:R5,hidden:M5,strikethrough:I5,bgRed:y5,bgGreen:C5,bgYellow:h5,bgBlue:V5,bgMagenta:L5,bgCyan:Q5,bgWhite:O5,isColorSupported:S5},uY=_5,D5=["up","down","left","right","space","enter","cancel"],iY={actions:new Set(D5),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function xW($,w){if(typeof $==="string")return iY.aliases.get($)===w;for(let Y of $){if(Y===void 0)continue;if(xW(Y,w))return!0}return!1}function Z5($,w){if($===w)return[];let Y=$.split(`
|
|
251
|
+
`),A=w.split(`
|
|
252
|
+
`),U=[];for(let X=0;X<Math.max(Y.length,A.length);X++)if(Y[X]!==A[X])U.push(X);return U}var hR=k5.platform.startsWith("win"),VW=Symbol("clapp:cancel");function xY($,w){let Y=$;if(Y.isTTY)Y.setRawMode(w)}function u5($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function i5($){return u5($).length}function QW($,w,Y){if(!w||w<1)return $;let A=Y?.hard??!1,U=Y?.trim??!0,X=$.split(`
|
|
253
|
+
`),J=[];for(let W of X){if(i5(W)<=w){J.push(U?W.trimEnd():W);continue}if(A){let f="",B=0,j=0;while(j<W.length){let z=W.slice(j).match(/^\x1b\[[0-9;]*m/);if(z){f+=z[0],j+=z[0].length;continue}if(B>=w)J.push(U?f.trimEnd():f),f="",B=0;f+=W[j],B++,j++}if(f)J.push(U?f.trimEnd():f)}else J.push(U?W.trimEnd():W)}return J.join(`
|
|
254
|
+
`)}class uX{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor($,w=!0){let{input:Y=x5,output:A=P5,render:U,signal:X,...J}=$;this.opts=J,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=U.bind(this),this._track=w,this._abortSignal=X,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber($,w){let Y=this._subscribers.get($)??[];Y.push(w),this._subscribers.set($,Y)}on($,w){return this.setSubscriber($,{cb:w}),this}once($,w){return this.setSubscriber($,{cb:w,once:!0}),this}emit($,...w){let Y=this._subscribers.get($)??[],A=[];for(let U of Y)if(U.cb(...w),U.once)A.push(()=>Y.splice(Y.indexOf(U),1));for(let U of A)U();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(VW);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=b5.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),xY(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Q$.show),this.output.off("resize",this.render),xY(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(Q$.show),this.output.off("resize",this.render),xY(this.input,!1),$(VW)})})}_isActionKey($,w){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,w){if(this.userInput=$??"",this.emit("userInput",this.userInput),w&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,w){if(this._track&&w.name!=="return"){if(w.name&&this._isActionKey($,w))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=w.name==="tab"||w.name==="escape"||w.name==="backspace"||w.name==="delete"||w.name==="enter"||w.name==="return"||w.name&&["up","down","left","right"].includes(w.name);if($&&!Y&&$.length===1&&$>=" ")this._manualLine+=$;else if(w.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let A=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(A)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&iY.aliases.has(w.name))this.emit("cursor",iY.aliases.get(w.name));if(iY.actions.has(w.name))this.emit("cursor",w.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),w),w?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(xW([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
255
|
+
`),xY(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let $=QW(this._prevFrame,LW.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
256
|
+
`).length-1;this.output.write(Q$.move(-999,$*-1))}render(){let $=QW(this._render(this)??"",LW.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(Q$.hide);else{let w=Z5(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let Y=w[0];this.output.write(Q$.move(0,Y)),this.output.write(kX.lines(1));let A=$.split(`
|
|
257
|
+
`);this.output.write(A[Y]),this._prevFrame=$,this.output.write(Q$.move(0,A.length-Y-1));return}if(w&&w?.length>1){let Y=w[0];this.output.write(Q$.move(0,Y)),this.output.write(kX.down());let U=$.split(`
|
|
258
|
+
`).slice(Y);this.output.write(U.join(`
|
|
259
|
+
`)),this._prevFrame=$;return}this.output.write(kX.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function c5($,w){if($===void 0)return 0;if(w.length===0)return 0;let A=w.findIndex((U)=>U.value===$);return A!==-1?A:0}function v5($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function m5($,w){if(!w)return;if($)return w;return w[0]}class d5 extends uX{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#A;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return uY.inverse(uY.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...Y]=this.userInput.slice(this._cursor);return`${$}${uY.inverse(w)}${Y.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#A=$.filter??v5;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let A of Y){let U=w.findIndex((X)=>X.value===A);if(U!==-1)this.toggleSelected(A),this.#$=U}this.focusedValue=this.options[this.#$]?.value,this.on("key",(A,U)=>this.#U(A,U)),this.on("userInput",(A)=>this.#X(A))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#U($,w){let Y=w.name==="up",A=w.name==="down",U=w.name==="return";if(Y||A){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(U)this.value=m5(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#X($){if($!==this.#Y){this.#Y=$;let w=this.options;if($)this.filteredOptions=w.filter((Y)=>this.#A($,Y));else this.filteredOptions=[...w];if(this.#$=c5(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class g5 extends uX{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return w.every((A)=>Y.includes(A.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),Y=this.getGroupItems(w);if(this.isGroupSelected(w))this.value=this.value.filter((A)=>Y.findIndex((U)=>U.value===A)===-1);else this.value=[...this.value,...Y.map((A)=>A.value)];this.value=Array.from(new Set(this.value))}else{let w=this.value.includes($.value);this.value=w?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((U)=>({...U,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let A=this.options[this.cursor]?.group===!0;if(!this.#$&&A)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let A=this.options[this.cursor]?.group===!0;if(!this.#$&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var l5=eF();var o=($,w)=>l5?$:w,QR=o("◆","*"),OR=o("■","x"),SR=o("▲","x"),_R=o("◇","o"),kR=o("┌","T"),n5=o("│","|"),DR=o("└","—"),ZR=o("●",">"),xR=o("○"," "),PR=o("◻","[•]"),bR=o("◼","[+]"),uR=o("◻","[ ]"),iR=o("▪","•"),cR=o("─","-"),vR=o("╮","+"),mR=o("├","+"),dR=o("╯","+"),gR=o("●","•"),lR=o("◆","*"),nR=o("▲","!"),pR=o("■","x");var tR={light:o("─","-"),heavy:o("━","="),block:o("█","#")};function p5(){return`${uY.gray(n5)} `}var rR=p5();V8();import{homedir as L8}from"node:os";import{join as Q8,resolve as uI}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",AE={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Q8(L8(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Q8(L8(),".stacks","ssl","stacks.localhost.crt"),keyPath:Q8(L8(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var sw=AE;fw();YX();UX();JX();fX();mf();qY();hY();b1();f0();import{spawn as WF}from"node:child_process";import*as P0 from"node:fs/promises";import{homedir as BF}from"node:os";import*as I$ from"node:path";import*as y from"node:process";var Lq=5000;function j$(){return I$.join(BF(),".stacks","rpx")}function Mw($=j$()){return I$.join($,"daemon.pid")}async function Rw($=j$()){try{let w=await P0.readFile(Mw($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function EX($=j$()){let w=await Rw($);return w!==null&&p0(w)}async function jF($=j$()){await P0.mkdir($,{recursive:!0});let w=Mw($);while(!0){try{let A=await P0.open(w,"wx");try{await A.write(`${y.pid}
|
|
260
|
+
`)}finally{await A.close()}return w}catch(A){if(A.code!=="EEXIST")throw A}let Y=await Rw($);if(Y!==null&&p0(Y))throw Error(`rpx daemon already running (pid=${Y})`);await P0.unlink(w).catch(()=>{})}}async function i1($=j$()){await P0.unlink(Mw($)).catch(()=>{})}function zF($){let w=$.cleanUrls??!1,Y=k1($.path);if($.static)return{static:NY($.static,w),cleanUrls:w,basePath:Y};let A=$.from??"localhost:1";return{sourceHost:new URL(A.startsWith("http")?A:`http://${A}`).host,cleanUrls:w,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites,basePath:Y}}function Qq($){return $.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??$[0]??"rpx.localhost"}async function AW($,w){let Y=await s$(w,$.verbose),A=[...new Set(Y.map((f)=>f.to).filter(Boolean))],U=Qq(A),X=[...new Set([U,...A,"rpx.localhost"])],J=Pf(A,U,$.verbose);if(typeof $.https==="object"&&typeof J.https==="object")J.https={...J.https,...$.https};let W=await a$(J);if(W&&!HU($X,X))E("daemon",`shared cert missing SANs for registry host(s), regenerating (${X.join(", ")})`,$.verbose),wX(),W=null;if(!W)E("daemon","no usable cert on disk, generating one via tlsx",$.verbose),await O1({...J,forceRegenerate:!0}),W=await a$(J);if(!W)throw Error("failed to bootstrap TLS for rpx daemon");return W}async function Oq($,w,Y,A){let U=y.env.SUDO_PASSWORD,X=y.env.HOME??BF(),J=[y.execPath,...y.argv.slice(1)],W=[`HOME=${X}`,`PATH=${y.env.PATH??""}`];if(A)W.push("RPX_VERBOSE=1");let f=U?["-S","-p","","env",...W,...J]:["-n","env",...W,...J];E("daemon",`elevating daemon via sudo for privileged ports ${w}/${Y}`,A);let B=WF("sudo",f,{detached:!0,stdio:["pipe","ignore","ignore"]}),j=null,z=null;if(B.once("error",(T)=>{j=T}),B.once("exit",(T)=>{z=T??0}),U&&B.stdin)B.stdin.write(`${U}
|
|
261
|
+
`),B.stdin.end();B.unref();let G=Mw($),F=Date.now()+15000;while(Date.now()<F){if(j)throw j;let T=await Rw($);if(T!==null&&p0(T)){if(A)R.success(`rpx daemon elevated to root (pid=${T}, https on :${w})`);return{httpsPort:w,httpPort:Y,pidPath:G,done:Promise.resolve(),stop:async()=>{try{y.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if(z!==null&&z!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${z}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((K)=>setTimeout(K,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}var XF=!1;function UW(){if(XF)return;XF=!0,y.on("uncaughtException",($)=>{R.error(`rpx daemon: uncaught exception (continuing): ${$?.stack??$}`)}),y.on("unhandledRejection",($)=>{R.error(`rpx daemon: unhandled rejection (continuing): ${$}`)})}function FF($,w){let Y;try{Y=new URL($.url)}catch{return new Response("Bad Request",{status:400})}let A=($.headers.get("host")??Y.hostname).split(":")[0];if(w&&Y.pathname.startsWith("/.well-known/acme-challenge/")){let U=w.challengeStore.handlePath(Y.pathname);if(U!==void 0)return new Response(U,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(w&&!w.hasCert(A))w.ensureCert(A).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${A}${Y.pathname}${Y.search}`}})}async function GF($={}){UW();let w=$.verbose??!1,Y=$.rpxDir??j$(),A=$.registryDir??I$.join(Y,"registry.d"),U=$.httpsPort??443,X=$.httpPort??80,J=$.hostname??"0.0.0.0",W=$.gcIntervalMs??Lq;if(y.env.RPX_DAEMON_WORKER==="1")return kq({rpxDir:y.env.RPX_WORKER_RPXDIR??Y,registryDir:y.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(y.env.RPX_WORKER_HTTPSPORT??"",10)||U,hostname:y.env.RPX_WORKER_HOSTNAME??J,verbose:y.env.RPX_WORKER_VERBOSE==="1"||w});let f=U>0&&U<1024||X>0&&X<1024,B=typeof y.getuid==="function"&&y.getuid()===0;if(y.platform!=="win32"&&f&&!B)return Oq(Y,U,X,w);let j=Math.max(1,$.workers??(Number.parseInt(y.env.RPX_WORKERS??"",10)||1));if(j>1)return Dq($,{rpxDir:Y,registryDir:A,httpsPort:U,httpPort:X,hostname:J,verbose:w,gcIntervalMs:W,workers:j});let z=await jF(Y),G=new Map,F=(L,t)=>Z1(G,L,t);function T(L){G=D1(L.map((L$)=>({host:L$.to,path:L$.path,route:zF(L$)})));let t=Array.from(G.keys());E("daemon",`routing table now covers ${t.length} host(s): ${t.join(", ")||"<empty>"}`,w)}await P1(A,w).catch((L)=>{E("daemon",`initial gc failed: ${L}`,w)});let K=await s$(A,w);T(K),await $w({rpxDir:Y,verbose:w}).catch((L)=>{E("daemon",`DNS reconcile on start failed: ${L}`,w)}),await Dw(K,{rpxDir:Y,verbose:w,ownerPid:y.pid}).catch((L)=>{E("daemon",`DNS setup on start failed: ${L}`,w)});let H=[];if($.productionCerts){if(H=await x1($.productionCerts,w),w&&H.length>0)R.info(`SNI: serving ${H.length} real cert(s): ${H.map((L)=>L.serverName).join(", ")}`)}let q=S1(F,w),M=_1(w),I=null;if(H.length===0)I=await AW($,A);let h=$.onDemandTls,N=h?.enabled?new IY({config:h,certsDir:h.certsDir??$.productionCerts?.certsDir??I$.join(Y,"on-demand-certs"),initial:H,verbose:w,onCertAdded:(L)=>{v1(L)}}):null;function C(L){if(L.length>0)return L.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key}));return{key:I.key,cert:I.cert,ca:I.ca,requestCert:!1,rejectUnauthorized:!1}}function O(L){return Bun.serve({port:U,hostname:J,reusePort:C1(),tls:C(L),fetch(t,L$){return q(t,L$)},websocket:M,error(t){return E("daemon",`https server error: ${t}`,w),new Response(`Server Error: ${t.message}`,{status:500})}})}let p=(L)=>[...new Set(L.map((t)=>t.to).filter(Boolean))],x0=(L)=>{if(!I)return H;return xf([...p(L),"rpx.localhost"],I)},h$=O(N?N.sniEntries():H.length>0?H:x0(K)),M$=null,Pw=!1;async function v1(L){if(S)return;if(M$=L,Pw)return;Pw=!0;try{while(!S&&M$){let t=M$;M$=null,E("daemon",`rebuilding :443 with ${t.length} SNI cert(s)`,w),h$.stop(!1);let L$,NW=!1;for(let qW=0;qW<20&&!S;qW++)try{h$=O(t),NW=!0;break}catch(uF){L$=uF,await new Promise((iF)=>setTimeout(iF,25))}if(!NW)R.error(`rpx: failed to rebuild :443 after issuing cert: ${L$?.message}`)}}finally{Pw=!1}}let V$=null;if(X>0)V$=Bun.serve({port:X,hostname:J,fetch(L){return FF(L,N)},error(){return new Response("Bad Request",{status:400})}});if(w)R.success(`rpx daemon listening on https://${J}:${U}${V$?` (http→https on :${X})`:""}`),R.info(`pid file: ${z}`),R.info(`registry: ${A}`);async function m1(L){if(S||H.length>0||N||!I)return;try{I=await AW($,A),await v1(x0(L))}catch(t){E("daemon",`TLS sync on registry change failed: ${t}`,w)}}let ZY=CY((L)=>{T(L),m1(L),Dw(L,{rpxDir:Y,verbose:w,ownerPid:y.pid}).catch((t)=>{E("daemon",`DNS sync on registry change failed: ${t}`,w)})},{dir:A,verbose:w}),bw=setInterval(()=>{P1(A,w).then((L)=>{if(L>0)E("daemon",`gc reaped ${L} stale entries`,w)}).catch((L)=>{E("daemon",`periodic gc failed: ${L}`,w)})},W);if(typeof bw.unref==="function")bw.unref();let S=!1,Yw,d1=new Promise((L)=>{Yw=L});async function g1(){if(S)return d1;if(S=!0,clearInterval(bw),ZY.close(),h$.stop(!1),V$?.stop(!1),await Nw({rpxDir:Y,verbose:w}).catch((L)=>{E("daemon",`DNS teardown failed: ${L}`,w)}),await i1(Y),w)R.info("rpx daemon stopped");return Yw(),d1}let l1=(L)=>{E("daemon",`received ${L}, shutting down`,w),g1().catch(()=>{})};return y.once("SIGINT",l1),y.once("SIGTERM",l1),{stop:g1,done:d1,httpsPort:typeof h$.port==="number"?h$.port:U,httpPort:V$&&typeof V$.port==="number"?V$.port:X,pidPath:z,ensureCert:(L)=>N?N.ensureCert(L):Promise.resolve(!1)}}function XW($){return I$.join($,"cluster-sni.json")}async function JF($,w,Y){let A=XW($),U=`${A}.${y.pid}.tmp`;await P0.writeFile(U,JSON.stringify({sni:w,dev:Y}),"utf8"),await P0.rename(U,A)}async function fF($){try{return JSON.parse(await P0.readFile(XW($),"utf8"))}catch{return{sni:[],dev:null}}}function Sq($){if($.sni.length>0)return $.sni.map((w)=>({serverName:w.serverName,cert:w.cert,key:w.key}));if($.dev)return{key:$.dev.key,cert:$.dev.cert,ca:$.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function _q(){let $=y.execPath,w=y.env.RPX_WORKER_BIN;if(w)return[$,w,"daemon:start"];let Y=I$.basename($).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&y.argv[1])return[$,y.argv[1],"daemon:start"];return[$,"daemon:start"]}async function kq($){UW();let{rpxDir:w,registryDir:Y,httpsPort:A,hostname:U,verbose:X}=$,J=new Map,W=(N,C)=>Z1(J,N,C),f=(N)=>{J=D1(N.map((C)=>({host:C.to,path:C.path,route:zF(C)})))};f(await s$(Y,X));let B=S1(W,X),j=_1(X),z=!1,G=(N)=>Bun.serve({port:A,hostname:U,reusePort:!0,tls:Sq(N),fetch(C,O){return B(C,O)},websocket:j,error(C){return E("daemon",`worker https error: ${C}`,X),new Response(`Server Error: ${C.message}`,{status:500})}}),F=G(await fF(w));async function T(){if(z)return;let N=await fF(w),C=null;for(let p=0;p<20&&!z;p++)try{C=G(N);break}catch{await new Promise((x0)=>setTimeout(x0,25))}if(!C){E("daemon","worker reloadTls: could not bind new listener; keeping current",X);return}let O=F;F=C,O.stop(!1)}let K=CY((N)=>f(N),{dir:Y,verbose:X}),H=()=>{T().catch(()=>{})};y.on("SIGHUP",H);let q,M=new Promise((N)=>{q=N});async function I(){if(z)return M;return z=!0,y.off("SIGHUP",H),K.close(),F.stop(!1),q(),M}let h=()=>{I().then(()=>y.exit(0)).catch(()=>y.exit(0))};if(y.once("SIGTERM",h),y.once("SIGINT",h),X)R.success(`rpx worker (pid ${y.pid}) serving :${A}`);return{stop:I,done:M,httpsPort:typeof F.port==="number"?F.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1)}}async function Dq($,w){UW();let{rpxDir:Y,registryDir:A,httpsPort:U,httpPort:X,hostname:J,verbose:W,gcIntervalMs:f,workers:B}=w,j=await jF(Y),z=[];if($.productionCerts)z=await x1($.productionCerts,W);let G=null;if(z.length===0)G=await AW($,A);let F=G?{key:G.key,cert:G.cert,ca:Array.isArray(G.ca)?G.ca.join(`
|
|
262
|
+
`):G.ca}:null,T=!1,K=[];function H(S){for(let Yw of K)try{Yw.kill(S)}catch{}}async function q(S){await JF(Y,S,F),H("SIGHUP")}let M=$.onDemandTls,I=M?.enabled?new IY({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??I$.join(Y,"on-demand-certs"),initial:z,verbose:W,onCertAdded:(S)=>{q(S)}}):null;await JF(Y,I?I.sniEntries():z,F);let h=await s$(A,W);await $w({rpxDir:Y,verbose:W}).catch((S)=>{E("daemon",`DNS reconcile on start failed: ${S}`,W)}),await Dw(h,{rpxDir:Y,verbose:W,ownerPid:y.pid}).catch((S)=>{E("daemon",`DNS setup on start failed: ${S}`,W)}),await P1(A,W).catch(()=>{});let N=CY((S)=>{Dw(S,{rpxDir:Y,verbose:W,ownerPid:y.pid}).catch((Yw)=>{E("daemon",`DNS sync on registry change failed: ${Yw}`,W)})},{dir:A,verbose:W}),C=setInterval(()=>{P1(A,W).catch(()=>{})},f);C.unref?.();let O=null;if(X>0)O=Bun.serve({port:X,hostname:J,fetch(S){return FF(S,I)},error(){return new Response("Bad Request",{status:400})}});let p=10,x0=60000,h$=30000,M$=0,Pw=Date.now();function v1(){if(T)return;let S={...y.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(U),RPX_WORKER_HOSTNAME:J,RPX_WORKER_VERBOSE:W?"1":"0"},Yw=Bun.spawn(_q(),{env:S,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(d1,g1){if(T)return;let l1=K.indexOf(d1);if(l1!==-1)K.splice(l1,1);let L=Date.now();if(L-Pw>x0)Pw=L,M$=0;if(M$++,M$>p){R.error(`rpx: worker keeps exiting (code ${g1}); giving up after ${p} restarts in ${Math.round(x0/1000)}s`);return}let t=Math.min(h$,100*2**Math.min(M$,8));E("daemon",`worker exited (code ${g1}); respawning in ${t}ms (restart ${M$}/${p})`,W),setTimeout(v1,t).unref?.()}});K.push(Yw)}for(let S=0;S<B;S++)v1();if(W)R.success(`rpx coordinator listening on https://${J}:${U} via ${B} worker(s)${O?` (http→https on :${X})`:""}`),R.info(`pid file: ${j}`);let V$,m1=new Promise((S)=>{V$=S});async function ZY(){if(T)return m1;if(T=!0,clearInterval(C),N.close(),O?.stop(!1),H("SIGTERM"),await Promise.race([Promise.all(K.map((S)=>S.exited)),new Promise((S)=>setTimeout(S,3000))]),H("SIGKILL"),await Nw({rpxDir:Y,verbose:W}).catch((S)=>{E("daemon",`DNS teardown failed: ${S}`,W)}),await i1(Y),await P0.unlink(XW(Y)).catch(()=>{}),W)R.info("rpx coordinator stopped");return V$(),m1}let bw=(S)=>{E("daemon",`coordinator received ${S}, shutting down`,W),ZY().catch(()=>{})};return y.once("SIGINT",bw),y.once("SIGTERM",bw),{stop:ZY,done:m1,httpsPort:U,httpPort:X,pidPath:j,ensureCert:(S)=>I?I.ensureCert(S):Promise.resolve(!1)}}function Zq(){let $=y.execPath,w=I$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&y.argv[1])return[$,y.argv[1],"daemon:start"];return[$,"daemon:start"]}async function EF($={}){let w=$.rpxDir??j$(),Y=$.verbose??!1;await $w({rpxDir:w,verbose:Y}).catch((j)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,Y)});let A=await Rw(w);if(A!==null&&p0(A))return E("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)E("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await i1(w);await P0.mkdir(w,{recursive:!0});let U=$.spawnCommand??Zq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${U.join(" ")}`,Y);let X=WF(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??y.cwd(),env:$.spawnEnv?{...y.env,...$.spawnEnv}:y.env});X.unref();let J=null;X.once("error",(j)=>{J=j});let W=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(J)throw J;let j=await Rw(w);if(j!==null&&p0(j))return E("daemon",`daemon registered with pid=${j}`,Y),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,f))}if(J)throw J;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function KF($={}){let w=$.rpxDir??j$(),Y=$.verbose??!1,A=$.timeoutMs??5000,U=$.pollIntervalMs??50,X=$.forceAfterTimeout??!0,J=await Rw(w);if(J===null||!p0(J)){if(J!==null)await i1(w);return await $w({rpxDir:w,verbose:Y}).catch(()=>{}),{stopped:!1,pid:J,forced:!1}}try{y.kill(J,"SIGTERM")}catch(f){if(f.code==="ESRCH")return await i1(w),{stopped:!1,pid:J,forced:!1};throw f}let W=Date.now()+A;while(Date.now()<W){if(!p0(J))return E("daemon",`daemon pid=${J} stopped cleanly`,Y),{stopped:!0,pid:J,forced:!1};await new Promise((f)=>setTimeout(f,U))}if(!X)throw Error(`rpx daemon (pid=${J}) did not exit within ${A}ms`);E("daemon",`daemon pid=${J} did not exit, escalating to SIGKILL`,Y);try{y.kill(J,"SIGKILL")}catch(f){if(f.code!=="ESRCH")throw f}return await i1(w),await Nw({rpxDir:w,verbose:Y}).catch((f)=>{E("daemon",`DNS teardown after SIGKILL: ${f}`,Y)}),{stopped:!0,pid:J,forced:!0}}async function TF($={}){let w=$.rpxDir??j$();if(await EX(w))return;await $w({rpxDir:w,verbose:$.verbose})}fw();f0();import{spawn as xq}from"node:child_process";import*as KX from"node:process";class HF{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){E("start",`Process ${$} is already running`,Y);return}let[A,...U]=w.command.split(" "),X=w.cwd||KX.cwd();E("start",`Starting process ${$}:`,Y),E("start",` Command: ${A} ${U.join(" ")}`,Y),E("start",` Working directory: ${X}`,Y),E("start",` Environment variables: ${R$(w.env)}`,Y);let J=xq(A,U,{cwd:X,env:{...KX.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:J,env:w.env}),new Promise((W,f)=>{if(J.on("error",(B)=>{if(!this.isShuttingDown)E("start",`Process ${$} failed to start: ${B}`,Y),this.processes.delete($),f(B)}),J.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)E("start",`Process ${$} exited with code ${B}; leaving the proxy running`,Y),this.processes.delete($),f(Error(`Process ${$} exited with code ${B}`))}),Y)J.stdout?.on("data",(B)=>{E("process",`[${$}] ${B.toString().trim()}`,!0)}),J.stderr?.on("data",(B)=>{E("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&J.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else E("start",`Process ${$} started successfully`,Y),W()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){E("start",`No process found for ${$}`,w);return}return E("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),E("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){E("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){E("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){E("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,E("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var TX=new HF;f0();import*as l0 from"node:fs/promises";import{homedir as Pq}from"node:os";import*as JW from"node:path";import*as fW from"node:process";var bq=/^[a-zA-Z0-9._-]+$/;function Zw(){return JW.join(Pq(),".stacks","rpx","registry.d")}function c1($){return typeof $==="string"&&$.length>0&&$.length<=128&&bq.test($)}function WW($,w){if(!c1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return JW.join($,`${w}.json`)}function NF($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0,U=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&c1(w.id)&&(A||U)&&typeof w.to==="string"&&w.to.length>0&&X&&Y&&typeof w.createdAt==="string"}async function uq($){await l0.mkdir($,{recursive:!0})}async function qF($,w=Zw(),Y){if(!NF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await uq(w);let A=WW(w,$.id),U=`${A}.tmp.${fW.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await l0.writeFile(U,X,{encoding:"utf8",mode:420}),await l0.rename(U,A),E("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(J){throw await l0.unlink(U).catch(()=>{}),J}}async function RF($,w=Zw(),Y){let A=WW(w,$);try{await l0.unlink(A),E("registry",`removed entry ${$}`,Y)}catch(U){if(U.code!=="ENOENT")throw U}}async function BW($,w=Zw(),Y){let A=WW(w,$);try{let U=await l0.readFile(A,"utf8"),X=JSON.parse(U);if(!NF(X))return E("registry",`entry ${$} failed validation, removing`,Y),await l0.unlink(A).catch(()=>{}),null;return X}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return E("registry",`entry ${$} has invalid JSON, removing`,Y),await l0.unlink(A).catch(()=>{}),null;throw U}}async function MF($=Zw(),w){let Y;try{Y=await l0.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let A=[];for(let U of Y){if(!U.endsWith(".json"))continue;let X=U.slice(0,-5);if(!c1(X))continue;let J=await BW(X,$,w);if(J)A.push(J)}return A}fw();import{execSync as tq}from"node:child_process";import*as LX from"node:http";import*as SF from"node:net";import*as A0 from"node:process";var HX=($,w)=>(Y)=>`\x1B[${$}m${Y}\x1B[${w}m`,y$={bold:HX(1,22),dim:HX(2,22),green:HX(32,39),cyan:HX(36,39)};iJ();nf();fw();hY();f0();import*as IF from"node:fs";import*as yF from"node:path";import*as C$ from"node:process";function iq($,w){let A=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function jW($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,Y=$.registryDir,A=new Set,U=$.proxies.map((G)=>{let F=G.id??iq(G.to,G.path);if(!yY(F))throw Error(`invalid registry id "${F}" derived from to="${G.to}"`);if(A.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return A.add(F),{...G,id:F}}),X=new Date().toISOString();for(let G of U)await i2({id:G.id,from:G.from,to:G.to,path:G.path,pid:$.persistent?void 0:C$.pid,cwd:C$.cwd(),createdAt:X,cleanUrls:G.cleanUrls,changeOrigin:G.changeOrigin,pathRewrites:G.pathRewrites,static:G.static},Y,w);let J=await m2({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let G of U){let F=G.static?`static ${typeof G.static==="string"?G.static:G.static.dir}`:G.from;R.success(`https://${G.to} → ${F}`)}if(R.info(`(via rpx daemon pid=${J.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,f=Y??Hw(),B=U.map((G)=>G.id),j=async()=>{if(W)return;W=!0;for(let G of B)await lf(G,Y,w).catch((F)=>{E("runner",`removeEntry(${G}) failed: ${F}`,w)})},z=(G)=>{E("runner",`received ${G}, unregistering ${B.length} entries`,w),j().finally(()=>C$.exit(0))};C$.once("SIGINT",z),C$.once("SIGTERM",z),C$.once("exit",()=>{if(W)return;for(let G of B)try{IF.unlinkSync(yF.join(f,`${G}.json`))}catch{}}),await new Promise(()=>{})}f0();import{exec as cq}from"node:child_process";import xw from"node:fs";import hF from"node:os";import FW from"node:path";import*as SY from"node:process";import{promisify as vq}from"node:util";var OY=vq(cq);function CF($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var z$=SY.platform==="win32"?FW.join(SY.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",zW=!1;async function NX($){if(SY.platform==="win32")throw Error("Administrator privileges required on Windows");if(rU()){let{stdout:A}=await OY($);return A}let w=Sw(),Y=$.replace(/'/g,"'\\''");try{if(w){let{stdout:A}=await OY(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`);return zW=!0,A}if(zW)try{let{stdout:A}=await OY(`sudo -n sh -c '${Y}'`);return A}catch(A){E("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await OY(`sudo -n sh -c '${Y}'`);return zW=!0,A}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(A){throw Error(`Failed to execute sudo command: ${A.message}`)}}async function _Y($,w){let Y=$.filter((U)=>!CF(U)),A=$.filter((U)=>CF(U));if(A.length>0)E("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,w);if(Y.length===0)return;E("hosts",`Adding hosts: ${Y.join(", ")}`,w),E("hosts",`Using hosts file at: ${z$}`,w);try{let U;try{U=await xw.promises.readFile(z$,"utf-8")}catch{E("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{U=await NX(`cat "${z$}"`)}catch(f){throw console.log(" Could not read hosts file — skipping hosts setup"),E("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let X=Y.filter((f)=>{let B=`127.0.0.1 ${f}`,j=`::1 ${f}`;return!U.includes(B)&&!U.includes(j)});if(X.length===0){E("hosts","All hosts already exist in hosts file",w);return}let J=X.map((f)=>`
|
|
248
263
|
# Added by rpx
|
|
249
|
-
127.0.0.1 ${
|
|
250
|
-
::1 ${
|
|
251
|
-
`),W=
|
|
252
|
-
`),
|
|
264
|
+
127.0.0.1 ${f}
|
|
265
|
+
::1 ${f}`).join(`
|
|
266
|
+
`),W=FW.join(hF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await xw.promises.writeFile(W,U+J,"utf8"),await NX(`cat "${W}" | tee "${z$}" > /dev/null`),console.log(` Hosts updated: ${X.join(", ")}`)}catch(f){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),X.forEach((B)=>{console.log(` 127.0.0.1 ${B}`),console.log(` ::1 ${B}`)}),console.log(` Or run: sudo nano ${z$}`)}finally{try{await xw.promises.unlink(W)}catch{}}}catch(U){E("hosts",`Failed to manage hosts file: ${U.message}`,w)}}async function VF($,w){E("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let Y;try{Y=await xw.promises.readFile(z$,"utf-8")}catch{E("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{Y=await NX(`cat "${z$}"`)}catch(f){throw E("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let A=Y.split(`
|
|
267
|
+
`),U=!1,X=A.filter((f)=>{if($.some((j)=>f.includes(` ${j}`)&&(f.includes("127.0.0.1")||f.includes("::1"))))return U=!0,!1;if(f.trim()==="# Added by rpx")return U=!0,!1;return!0});if(!U){E("hosts","No matching hosts found to remove",w);return}while(X[X.length-1]?.trim()==="")X.pop();let J=`${X.join(`
|
|
253
268
|
`)}
|
|
254
|
-
`,W=
|
|
255
|
-
`,U=(J)=>{let B=J.toLowerCase();return A.has(B)||Y.some((E)=>cf(B,E))},W=(J)=>{let B=NR(J);if(!U(B))return;let E="/";try{E=new URL(J.url).pathname}catch{}if(f.some((j)=>E.startsWith(j)))return;if(J.headers.get(w)===$.value)return;return new Response(X,{status:403,headers:{"content-type":"text/plain"}})};return W.protects=U,W}bf();uf();YA();U0();var UX=new fX,hR="0.12.0",yR=new YX("0.0.0.0"),RA=new Set,bJ=!1,XX=null,cJ=null;async function JX($){if(bJ)return z("cleanup","Cleanup already in progress, skipping",$?.verbose),cJ||Promise.resolve();bJ=!0,z("cleanup","Starting cleanup process",$?.verbose),cJ=new Promise((w)=>{XX=w});try{await UX.stopAll($?.verbose),q.info("Shutting down proxy servers...");let w=[],A=Array.from(RA).map((Y)=>new Promise((f)=>{Y.close(()=>{z("cleanup","Server closed successfully",$?.verbose),f()})}));if(w.push(...A),$?.hosts&&$.domains?.length){z("cleanup","Cleaning up hosts file entries",$?.verbose),z("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let Y=$.domains.filter((f)=>{if(f==="test.local")return!0;return f!=="localhost"&&!f.startsWith("localhost.")&&f!=="127.0.0.1"});if(z("cleanup",`Filtered domains for cleanup: ${JSON.stringify(Y)}`,$?.verbose),Y.length>0)q.info("Cleaning up hosts file entries..."),w.push(OF(Y,$?.verbose).then(()=>{z("cleanup",`Removed hosts entries for ${Y.join(", ")}`,$?.verbose)}).catch((f)=>{z("cleanup",`Failed to remove hosts entries: ${f}`,$?.verbose),q.warn(`Failed to clean up hosts file entries for ${Y.join(", ")}:`,f)}))}if($?.certs&&$.domains?.length){z("cleanup","Cleaning up SSL certificates",$?.verbose),q.info("Cleaning up SSL certificates...");let Y=$.domains.map(async(f)=>{try{await tT(f,$?.verbose),z("cleanup",`Removed certificates for ${f}`,$?.verbose)}catch(X){z("cleanup",`Failed to remove certificates for ${f}: ${X}`,$?.verbose),q.warn(`Failed to clean up certificates for ${f}:`,X)}});w.push(...Y)}await Promise.allSettled(w),z("cleanup","All cleanup tasks completed successfully",$?.verbose),q.success("All cleanup tasks completed successfully")}catch(w){z("cleanup",`Error during cleanup: ${w}`,$?.verbose),q.error("Error during cleanup:",w)}finally{if(XX)XX();XX=null,bJ=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(A0.env.NODE_ENV!=="test"&&A0.env.BUN_ENV!=="test"&&!w)A0.exit(0)}return cJ}var uJ=!1;function nJ($){if(uJ){z("signal",`Received second ${$} signal, forcing exit`,!0),A0.exit(1);return}uJ=!0,z("signal",`Received ${$} signal, initiating cleanup`,!0),JX().catch((w)=>{z("signal",`Cleanup failed after ${$}: ${w}`,!0),A0.exit(1)}).finally(()=>{uJ=!1})}A0.once("SIGINT",()=>nJ("SIGINT"));A0.once("SIGTERM",()=>nJ("SIGTERM"));A0.on("uncaughtException",($)=>{z("process",`Uncaught exception: ${$}`,!0),q.error("Uncaught exception:",$),nJ("uncaughtException")});async function NA($,w,A,Y=5){z("connection",`Testing connection to ${$}:${w} (retries left: ${Y})`,A);let f=15000,X=Date.now();if(A0.env.RPX_BYPASS_CONNECTION_TEST==="true"){z("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let U=()=>new Promise((W,J)=>{let B=ZF.connect({host:$,port:w,timeout:3000});B.once("connect",()=>{z("connection",`Successfully connected to ${$}:${w}`,A),B.end(),W()}),B.once("timeout",()=>{z("connection",`Connection to ${$}:${w} timed out`,A),B.destroy(),J(Error("Connection timed out"))}),B.once("error",(E)=>{z("connection",`Failed to connect to ${$}:${w}: ${E}`,A),B.destroy(),J(E)})});try{await U()}catch(W){if(Date.now()-X>f){z("connection",`Connection test timed out after ${f}ms, but continuing anyway`,A),q.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&Y>0)return z("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${Y} retries left)`,A),await new Promise((B)=>setTimeout(B,2000)),NA($,w,A,Y-1);if(Y>0)try{z("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((B,E)=>{let j=xw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(T)=>{z("connection",`Received HTTP response with status: ${T.statusCode}`,A),B()});j.on("error",(T)=>E(T)),j.on("timeout",()=>{j.destroy(),E(Error("HTTP request timed out"))}),j.end()}),z("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(B){return z("connection",`HTTP request to ${$}:${w} failed: ${B}`,A),z("connection",`Retrying socket connection in 2 seconds... (${Y} retries left)`,A),await new Promise((E)=>setTimeout(E,2000)),NA($,w,A,Y-1)}let J=`Failed to connect to ${$}:${w} after ${5-Y} attempts: ${W.message}`;z("connection",`${J}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),q.warn(J),q.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function xF($){z("server",`Starting server with options: ${E$($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),Y=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),f=[A.hostname];if(vJ($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){z("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await KA(f,$.verbose))[0]){q.info(`Adding ${A.hostname} to hosts file...`),q.info("This may require sudo/administrator privileges");try{await HA(f,$.verbose)}catch(W){if(q.error("Failed to add hosts entry:",W.message),q.warn("You can manually add this entry to your hosts file:"),q.warn(`127.0.0.1 ${A.hostname}`),q.warn(`::1 ${A.hostname}`),A0.platform==="win32")q.warn("On Windows:"),q.warn("1. Run notepad as administrator"),q.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else q.warn("On Unix systems:"),q.warn("sudo nano /etc/hosts")}}else z("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(U){q.error("Failed to check hosts file:",U.message)}}try{await NA(w.hostname,Y,$.verbose)}catch(U){z("server",`Connection test failed: ${U}`,$.verbose),q.error(U.message),q.warn("Continuing with proxy setup despite connection test failure..."),q.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let X=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=wA({...$,to:A.hostname});if(X=await a$({...$,to:A.hostname,https:$.https}),!X){if(z("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await S1({...$,from:w.toString(),to:A.hostname,https:$.https}),X=await a$({...$,to:A.hostname,https:$.https}),!X)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(U){throw z("server",`SSL setup failed: ${U}`,$.verbose),U}z("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await IR({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:Y,sourceUrl:{hostname:w.hostname,host:w.host},ssl:X})}async function MR($,w,A,Y,f,X,U,W,J,B,E){z("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,J);function j(G){let K={};for(let[R,N]of Object.entries(G))if(!R.startsWith(":"))K[R]=N;return K}let T=(G,K)=>{z("request",`Incoming request: ${G.method} ${G.url}`,J);let R=G.url||"/",N=G.method||"GET";if(G instanceof kF.Http2ServerRequest){let S=G.headers;N=S[":method"]||N,R=S[":path"]||R}if(B){if(!R.match(/\.[a-z0-9]+$/i))if(R.endsWith("/"))R=`${R}index.html`;else R=`${R}.html`}let h=j(G.headers);if(E)h.host=`${X.hostname}:${A}`,z("request",`Changed origin: setting host header to ${h.host}`,J);let y={hostname:X.hostname,port:A,path:R,method:N,headers:h};z("request",`Proxy request options: ${E$(y)}`,J);let I=xw.request(y,(S)=>{if(z("response",`Proxy response received with status ${S.statusCode}`,J),B&&S.statusCode===404){let V=[];if(R.endsWith(".html"))V.push(R.slice(0,-5));else if(!R.match(/\.[a-z0-9]+$/i))V.push(`${R}.html`);if(!R.endsWith("/"))V.push(`${R}/index.html`);if(V.length>0){z("cleanUrls",`Trying alternative paths: ${V.join(", ")}`,J);let O=(e0)=>{if(e0.length===0){K.writeHead(S.statusCode||404,S.headers),S.pipe(K);return}let $$=e0[0],S$={...y,path:$$},L$=xw.request(S$,(e$)=>{if(e$.statusCode===200)z("cleanUrls",`Found matching path: ${$$}`,J),K.writeHead(e$.statusCode,e$.headers),e$.pipe(K);else O(e0.slice(1))});L$.on("error",()=>O(e0.slice(1))),L$.end()};O(V);return}}let B0={...S.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};K.writeHead(S.statusCode||500,B0),S.pipe(K)});I.on("error",(S)=>{z("request",`Proxy request failed: ${S}`,J),q.error("Proxy request failed:",S),K.writeHead(502),K.end(`Proxy Error: ${S.message}`)}),G.pipe(I)};if(z("server",`Creating server with SSL config: ${!!U}`,J),U)return new Promise((G,K)=>{try{let R=Bun.serve({port:Y,hostname:f,tls:{key:U.key,cert:U.cert,ca:U.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(N){let h=new URL(N.url);z("request",`Bun.serve received: ${N.method} ${h.pathname}`,J);let y=`http://${X.host}`,I=new URL(h.pathname+h.search,y);try{let S=new Headers(N.headers);if(S.set("host",X.host),E)S.set("origin",y);S.set("x-forwarded-for","127.0.0.1"),S.set("x-forwarded-proto","https"),S.set("x-forwarded-host",w);let B0=await fetch(I.toString(),{method:N.method,headers:S,body:N.body,redirect:"manual"}),V=new Headers(B0.headers);if(B&&h.pathname.endsWith(".html")){let O=h.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:O}})}return new Response(B0.body,{status:B0.status,statusText:B0.statusText,headers:V})}catch(S){return z("request",`Proxy error: ${S}`,J),new Response(`Proxy Error: ${S}`,{status:502})}},error(N){return z("server",`Bun.serve error: ${N}`,J),new Response(`Server Error: ${N.message}`,{status:500})}});RA.add(R),DF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!0,cleanUrls:B,verbose:J}),G()}catch(R){K(R)}});let F=xw.createServer(T);function H(G){return RA.add(G),new Promise((K,R)=>{G.listen(Y,f,()=>{z("server",`Server listening on port ${Y}`,J),DF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!!U,cleanUrls:B,verbose:J}),K()}),G.on("error",(N)=>{z("server",`Server error: ${N}`,J),R(N)})})}return H(F)}async function IR($){z("setup",`Setting up reverse proxy: ${E$($)}`,$.verbose);let{from:w,to:A,fromPort:Y,sourceUrl:f,ssl:X,verbose:U,cleanup:W,vitePluginUsage:J,changeOrigin:B,cleanUrls:E}=$,j=80,T=443,F="0.0.0.0",H=$.portManager||yR,G=vJ($);try{if(G&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await KA([A],U))[0]){q.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await HA([A],U),q.success(`Added ${A} to your hosts file.`)}catch(y){q.error(`Failed to add ${A} to your hosts file: ${y}`),q.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(G&&A0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await KA([A],U))[0]){z("hosts",`${A} not found in hosts file, adding...`,U);try{await HA([A],U)}catch(y){z("hosts",`Failed to add ${A} to hosts file: ${y}`,U)}}}if(X&&!H.usedPorts.has(j)){if(!await kw(j,F,U))z("setup","Starting HTTP redirect server",U),PF(U),H.usedPorts.add(j);else if(z("setup","Port 80 is in use, skipping HTTP redirect",U),U)q.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let K=X?T:j,R=await kw(K,F,U),N;if(R){if(z("setup",`Port ${K} is already in use`,U),U)q.warn(`Port ${K} is already in use. This may be another instance of rpx or another service.`);if(K===443){if(N=await H.getNextAvailablePort(3443,!0),z("setup",`Using port ${N} instead of ${K}`,U),U)q.info(`Using port ${N} instead. Access your site at https://${A}:${N}`)}else if(N=await H.getNextAvailablePort(K+1000,!0),z("setup",`Using port ${N} instead of ${K}`,U),U)q.info(`Using port ${N} instead. Access your site at http://${A}:${N}`)}else N=K,H.usedPorts.add(N),z("setup",`Using standard ${K===443?"HTTPS":"HTTP"} port ${K} for ${A}`,U);await MR(w,A,Y,N,F,f,X,J,U,E,B)}catch(K){z("setup",`Setup failed: ${K}`,U),q.error(`Failed to setup reverse proxy: ${K.message}`),JX({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:U,vitePluginUsage:J})}}function PF($){z("redirect","Starting HTTP redirect server",$);let w=xw.createServer((A,Y)=>{let f=A.headers.host||"";z("redirect",`Redirecting request from ${f}${A.url} to HTTPS`,$),Y.writeHead(301,{Location:`https://${f}${A.url}`}),Y.end()}).listen(80);RA.add(w),z("redirect","HTTP redirect server started",$)}function iF($){let w={...G8,...$};if(z("proxy",`Starting proxy with options: ${E$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){q.error("viaDaemon mode requires both `from` and `to`");return}xJ({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((J)=>{q.error(`Failed to register with rpx daemon: ${J.message}`),A0.exit(1)});return}let A=w.to||"",Y=A.split(".").pop()?.toLowerCase()||"",f=A0.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),X=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(f&&X.includes(Y)&&w?.verbose)q.warn(`The .${Y} TLD may not work reliably for local development`),q.info(` Google owns .${Y} with HSTS preloading, which can bypass local DNS`),q.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(f)Promise.resolve().then(() => (V1(),af)).then(({setupDevelopmentDns:J})=>{J({domains:[A],verbose:w.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(Y))q.success(`DNS server started for .${Y} domains`);else q.success(`DNS server started for .${Y} domains (hosts file entry also added)`)});else z("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((J)=>{z("dns",`Failed to start DNS server: ${J}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:wA(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};z("proxy",`Server options: ${E$(W)}`,w.verbose),xF(W).catch((J)=>{z("proxy",`Failed to start proxy: ${J}`,w.verbose),q.error(`Failed to start proxy: ${J.message}`),JX({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function CR($){return $?.verbose||!1}function vJ($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function bF($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let A=CR(w),Y=vJ(w);if(z("config",`Starting with config: ${E$(w,2)}`,A),z("config",`Is multi-proxy? ${"proxies"in w}`,A),z("config",`Hosts management enabled? ${Y}`,A),w.viaDaemon){let G="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((K)=>({id:K.id,from:K.from,to:K.to,path:K.path,cleanUrls:K.cleanUrls??w.cleanUrls,changeOrigin:K.changeOrigin??w.changeOrigin,pathRewrites:K.pathRewrites})):[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await xJ({proxies:G,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){z("servers",`Found ${w.proxies.length} proxies in config`,A);for(let H of w.proxies)if(H.start){let G=`${H.from}-${H.to}`;try{z("watch",`Starting command for ${G} with command: ${H.start.command}`,A),q.info(`Starting command for ${G}...`),await UX.startProcess(G,H.start,A);let K=new URL(H.from.startsWith("http")?H.from:`http://${H.from}`),R=K.hostname||"localhost",N=Number(K.port)||80;try{await NA(R,N,A),z("watch",`Dev server is ready at ${R}:${N}`,A)}catch(h){z("watch",`Connection check failed, but continuing with proxy setup: ${h}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(K){throw z("watch",`Failed to start command for ${G}: ${K}`,A),Error(`Failed to start command for ${G}: ${K}`)}}else z("watch",`No start command for proxy ${H.from} -> ${H.to}`,A)}else if("start"in w&&w.start){z("watch","Found start command in single proxy config",A);let H=`${w.from}-${w.to}`;try{if(w.start)z("watch",`Starting command: ${w.start.command}`,A),await UX.startProcess(H,w.start,A);let G=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),K=G.hostname||"localhost",R=Number(G.port)||80;try{await NA(K,R,A),z("watch",`Dev server is ready at ${K}:${R}`,A)}catch(N){z("watch",`Connection check failed, but continuing with proxy setup: ${N}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(G){throw z("watch",`Failed to run start command: ${G}`,A),Error(`Failed to run start command: ${G}`)}}else z("watch","No start command found in config",A);let f="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(A0.platform!=="win32"&&(w.https||Y)){if(!Cw())try{z("sudo","Pre-acquiring sudo credentials for privileged operations",A),qR("sudo -v",{stdio:"inherit"})}catch{z("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let H=await a$(w);if(!H){if(z("ssl",`No valid or trusted certificates found for ${f}, generating new ones`,w.verbose),await S1(w),H=await a$(w),!H)throw Error(`Failed to load SSL certificates after generation for ${f}`)}else z("ssl",`Using existing and trusted certificates for ${f}`,w.verbose);w._cachedSSLConfig=H}let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({...H,https:w.https,cleanup:w.cleanup,cleanUrls:H.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:H.changeOrigin??w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig}],U=X.map((H)=>H.to||"rpx.localhost"),W=w._cachedSSLConfig,J=U.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),B=["dev","app","page","new","day","foo"],E=["test","localhost","local","example","invalid"],j=[...new Set(J.map((H)=>H.split(".").pop()?.toLowerCase()))],T=j.filter((H)=>!!H&&B.includes(H));if(T.length>0&&A)q.warn(`The following TLDs may not work reliably for local development: ${T.map((H)=>`.${H}`).join(", ")}`),q.info(" These TLDs have HSTS preloading which can bypass local DNS"),q.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(Y&&A0.platform==="darwin"&&J.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (V1(),af));if(await H({domains:J,verbose:A})){if(A)if(j.every((R)=>!!R&&E.includes(R)))q.success(`DNS server started for ${j.map((R)=>`.${R}`).join(", ")} domains`);else q.success(`DNS server started for ${j.map((R)=>`.${R}`).join(", ")} domains (hosts file entries also added)`)}else z("dns","Could not start DNS server - custom domains may not resolve",A)}let F=async()=>{z("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (V1(),af));await H({verbose:w.verbose})}catch(H){z("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await UX.stopAll(w.verbose)}catch(H){z("cleanup",`Error stopping processes: ${H}`,w.verbose)}await JX({domains:U,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};if(A0.on("SIGINT",F),A0.on("SIGTERM",F),A0.on("uncaughtException",(H)=>{z("process",`Uncaught exception: ${H}`,!0),console.error("Uncaught exception:",H),F()}),W&&X.length>1){z("proxies",`Creating shared HTTPS server for ${X.length} domains`,A);let H=[],G=new Set;for(let V of X){let O=V.to||"rpx.localhost",e0=V.cleanUrls||!1,$$=V.path,S$=L1($$);if(V.static)H.push({host:O,path:$$,route:{static:AA(V.static,e0),cleanUrls:e0,basePath:S$}}),z("proxies",`Route: ${O}${$$??""} → static ${typeof V.static==="string"?V.static:V.static.dir}`,A);else{let L$=new URL(V.from?.startsWith("http")?V.from:`http://${V.from}`);H.push({host:O,path:$$,route:{sourceHost:L$.host,cleanUrls:e0,changeOrigin:V.changeOrigin||!1,pathRewrites:V.pathRewrites,basePath:S$}}),z("proxies",`Route: ${O}${$$??""} → ${L$.host}`,A)}if(G.has(O))continue;if(G.add(O),Y&&!UA(O)&&!O.includes("localhost")&&!O.includes("127.0.0.1"))try{if(!(await KA([O],A))[0])await HA([O],A)}catch{z("hosts",`Could not add hosts entry for ${O}`,A)}}if(!await kw(80,"0.0.0.0",A))PF(A);let R=443;if(await kw(R,"0.0.0.0",A)){if(z("proxies",`Port ${R} is already in use, cannot start shared proxy`,A),A)q.warn(`Port ${R} is in use. Shared HTTPS proxy cannot start.`);return}let h=JA(H),y=fA((V,O)=>WA(h,V,O),A),I=w.originGuard?QF(w.originGuard):null,S=I?(V,O)=>I(V)??y(V,O):y,B0=XA(A);try{let V=Bun.serve({port:R,hostname:"0.0.0.0",tls:{key:W.key,cert:W.cert,ca:W.ca,requestCert:!1,rejectUnauthorized:!1},fetch(O,e0){return S(O,e0)},websocket:B0,error(O){return z("server",`Shared proxy server error: ${O}`,A),new Response(`Server Error: ${O.message}`,{status:500})}});RA.add(V),z("proxies",`Shared HTTPS proxy listening on port ${R} for ${h.size} domains`,A)}catch(V){z("proxies",`Failed to start shared proxy: ${V}`,A),console.error("Failed to start shared HTTPS proxy:",V),F()}}else for(let H of X)try{let G=H.to||"rpx.localhost";z("proxy",`Starting proxy for ${G} with SSL config: ${!!W}`,H.verbose),await xF({from:H.from||"localhost:5173",to:G,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:W,changeOrigin:H.changeOrigin||!1})}catch(G){z("proxies",`Failed to start proxy for ${H.to}: ${G}`,H.verbose),console.error(`Failed to start proxy for ${H.to}:`,G),F()}}function DF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${I$.green(I$.bold("rpx"))} ${I$.green(`v${hR}`)}`),console.log(` ${I$.green("➜")} ${I$.dim($?.from??"")} ${I$.dim("➜")} ${I$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${I$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${I$.green("➜")} Clean URLs enabled`)}$J();var lS=new Iw("rpx",{showTags:!1});function cF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}d0.chdir(LR(SR(VR(import.meta.url)),".."));var t0=new HX("rpx"),uF="0.12.0";t0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async($)=>{if(!$?.from||!$.to)return bF(rw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(Y){console.error("Failed to parse start-env JSON:",Y),d0.exit(1)}w.start=A}return iF(w)});t0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=cF(rw)?rw.proxies.find((Y)=>Y.to===$||`${Y.from}-${Y.to}`===$):rw.to===$?rw:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),d0.exit(1);try{await of.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(Y){console.error(`Failed to start dev server for ${$}:`,Y),d0.exit(1)}});t0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await of.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),d0.exit(1)}});t0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await of.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),d0.exit(1)}});t0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--verbose","Enable verbose logging").action(async($)=>{try{await(await HF({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,verbose:$.verbose??!0})).done,d0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),d0.exit(1)}});t0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,A=await RF({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!A.stopped&&A.pid===null){console.log("rpx daemon is not running");return}if(!A.stopped){console.log(`rpx daemon pid=${A.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${A.pid} stopped${A.forced?" (SIGKILL)":""}`)});t0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??F$(),A=await Kw(w),Y=await sf(w),f=$.registryDir,X=await IF(f).catch(()=>[]);if($.json){console.log(JSON.stringify({running:Y,pid:A,pidFile:Rw(w),rpxDir:w,registryDir:f??Qw(),entries:X},null,2));return}if(!Y){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Rw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Rw(w)}`);if(console.log(`registry: ${f??Qw()}`),X.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${X.length}):`);for(let U of X){let W=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${W})`)}});t0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),d0.exit(1);if(!_1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),d0.exit(1);try{await yF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),d0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await KF({rpxDir:$.rpxDir,verbose:$.verbose}),A=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${A} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),d0.exit(1)}});t0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async($,w)=>{if(!_1($))console.error(`invalid id: ${JSON.stringify($)}`),d0.exit(1);let A=await ZJ($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await MF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});t0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??F$();if(await sf(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await NF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});t0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(uF)});t0.version(uF);t0.help();t0.run();
|
|
269
|
+
`,W=FW.join(hF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await xw.promises.writeFile(W,J,"utf8"),await NX(`cat "${W}" | tee "${z$}" > /dev/null`),E("hosts","Hosts removed successfully",w)}catch(f){E("hosts","Could not clean up hosts file automatically",w)}finally{try{await xw.promises.unlink(W)}catch(f){E("hosts",`Failed to remove temporary file: ${f}`,w)}}}catch(Y){E("hosts",`Failed to clean up hosts file: ${Y.message}`,w)}}async function kY($,w){E("hosts",`Checking hosts: ${$}`,w);let Y;try{Y=await xw.promises.readFile(z$,"utf-8")}catch(A){E("hosts",`Error reading hosts file: ${A}`,w);try{let U=Sw(),X;if(U)X=`echo '${U}' | sudo -S cat "${z$}" 2>/dev/null`;else X=`sudo -n cat "${z$}" 2>/dev/null || cat "${z$}" 2>/dev/null || echo ""`;let{stdout:J}=await OY(X);Y=J}catch(U){return E("hosts",`Cannot read hosts file, assuming entries don't exist: ${U}`,w),$.map(()=>!1)}}return $.map((A)=>{let U=`127.0.0.1 ${A}`,X=`::1 ${A}`;return Y.includes(U)||Y.includes(X)})}YX();f0();import*as qX from"node:net";function Iw($,w,Y){return E("port",`Checking if port ${$} is in use on ${w}`,Y),new Promise((A)=>{let U=qX.createServer(),X=setTimeout(()=>{E("port",`Checking port ${$} timed out, assuming it's in use`,Y),U.close(),A(!0)},3000);U.once("error",(J)=>{if(clearTimeout(X),J.code==="EADDRINUSE")E("port",`Port ${$} is in use`,Y),A(!0);else E("port",`Error checking port ${$}: ${J.message}`,Y),A(!0)}),U.once("listening",()=>{clearTimeout(X),E("port",`Port ${$} is available`,Y),U.close(),A(!1)});try{U.listen($,w)}catch(J){clearTimeout(X),E("port",`Exception checking port ${$}: ${J}`,Y),A(!0)}})}async function mq($,w,Y,A=50){E("port",`Finding available port starting from ${$} (max attempts: ${A})`,Y);let U=$,X=0;while(X<A){if(X++,!await Iw(U,w,Y))return E("port",`Found available port: ${U} after ${X} attempts`,Y),U;E("port",`Port ${U} is in use, trying ${U+1} (attempt ${X}/${A})`,Y),U++}throw Error(`Unable to find available port after ${A} attempts starting from ${$}`)}function LF($,w,Y=5000,A){return E("port",`Testing connection to ${w}:${$}`,A),new Promise((U)=>{let X=qX.connect({host:w,port:$,timeout:Y});X.once("connect",()=>{E("port",`Successfully connected to ${w}:${$}`,A),X.end(),U(!0)}),X.once("timeout",()=>{E("port",`Connection to ${w}:${$} timed out`,A),X.destroy(),U(!1)}),X.once("error",(J)=>{E("port",`Failed to connect to ${w}:${$}: ${J.message}`,A),X.destroy(),U(!1)})})}class RX{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,Y=50){this.hostname=$,this.verbose=w,this.maxRetries=Y}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Iw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await LF($,this.hostname,3000,this.verbose))return E("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let Y=await mq($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await LF(Y,this.hostname,3000,this.verbose))if(Y<$+this.maxRetries)return this.findNextAvailablePort(Y+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort($){E("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var l3=new RX;fw();f0();import{spawn as dq}from"node:child_process";import*as MX from"node:process";class IX{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){E("start",`Process ${$} is already running`,Y);return}let[A,...U]=w.command.split(" "),X=w.cwd||MX.cwd();E("start",`Starting process ${$}:`,Y),E("start",` Command: ${A} ${U.join(" ")}`,Y),E("start",` Working directory: ${X}`,Y),E("start",` Environment variables: ${R$(w.env)}`,Y);let J=dq(A,U,{cwd:X,env:{...MX.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:J,env:w.env}),new Promise((W,f)=>{if(J.on("error",(B)=>{if(!this.isShuttingDown)E("start",`Process ${$} failed to start: ${B}`,Y),this.processes.delete($),f(B)}),J.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)E("start",`Process ${$} exited with code ${B}; leaving the proxy running`,Y),this.processes.delete($),f(Error(`Process ${$} exited with code ${B}`))}),Y)J.stdout?.on("data",(B)=>{E("process",`[${$}] ${B.toString().trim()}`,!0)}),J.stderr?.on("data",(B)=>{E("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&J.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else E("start",`Process ${$} started successfully`,Y),W()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){E("start",`No process found for ${$}`,w);return}return E("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),E("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){E("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){E("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){E("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,E("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var a3=new IX;import{timingSafeEqual as gq}from"node:crypto";function lq($,w){if($==null)return!1;let Y=Buffer.from($),A=Buffer.from(w);if(Y.length!==A.length)return!1;return gq(Y,A)}function yX($){return $.toLowerCase().replace(/\.$/,"")}var nq=["/.well-known/acme-challenge/"];function pq($){let w=$.headers.get("host");if(w)return yX(w.split(":")[0]);try{return yX(new URL($.url).hostname)}catch{return""}}function QF($){let w=$.header.toLowerCase(),Y=new Set,A=[];for(let f of $.hosts){let B=yX(f);if(B.startsWith("*."))A.push(B);else Y.add(B)}let U=$.exemptPaths??nq,X=$.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
|
|
270
|
+
`,J=(f)=>{let B=yX(f);return Y.has(B)||A.some((j)=>XX(B,j))},W=(f)=>{let B=pq(f);if(!J(B))return;let j="/";try{j=new URL(f.url).pathname}catch{}if(U.some((z)=>j.startsWith(z)))return;if(lq(f.headers.get(w),$.value))return;return new Response(X,{status:403,headers:{"content-type":"text/plain"}})};return W.protects=J,W}UX();JX();fX();qY();f0();var hX=new IX,rq="0.12.0",aq=new RX("0.0.0.0"),VX=new Set,GW=!1,CX=null,EW=null;async function QX($){if(GW)return E("cleanup","Cleanup already in progress, skipping",$?.verbose),EW||Promise.resolve();GW=!0,E("cleanup","Starting cleanup process",$?.verbose),EW=new Promise((w)=>{CX=w});try{await hX.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],Y=Array.from(VX).map((A)=>new Promise((U)=>{let X=A;try{if(typeof X.stop==="function")X.stop(!0),E("cleanup","Bun server stopped",$?.verbose),U();else if(typeof X.close==="function")X.close(()=>{E("cleanup","Server closed successfully",$?.verbose),U()});else U()}catch(J){E("cleanup",`Error stopping server: ${J}`,$?.verbose),U()}}));if(w.push(...Y),VX.clear(),$?.hosts&&$.domains?.length){E("cleanup","Cleaning up hosts file entries",$?.verbose),E("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let A=$.domains.filter((U)=>{if(U==="test.local")return!0;return U!=="localhost"&&!U.startsWith("localhost.")&&U!=="127.0.0.1"});if(E("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,$?.verbose),A.length>0)R.info("Cleaning up hosts file entries..."),w.push(VF(A,$?.verbose).then(()=>{E("cleanup",`Removed hosts entries for ${A.join(", ")}`,$?.verbose)}).catch((U)=>{E("cleanup",`Failed to remove hosts entries: ${U}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,U)}))}if($?.certs&&$.domains?.length){E("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let A=$.domains.map(async(U)=>{try{await M2(U,$?.verbose),E("cleanup",`Removed certificates for ${U}`,$?.verbose)}catch(X){E("cleanup",`Failed to remove certificates for ${U}: ${X}`,$?.verbose),R.warn(`Failed to clean up certificates for ${U}:`,X)}});w.push(...A)}await Promise.allSettled(w),E("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){E("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(CX)CX();CX=null,GW=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(A0.env.NODE_ENV!=="test"&&A0.env.BUN_ENV!=="test"&&!w)A0.exit(0)}return EW}var KW=!1;function _F($){if(KW){E("signal",`Received second ${$} signal, forcing exit`,!0),A0.exit(1);return}KW=!0,E("signal",`Received ${$} signal, initiating cleanup`,!0),QX().catch((w)=>{E("signal",`Cleanup failed after ${$}: ${w}`,!0),A0.exit(1)}).finally(()=>{KW=!1})}A0.once("SIGINT",()=>_F("SIGINT"));A0.once("SIGTERM",()=>_F("SIGTERM"));A0.on("uncaughtException",($)=>{R.error("Uncaught exception (continuing):",$)});A0.on("unhandledRejection",($)=>{R.error("Unhandled rejection (continuing):",$)});async function DY($,w,Y,A=5){E("connection",`Testing connection to ${$}:${w} (retries left: ${A})`,Y);let U=15000,X=Date.now();if(A0.env.RPX_BYPASS_CONNECTION_TEST==="true"){E("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let J=()=>new Promise((W,f)=>{let B=SF.connect({host:$,port:w,timeout:3000});B.once("connect",()=>{E("connection",`Successfully connected to ${$}:${w}`,Y),B.end(),W()}),B.once("timeout",()=>{E("connection",`Connection to ${$}:${w} timed out`,Y),B.destroy(),f(Error("Connection timed out"))}),B.once("error",(j)=>{E("connection",`Failed to connect to ${$}:${w}: ${j}`,Y),B.destroy(),f(j)})});try{await J()}catch(W){let f=W;if(Date.now()-X>U){E("connection",`Connection test timed out after ${U}ms, but continuing anyway`,Y),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(f.code==="ECONNREFUSED"&&A>0)return E("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((j)=>setTimeout(j,2000)),DY($,w,Y,A-1);if(A>0)try{E("connection",`Trying HTTP request to ${$}:${w}`,Y),await new Promise((j,z)=>{let G=LX.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(F)=>{E("connection",`Received HTTP response with status: ${F.statusCode}`,Y),j()});G.on("error",(F)=>z(F)),G.on("timeout",()=>{G.destroy(),z(Error("HTTP request timed out"))}),G.end()}),E("connection",`HTTP request to ${$}:${w} succeeded`,Y);return}catch(j){return E("connection",`HTTP request to ${$}:${w} failed: ${j}`,Y),E("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),DY($,w,Y,A-1)}let B=`Failed to connect to ${$}:${w} after ${5-A} attempts: ${f.message}`;E("connection",`${B}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),R.warn(B),R.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function kF($){E("server",`Starting server with options: ${R$($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),Y=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),A=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),U=[Y.hostname];if(HW($)&&!Y.hostname.includes("localhost")&&!Y.hostname.includes("127.0.0.1")){E("hosts",`Checking if hosts file entry exists for: ${Y.hostname}`,$?.verbose);try{if(!(await kY(U,$.verbose))[0]){R.info(`Adding ${Y.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await _Y(U,$.verbose)}catch(W){if(R.error("Failed to add hosts entry:",W.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${Y.hostname}`),R.warn(`::1 ${Y.hostname}`),A0.platform==="win32")R.warn("On Windows:"),R.warn("1. Run notepad as administrator"),R.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else R.warn("On Unix systems:"),R.warn("sudo nano /etc/hosts")}}else E("hosts",`Host entry already exists for ${Y.hostname}`,$.verbose)}catch(J){R.error("Failed to check hosts file:",J.message)}}try{await DY(w.hostname,A,$.verbose)}catch(J){E("server",`Connection test failed: ${J}`,$.verbose),R.error(J.message),R.warn("Continuing with proxy setup despite connection test failure..."),R.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let X=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=TY({...$,to:Y.hostname});if(X=await a$({...$,to:Y.hostname,https:$.https}),!X){if(E("ssl",`Generating new certificates for ${Y.hostname}`,$.verbose),await O1({...$,from:w.toString(),to:Y.hostname,https:$.https}),X=await a$({...$,to:Y.hostname,https:$.https}),!X)throw Error(`Failed to load SSL configuration after generating certificates for ${Y.hostname}`)}}catch(J){throw E("server",`SSL setup failed: ${J}`,$.verbose),J}E("server",`Setting up reverse proxy with SSL config for ${Y.hostname}`,$.verbose),await oq({...$,from:$.from||"localhost:5173",to:Y.hostname,fromPort:A,sourceUrl:{hostname:w.hostname,host:w.host},ssl:X})}async function sq($,w,Y,A,U,X,J,W,f){E("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${W}`,J);let B=[{host:w,route:{sourceHost:A.host,cleanUrls:W||!1,changeOrigin:f||!1,basePath:"/"}}];if(!TW({routeEntries:B,listenPort:Y,sslConfig:U,originGuard:null,verbose:J??!1}))throw Error(`Failed to start proxy server for ${w} on port ${Y}`);$R({from:$,to:w,vitePluginUsage:X,listenPort:Y,ssl:!!U,cleanUrls:W,verbose:J})}async function oq($){E("setup",`Setting up reverse proxy: ${R$($)}`,$.verbose);let{from:w,to:Y,sourceUrl:A,ssl:U,verbose:X,cleanup:J,vitePluginUsage:W,changeOrigin:f,cleanUrls:B}=$,j=80,z=443,G="0.0.0.0",F=$.portManager||aq,T=HW($);try{if(T&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1")){if(!(await kY([Y],X))[0]){R.warn(`The hostname ${Y} isn't in your hosts file. Adding it now...`);try{await _Y([Y],X),R.success(`Added ${Y} to your hosts file.`)}catch(I){R.error(`Failed to add ${Y} to your hosts file: ${I}`),R.info(`You may need to manually add '127.0.0.1 ${Y}' to your /etc/hosts file.`)}}}else if(T&&A0.platform!=="darwin"&&Y&&Y.includes("localhost")&&!Y.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await kY([Y],X))[0]){E("hosts",`${Y} not found in hosts file, adding...`,X);try{await _Y([Y],X)}catch(I){E("hosts",`Failed to add ${Y} to hosts file: ${I}`,X)}}}if(U&&!F.usedPorts.has(j)){if(!await Iw(j,G,X))E("setup","Starting HTTP redirect server",X),DF(X),F.usedPorts.add(j);else if(E("setup","Port 80 is in use, skipping HTTP redirect",X),X)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let K=U?z:j,H=await Iw(K,G,X),q;if(H){if(E("setup",`Port ${K} is already in use`,X),X)R.warn(`Port ${K} is already in use. This may be another instance of rpx or another service.`);if(K===443){if(q=await F.getNextAvailablePort(3443,!0),E("setup",`Using port ${q} instead of ${K}`,X),X)R.info(`Using port ${q} instead. Access your site at https://${Y}:${q}`)}else if(q=await F.getNextAvailablePort(K+1000,!0),E("setup",`Using port ${q} instead of ${K}`,X),X)R.info(`Using port ${q} instead. Access your site at http://${Y}:${q}`)}else q=K,F.usedPorts.add(q),E("setup",`Using standard ${K===443?"HTTPS":"HTTP"} port ${K} for ${Y}`,X);await sq(w,Y,q,A,U,W,X,B,f)}catch(K){E("setup",`Setup failed: ${K}`,X),R.error(`Failed to setup reverse proxy: ${K.message}`),QX({domains:[Y],hosts:typeof J==="boolean"?J:J?.hosts,certs:typeof J==="boolean"?J:J?.certs,verbose:X,vitePluginUsage:W})}}function DF($,w=80,Y=443){E("redirect",`Starting HTTP redirect server on port ${w}`,$);let A=LX.createServer((U,X)=>{let J=U.headers.host||"",W=J.includes(":")?J.slice(0,J.indexOf(":")):J,f=Y===443?W:`${W}:${Y}`;E("redirect",`Redirecting request from ${J}${U.url} to https://${f}`,$),X.writeHead(301,{Location:`https://${f}${U.url}`}),X.end()}).listen(w);VX.add(A),E("redirect","HTTP redirect server started",$)}function ZF($){let w={...uJ,...$};if(E("proxy",`Starting proxy with options: ${R$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}jW({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((f)=>{R.error(`Failed to register with rpx daemon: ${f.message}`),A0.exit(1)});return}let Y=w.to||"",A=Y.split(".").pop()?.toLowerCase()||"",U=A0.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),X=["dev","app","page","new","day","foo"],J=["test","localhost","local","example","invalid"];if(U&&X.includes(A)&&w?.verbose)R.warn(`The .${A} TLD may not work reliably for local development`),R.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),R.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(U)Promise.resolve().then(() => (b1(),GX)).then(({setupDevelopmentDns:f})=>{f({domains:[Y],verbose:w.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if(w.verbose)if(J.includes(A))R.success(`DNS server started for .${A} domains`);else R.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else E("dns",`Could not start DNS server - ${Y} may not resolve in browser`,w.verbose)})}).catch((f)=>{E("dns",`Failed to start DNS server: ${f}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:TY(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};E("proxy",`Server options: ${R$(W)}`,w.verbose),kF(W).catch((f)=>{E("proxy",`Failed to start proxy: ${f}`,w.verbose),R.error(`Failed to start proxy: ${f.message}`),QX({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function eq($){return $?.verbose||!1}function HW($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function xF($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let Y=eq(w),A=HW(w);if(E("config",`Starting with config: ${R$(w,2)}`,Y),E("config",`Is multi-proxy? ${"proxies"in w}`,Y),E("config",`Hosts management enabled? ${A}`,Y),w.viaDaemon){let C="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((O)=>({id:O.id,from:O.from,to:O.to,path:O.path,cleanUrls:O.cleanUrls??w.cleanUrls,changeOrigin:O.changeOrigin??w.changeOrigin,pathRewrites:O.pathRewrites})):[{id:w.id,from:w.from,to:w.to??"rpx.localhost",path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await jW({proxies:C,verbose:Y});return}if("proxies"in w&&Array.isArray(w.proxies)){E("servers",`Found ${w.proxies.length} proxies in config`,Y);for(let N of w.proxies)if(N.start){let C=`${N.from}-${N.to}`;try{E("watch",`Starting command for ${C} with command: ${N.start.command}`,Y),R.info(`Starting command for ${C}...`),await hX.startProcess(C,N.start,Y);let O=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`),p=O.hostname||"localhost",x0=Number(O.port)||80;try{await DY(p,x0,Y),E("watch",`Dev server is ready at ${p}:${x0}`,Y)}catch(h$){E("watch",`Connection check failed, but continuing with proxy setup: ${h$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(O){throw E("watch",`Failed to start command for ${C}: ${O}`,Y),Error(`Failed to start command for ${C}: ${O}`)}}else E("watch",`No start command for proxy ${N.from} -> ${N.to}`,Y)}else if("start"in w&&w.start){E("watch","Found start command in single proxy config",Y);let N=`${w.from}-${w.to}`;try{if(w.start)E("watch",`Starting command: ${w.start.command}`,Y),await hX.startProcess(N,w.start,Y);let C=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),O=C.hostname||"localhost",p=Number(C.port)||80;try{await DY(O,p,Y),E("watch",`Dev server is ready at ${O}:${p}`,Y)}catch(x0){E("watch",`Connection check failed, but continuing with proxy setup: ${x0}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(C){throw E("watch",`Failed to run start command: ${C}`,Y),Error(`Failed to run start command: ${C}`)}}else E("watch","No start command found in config",Y);let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(A0.platform!=="win32"&&(w.https||A)){if(!Sw())try{E("sudo","Pre-acquiring sudo credentials for privileged operations",Y),tq("sudo -v",{stdio:"inherit"})}catch{E("sudo","Could not pre-acquire sudo credentials",Y)}}let X=[];if(w.productionCerts){if(X=await x1(w.productionCerts,Y),X.length>0)E("ssl",`Using ${X.length} production SNI cert(s): ${X.map((N)=>N.serverName).join(", ")}`,Y)}if(w.https){let N=X.length>0?null:await a$(w);if(!N&&X.length===0){if(E("ssl",`No valid or trusted certificates found for ${U}, generating new ones`,w.verbose),await O1(w),N=await a$(w),!N)throw Error(`Failed to load SSL certificates after generation for ${U}`)}else E("ssl",`Using existing and trusted certificates for ${U}`,w.verbose);w._cachedSSLConfig=N}let J="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((N)=>({...N,https:w.https,cleanup:w.cleanup,cleanUrls:N.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:N.changeOrigin??w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig}],W=J.map((N)=>N.to||"rpx.localhost"),f=X.length>0?X:w._cachedSSLConfig??null,B=W.filter((N)=>N&&!N.includes("localhost")&&!N.includes("127.0.0.1")),j=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"],G=[...new Set(B.map((N)=>N.split(".").pop()?.toLowerCase()))],F=G.filter((N)=>!!N&&j.includes(N));if(F.length>0&&Y)R.warn(`The following TLDs may not work reliably for local development: ${F.map((N)=>`.${N}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&A0.platform==="darwin"&&B.length>0){let{setupDevelopmentDns:N}=await Promise.resolve().then(() => (b1(),GX));if(await N({domains:B,verbose:Y})){if(Y)if(G.every((p)=>!!p&&z.includes(p)))R.success(`DNS server started for ${G.map((p)=>`.${p}`).join(", ")} domains`);else R.success(`DNS server started for ${G.map((p)=>`.${p}`).join(", ")} domains (hosts file entries also added)`)}else E("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{E("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:N}=await Promise.resolve().then(() => (b1(),GX));await N({verbose:w.verbose})}catch(N){E("cleanup",`Error stopping DNS server: ${N}`,w.verbose)}try{await hX.stopAll(w.verbose)}catch(N){E("cleanup",`Error stopping processes: ${N}`,w.verbose)}await QX({domains:W,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};A0.on("SIGINT",T),A0.on("SIGTERM",T);let K=w.singlePortMode===!0,H=w.httpsPort??443,q=w.httpPort??80,M=w.originGuard?QF(w.originGuard):null,I=!!f&&(J.length>1||K),h=!f&&K&&J.length>0;if(I&&f){E("proxies",`Creating shared HTTPS server for ${J.length} domains on port ${H}`,Y);let N=await OF(J,A,Y);if(!await Iw(q,"0.0.0.0",Y))DF(Y,q,H);if(await Iw(H,"0.0.0.0",Y)){if(E("proxies",`Port ${H} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${H} is in use. Shared HTTPS proxy cannot start.`);return}if(!TW({routeEntries:N,listenPort:H,sslConfig:f,originGuard:M,verbose:Y})){R.error(`Shared HTTPS proxy failed to bind :${H}; not exiting`);return}}else if(h){E("proxies",`Creating shared HTTP server for ${J.length} domains on port ${q}`,Y);let N=await OF(J,A,Y);if(await Iw(q,"0.0.0.0",Y)){if(E("proxies",`Port ${q} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${q} is in use. Shared HTTP proxy cannot start.`);return}if(!TW({routeEntries:N,listenPort:q,sslConfig:null,originGuard:M,verbose:Y})){R.error(`Shared HTTP proxy failed to bind :${q}; not exiting`);return}}else for(let N of J)try{let C=N.to||"rpx.localhost";E("proxy",`Starting proxy for ${C} with SSL config: ${!!f}`,N.verbose),await kF({from:N.from||"localhost:5173",to:C,cleanUrls:N.cleanUrls||!1,https:N.https||!1,cleanup:N.cleanup||!1,vitePluginUsage:N.vitePluginUsage||!1,verbose:N.verbose||!1,_cachedSSLConfig:w._cachedSSLConfig,changeOrigin:N.changeOrigin||!1})}catch(C){E("proxies",`Failed to start proxy for ${N.to}: ${C}`,N.verbose),R.error(`Failed to start proxy for ${N.to}:`,C)}}async function OF($,w,Y){let A=[],U=new Set;for(let X of $){let J=X.to||"rpx.localhost",W=X.cleanUrls||!1,f=X.path,B=k1(f);if(X.static)A.push({host:J,path:f,route:{static:NY(X.static,W),cleanUrls:W,basePath:B}}),E("proxies",`Route: ${J}${f??""} → static ${typeof X.static==="string"?X.static:X.static.dir}`,Y);else{let j=new URL(X.from?.startsWith("http")?X.from:`http://${X.from}`);A.push({host:J,path:f,route:{sourceHost:j.host,cleanUrls:W,changeOrigin:X.changeOrigin||!1,pathRewrites:X.pathRewrites,basePath:B}}),E("proxies",`Route: ${J}${f??""} → ${j.host}`,Y)}if(U.has(J))continue;if(U.add(J),w&&!RY(J)&&!J.includes("localhost")&&!J.includes("127.0.0.1"))try{if(!(await kY([J],Y))[0])await _Y([J],Y)}catch{E("hosts",`Could not add hosts entry for ${J}`,Y)}}return A}function TW($){let{routeEntries:w,listenPort:Y,sslConfig:A,originGuard:U,verbose:X}=$,J=D1(w),W=S1((j,z)=>Z1(J,j,z),X),f=U?(j,z)=>U(j)??W(j,z):W,B=_1(X);try{let j=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:C1(),...A?{tls:Array.isArray(A)?A.map((z)=>({serverName:z.serverName,key:z.key,cert:z.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(z,G){return f(z,G)},websocket:B,error(z){return E("server",`Shared proxy server error: ${z}`,X),new Response(`Server Error: ${z.message}`,{status:500})}});return VX.add(j),E("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${J.size} domains`,X),j}catch(j){return E("proxies",`Failed to start shared proxy: ${j}`,X),console.error("Failed to start shared proxy:",j),null}}function $R($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${y$.green(y$.bold("rpx"))} ${y$.green(`v${rq}`)}`),console.log(` ${y$.green("➜")} ${y$.dim($?.from??"")} ${y$.dim("➜")} ${y$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${y$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${y$.green("➜")} Clean URLs enabled`)}yf();var IL=new Ow("rpx",{showTags:!1});function PF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}n0.chdir(YR(wR(AR(import.meta.url)),".."));var r0=new bX("rpx"),bF="0.12.0";r0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async($)=>{if(!$?.from||!$.to)return xF(sw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,singlePortMode:$.singlePortMode||!1,httpPort:$.httpPort!==void 0?Number($.httpPort):void 0,httpsPort:$.httpsPort!==void 0?Number($.httpsPort):void 0,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let Y={command:$.startCommand};if($.startCwd)Y.cwd=$.startCwd;if($.startEnv)try{Y.env=JSON.parse($.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),n0.exit(1)}w.start=Y}return ZF(w)});r0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let Y=PF(sw)?sw.proxies.find((A)=>A.to===$||`${A.from}-${A.to}`===$):sw.to===$?sw:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${$}`),n0.exit(1);try{await TX.startProcess($,Y.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(A){console.error(`Failed to start dev server for ${$}:`,A),n0.exit(1)}});r0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await TX.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(Y){console.error(`Failed to stop dev server for ${$}:`,Y),n0.exit(1)}});r0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await TX.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),n0.exit(1)}});r0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--verbose","Enable verbose logging").action(async($)=>{try{await(await GF({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,verbose:$.verbose??!0})).done,n0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),n0.exit(1)}});r0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,Y=await KF({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});r0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??j$(),Y=await Rw(w),A=await EX(w),U=$.registryDir,X=await MF(U).catch(()=>[]);if($.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:Mw(w),rpxDir:w,registryDir:U??Zw(),entries:X},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${Mw(w)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${Mw(w)}`);if(console.log(`registry: ${U??Zw()}`),X.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${X.length}):`);for(let J of X){let W=J.pid!==void 0?`, pid=${J.pid}`:"";console.log(` https://${J.to} \u2192 ${J.from} (id=${J.id}${W})`)}});r0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),n0.exit(1);if(!c1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),n0.exit(1);try{await qF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),n0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await EF({rpxDir:$.rpxDir,verbose:$.verbose}),Y=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${Y} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),n0.exit(1)}});r0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async($,w)=>{if(!c1($))console.error(`invalid id: ${JSON.stringify($)}`),n0.exit(1);let Y=await BW($,w.registryDir,w.verbose);if(!Y){console.log(`no registry entry for id=${$}`);return}await RF($,w.registryDir,w.verbose),console.log(`unregistered ${Y.to} (id=${$})`)});r0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??j$();if(await EX(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await TF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});r0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(bF)});r0.version(bF);r0.help();r0.run();
|