@stacksjs/rpx 0.11.39 → 0.11.40

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 CHANGED
@@ -1,22 +1,22 @@
1
1
  #!/usr/bin/env bun
2
- import{createRequire as d6}from"node:module";var v6=Object.defineProperty;var m6=(w)=>w;function g6(w,$){this[w]=m6.bind(null,$)}var tj=(w,$)=>{for(var Y in $)v6(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:g6.bind($,Y)})};var a=(w,$)=>()=>(w&&($=w(w=0)),$);var i=d6(import.meta.url);import{existsSync as zQ,statSync as BQ}from"fs";import{existsSync as tG,mkdirSync as DM,readdirSync as xM,readFileSync as aG,writeFileSync as kM}from"fs";import{homedir as t$}from"os";import{dirname as iM,resolve as Aw}from"path";import DA from"process";import{existsSync as GQ,statSync as EQ}from"fs";import{existsSync as DJ,mkdirSync as sG,readdirSync as oG,writeFileSync as eG}from"fs";import{homedir as a$}from"os";import{dirname as KQ,resolve as v0}from"path";import _$ from"process";import{join as w5,relative as $5,resolve as FQ}from"path";import qA from"process";import{existsSync as eQ,mkdirSync as pM,readdirSync as rM,writeFileSync as tM}from"fs";import{homedir as BJ}from"os";import{dirname as oM,resolve as c0}from"path";import s1 from"process";import{join as Y5,relative as A5,resolve as TQ}from"path";import HA from"process";import{existsSync as wf,mkdirSync as Ay,readdirSync as Xy,writeFileSync as Jy}from"fs";import{dirname as Wy,resolve as RA}from"path";import xJ from"process";import{Buffer as Q$}from"buffer";import{createCipheriv as X5,createDecipheriv as J5,randomBytes as GJ}from"crypto";import{closeSync as EJ,createReadStream as NQ,createWriteStream as U5,existsSync as KJ,fsyncSync as qQ,openSync as HQ,writeFileSync as W5}from"fs";import{access as j5,constants as RQ,mkdir as Q5,readdir as eY,rename as MQ,stat as s$,unlink as wA,writeFile as FJ}from"fs/promises";import{join as o$}from"path";import L0 from"process";import{pipeline as f5}from"stream/promises";import{createGzip as yQ}from"zlib";import e$ from"process";import bw from"process";import{Buffer as Pw}from"buffer";import{createCipheriv as z5,createDecipheriv as B5,randomBytes as TJ}from"crypto";import{closeSync as NJ,createReadStream as IQ,createWriteStream as G5,existsSync as $A,fsyncSync as CQ,openSync as VQ,writeFileSync as E5}from"fs";import{access as K5,constants as LQ,mkdir as F5,readdir as YA,rename as SQ,stat as w1,unlink as AA,writeFile as qJ}from"fs/promises";import{isAbsolute as T5,join as $1,resolve as N5}from"path";import x from"process";import{pipeline as q5}from"stream/promises";import{createGzip as hQ}from"zlib";import Y1 from"process";import uw from"process";import XA from"process";import{existsSync as JA}from"fs";import{resolve as HJ}from"path";import{existsSync as H5}from"fs";import{existsSync as R5,readdirSync as M5}from"fs";import{extname as RJ,resolve as OQ}from"path";import y5 from"process";import{join as I5,relative as C5,resolve as _Q}from"path";import MA from"process";import{Buffer as iw}from"buffer";import{createCipheriv as V5,createDecipheriv as L5,randomBytes as MJ}from"crypto";import{closeSync as yJ,createReadStream as DQ,createWriteStream as S5,existsSync as UA,fsyncSync as xQ,openSync as kQ,writeFileSync as h5}from"fs";import{access as O5,constants as ZQ,mkdir as _5,readdir as WA,rename as PQ,stat as A1,unlink as jA,writeFile as IJ}from"fs/promises";import{isAbsolute as D5,join as X1,resolve as x5}from"path";import k from"process";import{pipeline as k5}from"stream/promises";import{createGzip as iQ}from"zlib";import J1 from"process";import cw from"process";import fA from"process";import{existsSync as zA}from"fs";import{resolve as OJ}from"path";import{existsSync as wK}from"fs";class sQ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!zQ(w))return!0;return BQ(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=zQ(Y)?BQ(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class oQ{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function i5(w,$){this[w]=P5.bind(null,$)}class nJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!GQ(w))return!0;return EQ(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=GQ(Y)?EQ(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class lJ{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function c5(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function v5(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function m5(w){return w.getStats().size*2}function pJ(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&$0($[0])&&"id"in $[0]&&$[0].id===3&&$0($[1])&&"id"in $[1]&&$[1].id===4)return $;if($0($)&&$0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if($0(w)&&"arr"in w&&Array.isArray(w.arr)&&$0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&$0($[0])&&$0(w[0])){let A=[...$];for(let X of w)if($0(X)&&"name"in X){if(!A.find((U)=>$0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if($0(X)&&"path"in X){if(!A.find((U)=>$0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>yA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!$0($)||!$0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if($0(X)&&$0(Y[A]))Y[A]=pJ(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&$0(X[0])&&$0(Y[A][0])){let J=[...X];for(let U of Y[A])if($0(U)&&"name"in U){if(!J.find((W)=>$0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if($0(U)&&"path"in U){if(!J.find((W)=>$0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>yA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function yA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!yA(w[Y],$[Y]))return!1;return!0}if($0(w)&&$0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!yA(w[X],$[X]))return!1}return!0}return!1}function $0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function g5(w,$){if(!wf(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return pJ($,A)}catch{return null}}catch{return null}}async function d5({name:w="",cwd:$,defaultConfig:Y}){let A=$||xJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=RA(A,`${U}${j}`),Q=await g5(W,Y);if(Q!==null)return Q}try{let U=RA(A,"package.json");if(wf(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return pJ(Y,W)}catch{}}}catch{}return Y}function n5(w,$={}){let Y=HA.cwd();while(Y.includes("storage"))Y=TQ(Y,"..");let A=TQ(Y,w||"");if($?.relative)return A5(HA.cwd(),A);return A}async function l5(){try{let w=await d5({name:"clarity",defaultConfig:EA,cwd:HA.cwd(),endpoint:"",headers:{}});return{...EA,...w}}catch{return EA}}function U0(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function p5(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bw<"u"){let w=bw.type;if(w==="renderer"||w==="worker")return!1;return!!(bw.versions&&(bw.versions.node||bw.versions.bun))}return!1}class Yf{async format(w){let $=await p5(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:e$.pid,hostname:$(),environment:e$.env.NODE_ENV||"development",platform:e$.platform,version:e$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:e$.env.NODE_ENV||e$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class IA{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=w,this.config={...ZJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Yf,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...KA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...KA};return{...KA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:ZJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await j5(this.config.logDirectory,RQ.F_OK|RQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await Q5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:Q$.from(w);try{if(!KJ(this.currentLogFile))await FJ(this.currentLogFile,"",{mode:420});if(X=HQ(this.currentLogFile,"a",420),W5(X,W,{flag:"a"}),qQ(X),X!==void 0)EJ(X),X=void 0;if((await s$(this.currentLogFile)).size===0){if(await FJ(this.currentLogFile,W,{flag:"w",mode:420}),(await s$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{EJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 o$(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 o$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return o$(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return GJ(16).toString("hex")}generateKey(){return GJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=GJ(16),A=X5("aes-256-gcm",$,Y),X=Q$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Q$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=yQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(Q$.from(Q$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(U0())return;let w=await s$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await eY(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await s$(Y).catch(()=>null))try{if(await MQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await wA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await FJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await s$(Y).catch(()=>null))await MQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await eY(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await wA(o$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=NQ(w),A=U5($),X=yQ();await f5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),KJ(this.currentLogFile))try{let w=HQ(this.currentLogFile,"r+");qQ(w),EJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await eY(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await wA(o$(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?s.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=L0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${s.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!U0()){let Q=Bf[w],f=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:s.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:s.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
3
- `);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:s.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
2
+ import{createRequire as l6}from"node:module";var g6=Object.defineProperty;var d6=(w)=>w;function n6(w,$){this[w]=d6.bind(null,$)}var sj=(w,$)=>{for(var Y in $)g6(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:n6.bind($,Y)})};var s=(w,$)=>()=>(w&&($=w(w=0)),$);var i=l6(import.meta.url);import{existsSync as GQ,statSync as EQ}from"fs";import{existsSync as sG,mkdirSync as kM,readdirSync as ZM,readFileSync as oG,writeFileSync as PM}from"fs";import{homedir as p$}from"os";import{dirname as uM,resolve as Uw}from"path";import xA from"process";import{existsSync as KQ,statSync as FQ}from"fs";import{existsSync as xJ,mkdirSync as eG,readdirSync as w5,writeFileSync as $5}from"fs";import{homedir as r$}from"os";import{dirname as TQ,resolve as v0}from"path";import h$ from"process";import{join as Y5,relative as A5,resolve as NQ}from"path";import HA from"process";import{existsSync as $f,mkdirSync as tM,readdirSync as aM,writeFileSync as sM}from"fs";import{homedir as GJ}from"os";import{dirname as wy,resolve as c0}from"path";import a1 from"process";import{join as X5,relative as J5,resolve as qQ}from"path";import RA from"process";import{existsSync as Yf,mkdirSync as Jy,readdirSync as Uy,writeFileSync as Wy}from"fs";import{dirname as Qy,resolve as MA}from"path";import kJ from"process";import{Buffer as j$}from"buffer";import{createCipheriv as U5,createDecipheriv as W5,randomBytes as EJ}from"crypto";import{closeSync as KJ,createReadStream as HQ,createWriteStream as j5,existsSync as FJ,fsyncSync as RQ,openSync as MQ,writeFileSync as Q5}from"fs";import{access as f5,constants as yQ,mkdir as z5,readdir as wA,rename as IQ,stat as t$,unlink as $A,writeFile as TJ}from"fs/promises";import{join as a$}from"path";import L0 from"process";import{pipeline as B5}from"stream/promises";import{createGzip as CQ}from"zlib";import s$ from"process";import Pw from"process";import{Buffer as kw}from"buffer";import{createCipheriv as G5,createDecipheriv as E5,randomBytes as NJ}from"crypto";import{closeSync as qJ,createReadStream as VQ,createWriteStream as K5,existsSync as YA,fsyncSync as LQ,openSync as SQ,writeFileSync as F5}from"fs";import{access as T5,constants as hQ,mkdir as N5,readdir as AA,rename as OQ,stat as o$,unlink as XA,writeFile as HJ}from"fs/promises";import{isAbsolute as q5,join as e$,resolve as H5}from"path";import x from"process";import{pipeline as R5}from"stream/promises";import{createGzip as _Q}from"zlib";import w1 from"process";import iw from"process";import JA from"process";import{existsSync as UA}from"fs";import{resolve as RJ}from"path";import{existsSync as M5}from"fs";import{existsSync as y5,readdirSync as I5}from"fs";import{extname as MJ,resolve as DQ}from"path";import C5 from"process";import{join as V5,relative as L5,resolve as xQ}from"path";import yA from"process";import{Buffer as Zw}from"buffer";import{createCipheriv as S5,createDecipheriv as h5,randomBytes as yJ}from"crypto";import{closeSync as IJ,createReadStream as kQ,createWriteStream as O5,existsSync as WA,fsyncSync as ZQ,openSync as PQ,writeFileSync as _5}from"fs";import{access as D5,constants as iQ,mkdir as x5,readdir as jA,rename as bQ,stat as $1,unlink as QA,writeFile as CJ}from"fs/promises";import{isAbsolute as k5,join as Y1,resolve as Z5}from"path";import k from"process";import{pipeline as P5}from"stream/promises";import{createGzip as uQ}from"zlib";import A1 from"process";import bw from"process";import zA from"process";import{existsSync as BA}from"fs";import{resolve as _J}from"path";import{existsSync as YK}from"fs";class eQ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!GQ(w))return!0;return EQ(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=GQ(Y)?EQ(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class wf{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function u5(w,$){this[w]=b5.bind(null,$)}class lJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!KQ(w))return!0;return FQ(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=KQ(Y)?FQ(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class pJ{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function m5(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function g5(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function d5(w){return w.getStats().size*2}function rJ(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&Y0($[0])&&"id"in $[0]&&$[0].id===3&&Y0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(Y0($)&&Y0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(Y0(w)&&"arr"in w&&Array.isArray(w.arr)&&Y0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&Y0($[0])&&Y0(w[0])){let A=[...$];for(let X of w)if(Y0(X)&&"name"in X){if(!A.find((U)=>Y0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(Y0(X)&&"path"in X){if(!A.find((U)=>Y0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>IA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!Y0($)||!Y0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=rJ(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&Y0(X[0])&&Y0(Y[A][0])){let J=[...X];for(let U of Y[A])if(Y0(U)&&"name"in U){if(!J.find((W)=>Y0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(Y0(U)&&"path"in U){if(!J.find((W)=>Y0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>IA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function IA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!IA(w[Y],$[Y]))return!1;return!0}if(Y0(w)&&Y0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!IA(w[X],$[X]))return!1}return!0}return!1}function Y0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function n5(w,$){if(!Yf(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return rJ($,A)}catch{return null}}catch{return null}}async function l5({name:w="",cwd:$,defaultConfig:Y}){let A=$||kJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=MA(A,`${U}${j}`),Q=await n5(W,Y);if(Q!==null)return Q}try{let U=MA(A,"package.json");if(Yf(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return rJ(Y,W)}catch{}}}catch{}return Y}function p5(w,$={}){let Y=RA.cwd();while(Y.includes("storage"))Y=qQ(Y,"..");let A=qQ(Y,w||"");if($?.relative)return J5(RA.cwd(),A);return A}async function r5(){try{let w=await l5({name:"clarity",defaultConfig:KA,cwd:RA.cwd(),endpoint:"",headers:{}});return{...KA,...w}}catch{return KA}}function U0(){if(Pw.env.NODE_ENV==="test"||Pw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function t5(){if(Pw.env.NODE_ENV==="test"||Pw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Pw<"u"){let w=Pw.type;if(w==="renderer"||w==="worker")return!1;return!!(Pw.versions&&(Pw.versions.node||Pw.versions.bun))}return!1}class Xf{async format(w){let $=await t5(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:s$.pid,hostname:$(),environment:s$.env.NODE_ENV||"development",platform:s$.platform,version:s$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:s$.env.NODE_ENV||s$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class CA{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=w,this.config={...PJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Xf,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...FA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...FA};return{...FA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:PJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await f5(this.config.logDirectory,yQ.F_OK|yQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await z5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:j$.from(w);try{if(!FJ(this.currentLogFile))await TJ(this.currentLogFile,"",{mode:420});if(X=MQ(this.currentLogFile,"a",420),Q5(X,W,{flag:"a"}),RQ(X),X!==void 0)KJ(X),X=void 0;if((await t$(this.currentLogFile)).size===0){if(await TJ(this.currentLogFile,W,{flag:"w",mode:420}),(await t$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{KJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 a$(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 a$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return a$(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return EJ(16).toString("hex")}generateKey(){return EJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=EJ(16),A=U5("aes-256-gcm",$,Y),X=j$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:j$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=CQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(j$.from(j$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(U0())return;let w=await t$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await wA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await t$(Y).catch(()=>null))try{if(await IQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await $A(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await TJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await t$(Y).catch(()=>null))await IQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await wA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await $A(a$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=HQ(w),A=j5($),X=CQ();await B5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),FJ(this.currentLogFile))try{let w=MQ(this.currentLogFile,"r+");RQ(w),KJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await wA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await $A(a$(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?o.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=L0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${o.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!U0()){let Q=Ef[w],f=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:o.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:o.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
3
+ `);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:o.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
4
4
  `;if(j)W+=`${j}
5
- `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!U0()){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(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
6
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let f=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:s.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(Q.trim());await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new IA($,{...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(!KJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return NQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=Q$.isBuffer(w)?w:Q$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=J5("aes-256-gcm",Y,X);return j.setAuthTag(J),Q$.concat([j.update(U),j.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!U0()){let J=w.split(`
7
- `),U=Math.max(...J.map((f)=>f.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((f)=>{let z=" ".repeat(U-f.length-2);return`│ ${f}${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(j)})),Q.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(W),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
8
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(U0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${s.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();L0.stdin.removeListener("data",Y);try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!1)}catch{}L0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!0)}catch{}L0.stdin.resume(),L0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){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 W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!U0()){let U=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",j=s.blue("◐");console.error(`${j} ${U} ${s.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
9
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||U0()||w<=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:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),j!==void 0)this.activeProgressBar.message=j;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;L0.stdout.write(`${"\r".padEnd(L0.stdout.columns||80)}\r`),this.log(j,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=s.green("━".repeat(A)),U=s.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=$||Y===100?s.green("✓"):s.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${s.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=L0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,L0.stdout.write(w.lastRenderedLine),$)L0.stdout.write(`
10
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await eY(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=o$(this.config.logDirectory,A);if(w.before)try{if((await s$(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 wA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function GA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&d($[0])&&"id"in $[0]&&$[0].id===3&&d($[1])&&"id"in $[1]&&$[1].id===4)return $;if(d($)&&d(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(d(w)&&"arr"in w&&Array.isArray(w.arr)&&d($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&d($[0])&&d(w[0])){let A=[...$];for(let X of w)if(d(X)&&"name"in X){if(!A.find((U)=>d(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(d(X)&&"path"in X){if(!A.find((U)=>d(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>CA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!d($)||!d(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(d(X)&&d(Y[A]))Y[A]=GA(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&d(X[0])&&d(Y[A][0])){let J=[...X];for(let U of Y[A])if(d(U)&&"name"in U){if(!J.find((W)=>d(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(d(U)&&"path"in U){if(!J.find((W)=>d(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>CA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function rJ(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:GA(w,$);if(Array.isArray(w))return Y==="replace"?$:GA(w,$);if(!d($)||!d(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=GA(U,J);else if(d(J)&&d(U))A[X]=rJ(U,J,Y);else A[X]=J}return A}function CA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!CA(w[Y],$[Y]))return!1;return!0}if(d(w)&&d($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!CA(w[X],$[X]))return!1}return!0}return!1}function d(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function QA(w,$,Y="replace"){if(!eQ(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return rJ($,X,Y)}catch{return null}}catch{return null}}function r5(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)h0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=s1.env[G]||s1.env[T];if(K!==void 0){if(Y)h0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((N)=>N.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function t5({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?r5(w,X,J):X,Q=Y||s1.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)h0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,c0(Q,"config"),c0(Q,".config"),A?c0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)h0.info(`Searching for configuration in: ${F}`);let R=[c0(Q,"config"),c0(Q,".config")].concat(A?[c0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let L of R)for(let V of f){let q=c0(F,`${L}${V}`),M=await QA(q,W,j);if(M!==null){if(J)h0.success(`Configuration loaded from: ${q}`);return M}}}if(w){let F=c0(BJ(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)h0.info(`Checking user config directory: ${F}`);for(let R of N)for(let L of f){let V=c0(F,`${R}${L}`),q=await QA(V,W,j);if(q!==null){if(J)h0.success(`Configuration loaded from user config directory: ${V}`);return q}}}if(w){let F=c0(BJ(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)h0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of N)for(let L of f){let V=c0(F,`${R}${L}`),q=await QA(V,W,j);if(q!==null){if(J)h0.success(`Configuration loaded from user config directory dotfile: ${V}`);return q}}}if(w){let F=BJ(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)h0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of N)for(let L of f){let V=c0(F,`${R}${L}`),q=await QA(V,W,j);if(q!==null){if(J)h0.success(`Configuration loaded from user home directory: ${V}`);return q}}}try{let F=c0(Q,"package.json");if(eQ(F)){let N=await import(F),R=N[w];if(!R&&$){if(R=N[$],R&&J)h0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)h0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return rJ(W,R,j)}catch(L){if(J)h0.warn("Failed to merge package.json config:",L)}}}catch(F){if(J)h0.warn("Failed to load package.json:",F)}if(J)h0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function a5(w,$={}){let Y=qA.cwd();while(Y.includes("storage"))Y=FQ(Y,"..");let A=FQ(Y,w||"");if($?.relative)return $5(qA.cwd(),A);return A}async function s5(){try{let w=await t5({name:"clarity",alias:"logging",defaultConfig:FA,cwd:qA.cwd()});return{...FA,...w||{}}}catch{return FA}}function E0(){if(uw.env.NODE_ENV==="test"||uw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function o5(){if(uw.env.NODE_ENV==="test"||uw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof uw<"u"){let w=uw.type;if(w==="renderer"||w==="worker")return!1;return!!(uw.versions&&(uw.versions.node||uw.versions.bun))}return!1}class Af{async format(w){let $=await o5(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:Y1.pid,hostname:$(),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 VA{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=w,this.config={...PJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Af,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...TA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...TA};return{...TA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:PJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await K5(this.config.logDirectory,LQ.F_OK|LQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await F5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:Pw.from(w);try{if(!$A(this.currentLogFile))await qJ(this.currentLogFile,"",{mode:420});if(X=VQ(this.currentLogFile,"a",420),E5(X,W,{flag:"a"}),CQ(X),X!==void 0)NJ(X),X=void 0;if((await w1(this.currentLogFile)).size===0){if(await qJ(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(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{NJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 $1(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 $1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return $1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return TJ(16).toString("hex")}generateKey(){return TJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=TJ(16),A=z5("aes-256-gcm",$,Y),X=Pw.isBuffer(w)?w:Pw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=Pw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=hQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(Pw.from(Pw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let w=await w1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await YA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await w1(Y).catch(()=>null))try{if(await SQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await AA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await qJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await w1(Y).catch(()=>null))await SQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await YA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await AA($1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=IQ(w),A=G5($),X=hQ();await q5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),$A(this.currentLogFile))try{let w=VQ(this.currentLogFile,"r+");CQ(w),NJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await YA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await AA($1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?b.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let w=typeof x.env.NO_COLOR<"u",$=x.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${b.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=b.underline(b.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>b.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>b.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>b.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>b.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>b.strikethrough(A)),$}supportsHyperlinks(){if(E0())return!1;let w=x.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=x.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(T5($)||$.startsWith("./")||$.startsWith("../"))$=N5($);else return null;return $A($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":Gf[w],B=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:b.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:b.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
5
+ `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!U0()){let Y=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:o.blue("◐"),tag:Y,message:`${o.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
6
+ `,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let f=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:o.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(Q.trim());await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new CA($,{...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(!FJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return HQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=j$.isBuffer(w)?w:j$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=W5("aes-256-gcm",Y,X);return j.setAuthTag(J),j$.concat([j.update(U),j.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!U0()){let J=w.split(`
7
+ `),U=Math.max(...J.map((f)=>f.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((f)=>{let z=" ".repeat(U-f.length-2);return`│ ${f}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:o.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(j)})),Q.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(W),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(U0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${o.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();L0.stdin.removeListener("data",Y);try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!1)}catch{}L0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!0)}catch{}L0.stdin.resume(),L0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){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 W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!U0()){let U=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",j=o.blue("◐");console.error(`${j} ${U} ${o.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||U0()||w<=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:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),j!==void 0)this.activeProgressBar.message=j;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;L0.stdout.write(`${"\r".padEnd(L0.stdout.columns||80)}\r`),this.log(j,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=o.green("━".repeat(A)),U=o.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=$||Y===100?o.green("✓"):o.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${o.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=L0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,L0.stdout.write(w.lastRenderedLine),$)L0.stdout.write(`
10
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await wA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=a$(this.config.logDirectory,A);if(w.before)try{if((await t$(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 $A(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function EA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&n($[0])&&"id"in $[0]&&$[0].id===3&&n($[1])&&"id"in $[1]&&$[1].id===4)return $;if(n($)&&n(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(n(w)&&"arr"in w&&Array.isArray(w.arr)&&n($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&n($[0])&&n(w[0])){let A=[...$];for(let X of w)if(n(X)&&"name"in X){if(!A.find((U)=>n(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(n(X)&&"path"in X){if(!A.find((U)=>n(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>VA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!n($)||!n(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(n(X)&&n(Y[A]))Y[A]=EA(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&n(X[0])&&n(Y[A][0])){let J=[...X];for(let U of Y[A])if(n(U)&&"name"in U){if(!J.find((W)=>n(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(n(U)&&"path"in U){if(!J.find((W)=>n(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>VA(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function tJ(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:EA(w,$);if(Array.isArray(w))return Y==="replace"?$:EA(w,$);if(!n($)||!n(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=EA(U,J);else if(n(J)&&n(U))A[X]=tJ(U,J,Y);else A[X]=J}return A}function VA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!VA(w[Y],$[Y]))return!1;return!0}if(n(w)&&n($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!VA(w[X],$[X]))return!1}return!0}return!1}function n(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function fA(w,$,Y="replace"){if(!$f(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return tJ($,X,Y)}catch{return null}}catch{return null}}function a5(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)h0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=a1.env[G]||a1.env[T];if(K!==void 0){if(Y)h0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((N)=>N.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function s5({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?a5(w,X,J):X,Q=Y||a1.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)h0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,c0(Q,"config"),c0(Q,".config"),A?c0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)h0.info(`Searching for configuration in: ${F}`);let R=[c0(Q,"config"),c0(Q,".config")].concat(A?[c0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let V of R)for(let L of f){let q=c0(F,`${V}${L}`),C=await fA(q,W,j);if(C!==null){if(J)h0.success(`Configuration loaded from: ${q}`);return C}}}if(w){let F=c0(GJ(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)h0.info(`Checking user config directory: ${F}`);for(let R of N)for(let V of f){let L=c0(F,`${R}${V}`),q=await fA(L,W,j);if(q!==null){if(J)h0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let F=c0(GJ(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)h0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=c0(F,`${R}${V}`),q=await fA(L,W,j);if(q!==null){if(J)h0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let F=GJ(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)h0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=c0(F,`${R}${V}`),q=await fA(L,W,j);if(q!==null){if(J)h0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let F=c0(Q,"package.json");if($f(F)){let N=await import(F),R=N[w];if(!R&&$){if(R=N[$],R&&J)h0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)h0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return tJ(W,R,j)}catch(V){if(J)h0.warn("Failed to merge package.json config:",V)}}}catch(F){if(J)h0.warn("Failed to load package.json:",F)}if(J)h0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function o5(w,$={}){let Y=HA.cwd();while(Y.includes("storage"))Y=NQ(Y,"..");let A=NQ(Y,w||"");if($?.relative)return A5(HA.cwd(),A);return A}async function e5(){try{let w=await s5({name:"clarity",alias:"logging",defaultConfig:TA,cwd:HA.cwd()});return{...TA,...w||{}}}catch{return TA}}function E0(){if(iw.env.NODE_ENV==="test"||iw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wE(){if(iw.env.NODE_ENV==="test"||iw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof iw<"u"){let w=iw.type;if(w==="renderer"||w==="worker")return!1;return!!(iw.versions&&(iw.versions.node||iw.versions.bun))}return!1}class Jf{async format(w){let $=await wE(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:w1.pid,hostname:$(),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 LA{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=w,this.config={...iJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Jf,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...NA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...NA};return{...NA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:iJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await T5(this.config.logDirectory,hQ.F_OK|hQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await N5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:kw.from(w);try{if(!YA(this.currentLogFile))await HJ(this.currentLogFile,"",{mode:420});if(X=SQ(this.currentLogFile,"a",420),F5(X,W,{flag:"a"}),LQ(X),X!==void 0)qJ(X),X=void 0;if((await o$(this.currentLogFile)).size===0){if(await HJ(this.currentLogFile,W,{flag:"w",mode:420}),(await o$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{qJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 e$(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 e$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return e$(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}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 w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=NJ(16),A=G5("aes-256-gcm",$,Y),X=kw.isBuffer(w)?w:kw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=kw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=_Q(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(kw.from(kw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let w=await o$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await AA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await o$(Y).catch(()=>null))try{if(await OQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await XA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await HJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await o$(Y).catch(()=>null))await OQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await AA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await XA(e$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=VQ(w),A=K5($),X=_Q();await R5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),YA(this.currentLogFile))try{let w=SQ(this.currentLogFile,"r+");LQ(w),qJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await AA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await XA(e$(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?b.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let w=typeof x.env.NO_COLOR<"u",$=x.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${b.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=b.underline(b.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>b.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>b.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>b.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>b.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>b.strikethrough(A)),$}supportsHyperlinks(){if(E0())return!1;let w=x.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=x.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(q5($)||$.startsWith("./")||$.startsWith("../"))$=H5($);else return null;return YA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":Kf[w],B=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:b.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:b.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
11
11
  `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:b.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!E0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
12
12
  `;if(j)f+=`${j}
13
13
  `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!E0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!E0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!E0()&&x.stdout.isTTY)x.stdout.write(`
14
14
  `);if(this[W==="warning"?"warn":W](j),this.activeProgressBar&&this.shouldStyleConsole()&&!E0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=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(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
15
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":b.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new VA($,{...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(E0())throw Error("createReadStream is not supported in browser environments");if(!$A(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return IQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=Pw.isBuffer(w)?w:Pw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=B5("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=Pw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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 E0()}isServerMode(){return!E0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
15
+ `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":b.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new LA($,{...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(E0())throw Error("createReadStream is not supported in browser environments");if(!YA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return VQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=kw.isBuffer(w)?w:kw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=E5("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=kw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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 E0()}isServerMode(){return!E0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
16
16
  `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:b.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(f),showTimestamp:!1}))}else if(!E0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
17
17
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(E0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${b.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();x.stdin.removeListener("data",Y);try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!1)}catch{}x.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!0)}catch{}x.stdin.resume(),x.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(f,z)=>{if(z==="%")return"%";if(Q>=$.length)return f;let B=$[Q++];switch(z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return f}}),Q<$.length)Y+=` ${$.slice(Q).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${Q}${W} ${b.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
18
18
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!x.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=b.green("━".repeat(A)),U=b.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?b.green("✓"):b.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=x.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,x.stdout.write(w.lastRenderedLine),$)x.stdout.write(`
19
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||E0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(E0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await YA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=$1(this.config.logDirectory,A);if(w.before)try{if((await w1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 AA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function Xf(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function Jf(w){return w instanceof a0}function e5(w){return w instanceof LA}function wE(w){if(Jf(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class xA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return wY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=XA.env[W]||(Q?XA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=XA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof SA)throw z;throw f$.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw f$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(XA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
19
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||E0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(E0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await AA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=e$(this.config.logDirectory,A);if(w.before)try{if((await o$(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 XA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function Uf(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function Wf(w){return w instanceof o0}function $E(w){return w instanceof SA}function YE(w){if(Wf(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class kA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return e1.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=JA.env[W]||(Q?JA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=JA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof hA)throw z;throw Q$.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw Q$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(JA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
20
20
 
21
21
  `;for(let A of w)Y+=`${A.key}
22
22
  `,Y+=` Type: ${A.type}
@@ -28,25 +28,25 @@ import{createRequire as d6}from"node:module";var v6=Object.defineProperty;var m6
28
28
  `;Y+=`| Variable | Type | Description | Example |
29
29
  `,Y+=`|----------|------|-------------|----------|
30
30
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
31
- `;return Y}}function $E(w,$){let Y=ff("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function Uf(w,$,Y={}){return Wf(w,$,Y,new WeakMap)}function Wf(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return jf(w,$,X,A);if(!Xw($)||!Xw(w))return $;return JE(w,$,Y,A)}function jf(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return YE(w,$);case"smart":return AE(w,$,A);default:return $}return $}function YE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>kJ(X,A)))Y.push(A);return Y}function AE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Xw($[0])&&Xw(w[0]))return XE(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function XE(w,$,Y){let A=[...$];for(let X of w){if(!Xw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Xw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function JE(w,$,Y,A){let X=$;if(Xw(X)&&A.has(X))return A.get(X);let J={...w};if(Xw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Xw(j)&&Xw(W))J[U]=Wf(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=jf(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function tJ(w,$,Y="replace"){return Uf(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function kJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!kJ(w[Y],$[Y]))return!1;return!0}if(Xw(w)&&Xw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!kJ(w[X],$[X]))return!1}return!0}return!1}function Xw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class kA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=U1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!JA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new o1(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new o1(w,Error("Configuration must export a valid object"),"unknown");let F={config:tJ($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)U1.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?f$.configLoad(w,Q):f$.configLoad(w,Error(String(Q)))}};if(U)return wY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(HJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return Xf(async()=>{return JA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!JA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=HJ(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=HJ(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(w))}async validateConfigFile(w){let $=[];try{if(!JA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class aJ{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await wY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!H5($))throw new e1($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new e1($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:Kf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class sJ{fileLoader=new kA;envProcessor=new xA;validator=new aJ;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Kw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Kw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||_$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(v0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw f$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?a1(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Kw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Kw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?a1(w,Y,X):Y,j=[v0(a$(),".config",w),v0(a$(),".config"),a$()];for(let W of j){if(X)Kw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Kw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?a1(w,A,J):A;try{let W=v0(Y,"package.json");if(!DJ(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Kw.success(`Configuration loaded from package.json: ${z}`);return{config:tJ(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Kw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:a1(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw f$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return U1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);U1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,v0(w,"config"),v0(w,".config"),$?v0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(v0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[v0(a$(),".config",w),v0(a$(),".config"),a$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function bQ(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function UE(w){return vw.loadConfig({...w,__strictErrorHandling:!0})}async function Qf(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await vw.loadConfig(w);else A=await vw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Kw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await vw.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function WE(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await vw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&bQ(Y)))return(await vw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await vw.loadConfig({...w,cwd:w.cwd||_$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&bQ($)))return(await vw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function jE(w,$,Y="replace"){let A=new kA;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function a1(w,$,Y=!1){let A=new xA,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=_$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function QE(w){let $=v0(_$.cwd(),w.configDir),Y=v0(_$.cwd(),w.generatedDir),A=v0(Y,"config-types.ts");if(!DJ(KQ(A)))sG(KQ(A),{recursive:!0,mode:511});let X=DJ($)?oG($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${bE}
31
+ `;return Y}}function AE(w,$){let Y=Bf("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function jf(w,$,Y={}){return Qf(w,$,Y,new WeakMap)}function Qf(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return ff(w,$,X,A);if(!Ww($)||!Ww(w))return $;return WE(w,$,Y,A)}function ff(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return XE(w,$);case"smart":return JE(w,$,A);default:return $}return $}function XE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>ZJ(X,A)))Y.push(A);return Y}function JE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Ww($[0])&&Ww(w[0]))return UE(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function UE(w,$,Y){let A=[...$];for(let X of w){if(!Ww(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Ww(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function WE(w,$,Y,A){let X=$;if(Ww(X)&&A.has(X))return A.get(X);let J={...w};if(Ww(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Ww(j)&&Ww(W))J[U]=Qf(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=ff(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function aJ(w,$,Y="replace"){return jf(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function ZJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!ZJ(w[Y],$[Y]))return!1;return!0}if(Ww(w)&&Ww($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!ZJ(w[X],$[X]))return!1}return!0}return!1}function Ww(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class ZA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=X1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!UA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new s1(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new s1(w,Error("Configuration must export a valid object"),"unknown");let F={config:aJ($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)X1.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?Q$.configLoad(w,Q):Q$.configLoad(w,Error(String(Q)))}};if(U)return e1.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(RJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return Uf(async()=>{return UA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!UA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=RJ(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=RJ(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(w))}async validateConfigFile(w){let $=[];try{if(!UA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class sJ{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await e1.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!M5($))throw new o1($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new o1($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:Tf},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class oJ{fileLoader=new ZA;envProcessor=new kA;validator=new sJ;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Fw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Fw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||h$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(v0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw Q$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?t1(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Fw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Fw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?t1(w,Y,X):Y,j=[v0(r$(),".config",w),v0(r$(),".config"),r$()];for(let W of j){if(X)Fw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Fw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?t1(w,A,J):A;try{let W=v0(Y,"package.json");if(!xJ(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Fw.success(`Configuration loaded from package.json: ${z}`);return{config:aJ(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Fw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:t1(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw Q$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return X1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);X1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,v0(w,"config"),v0(w,".config"),$?v0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(v0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[v0(r$(),".config",w),v0(r$(),".config"),r$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function cQ(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function jE(w){return uw.loadConfig({...w,__strictErrorHandling:!0})}async function zf(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await uw.loadConfig(w);else A=await uw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Fw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await uw.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function QE(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await uw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&cQ(Y)))return(await uw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await uw.loadConfig({...w,cwd:w.cwd||h$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&cQ($)))return(await uw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function fE(w,$,Y="replace"){let A=new ZA;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function t1(w,$,Y=!1){let A=new kA,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=h$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function zE(w){let $=v0(h$.cwd(),w.configDir),Y=v0(h$.cwd(),w.generatedDir),A=v0(Y,"config-types.ts");if(!xJ(TQ(A)))eG(TQ(A),{recursive:!0,mode:511});let X=xJ($)?w5($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${cE}
32
32
  export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
33
- `;eG(A,J,{mode:438})}function fE(w){let $=null,Y=null,A=()=>{if(!Y)Y=Qf(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Kw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function zE(w){let $=OQ(y5.cwd(),w?.configDir||"./config");function Y(){if(!R5($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=M5($).filter((W)=>X.has(RJ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let f=RJ(Q).toLowerCase(),z=j.get(W);if(!z){j.set(W,Q);continue}let B=RJ(z).toLowerCase();if(J.indexOf(f)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",j=X.length?`{
34
- ${X.map((Q)=>{let f=OQ($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${f}').default`}).join(`,
33
+ `;$5(A,J,{mode:438})}function BE(w){let $=null,Y=null,A=()=>{if(!Y)Y=zf(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Fw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function GE(w){let $=DQ(C5.cwd(),w?.configDir||"./config");function Y(){if(!y5($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=I5($).filter((W)=>X.has(MJ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let f=MJ(Q).toLowerCase(),z=j.get(W);if(!z){j.set(W,Q);continue}let B=MJ(z).toLowerCase();if(J.indexOf(f)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",j=X.length?`{
34
+ ${X.map((Q)=>{let f=DQ($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${f}').default`}).join(`,
35
35
  `)}
36
36
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
37
37
  export type ConfigByName = ${j}
38
38
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
39
39
  export type ConfigOf = Config
40
- `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function cE(w,$={}){let Y=MA.cwd();while(Y.includes("storage"))Y=_Q(Y,"..");let A=_Q(Y,w||"");if($?.relative)return C5(MA.cwd(),A);return A}function F0(){if(cw.env.NODE_ENV==="test"||cw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function mE(){if(cw.env.NODE_ENV==="test"||cw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof cw<"u"){let w=cw.type;if(w==="renderer"||w==="worker")return!1;return!!(cw.versions&&(cw.versions.node||cw.versions.bun))}return!1}class qf{async format(w){let $=await mE(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:J1.pid,hostname:$(),environment:J1.env.NODE_ENV||"development",platform:J1.platform,version:J1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:J1.env.NODE_ENV||J1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ZA{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=w,this.config={...hA},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new qf,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...hJ,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...hJ};return{...hJ,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:hA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await O5(this.config.logDirectory,ZQ.F_OK|ZQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await _5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:iw.from(w);try{if(!UA(this.currentLogFile))await IJ(this.currentLogFile,"",{mode:420});if(X=kQ(this.currentLogFile,"a",420),h5(X,W,{flag:"a"}),xQ(X),X!==void 0)yJ(X),X=void 0;if((await A1(this.currentLogFile)).size===0){if(await IJ(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(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{yJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 w=new Date().toISOString().split("T")[0];return X1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}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 w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=MJ(16),A=V5("aes-256-gcm",$,Y),X=iw.isBuffer(w)?w:iw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=iw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=iQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(iw.from(iw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(F0())return;if(!this.shouldWriteToFile())return;let w=await A1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await WA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await A1(Y).catch(()=>null))try{if(await PQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await jA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await IJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await A1(Y).catch(()=>null))await PQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await WA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await jA(X1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=DQ(w),A=S5($),X=iQ();await k5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),UA(this.currentLogFile))try{let w=kQ(this.currentLogFile,"r+");xQ(w),yJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await WA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await jA(X1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?v.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let w=typeof k.env.NO_COLOR<"u",$=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(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=k.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${v.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),$}supportsHyperlinks(){if(F0())return!1;let w=k.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=k.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(D5($)||$.startsWith("./")||$.startsWith("../"))$=x5($);else return null;return UA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":pE[w],B=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:v.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:v.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
40
+ `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function mE(w,$={}){let Y=yA.cwd();while(Y.includes("storage"))Y=xQ(Y,"..");let A=xQ(Y,w||"");if($?.relative)return L5(yA.cwd(),A);return A}function F0(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function dE(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bw<"u"){let w=bw.type;if(w==="renderer"||w==="worker")return!1;return!!(bw.versions&&(bw.versions.node||bw.versions.bun))}return!1}class Rf{async format(w){let $=await dE(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:A1.pid,hostname:$(),environment:A1.env.NODE_ENV||"development",platform:A1.platform,version:A1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:A1.env.NODE_ENV||A1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class PA{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=w,this.config={...OA},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Rf,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...OJ,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...OJ};return{...OJ,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:OA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await D5(this.config.logDirectory,iQ.F_OK|iQ.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await x5(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:Zw.from(w);try{if(!WA(this.currentLogFile))await CJ(this.currentLogFile,"",{mode:420});if(X=PQ(this.currentLogFile,"a",420),_5(X,W,{flag:"a"}),ZQ(X),X!==void 0)IJ(X),X=void 0;if((await $1(this.currentLogFile)).size===0){if(await CJ(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(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{IJ(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 Y1(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 Y1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return Y1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return yJ(16).toString("hex")}generateKey(){return yJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=yJ(16),A=S5("aes-256-gcm",$,Y),X=Zw.isBuffer(w)?w:Zw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=Zw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=uQ(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(Zw.from(Zw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(F0())return;if(!this.shouldWriteToFile())return;let w=await $1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await jA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await $1(Y).catch(()=>null))try{if(await bQ(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await QA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await CJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await $1(Y).catch(()=>null))await bQ(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await jA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await QA(Y1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=kQ(w),A=O5($),X=uQ();await P5(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),WA(this.currentLogFile))try{let w=PQ(this.currentLogFile,"r+");ZQ(w),IJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await jA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await QA(Y1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?v.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let w=typeof k.env.NO_COLOR<"u",$=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(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=k.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${v.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),$}supportsHyperlinks(){if(F0())return!1;let w=k.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=k.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(k5($)||$.startsWith("./")||$.startsWith("../"))$=Z5($);else return null;return WA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":tE[w],B=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:v.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:v.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
41
41
  `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:v.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!F0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
42
42
  `;if(j)f+=`${j}
43
43
  `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!F0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!F0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!F0()&&k.stdout.isTTY)k.stdout.write(`
44
44
  `);if(this[W==="warning"?"warn":W](j),this.activeProgressBar&&this.shouldStyleConsole()&&!F0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":v.blue("◐"),tag:Y,message:`${v.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
45
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":v.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!F0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new ZA($,{...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(F0())throw Error("createReadStream is not supported in browser environments");if(!UA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return DQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=iw.isBuffer(w)?w:iw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=L5("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=iw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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 F0()}isServerMode(){return!F0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
45
+ `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":v.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!F0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new PA($,{...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(F0())throw Error("createReadStream is not supported in browser environments");if(!WA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return kQ(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=Zw.isBuffer(w)?w:Zw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=h5("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=Zw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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 F0()}isServerMode(){return!F0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
46
46
  `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:v.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(f),showTimestamp:!1}))}else if(!F0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
47
47
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(F0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${v.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=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(""),$(X==="y"||X==="yes")};try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!0)}catch{}k.stdin.resume(),k.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(f,z)=>{if(z==="%")return"%";if(Q>=$.length)return f;let B=$[Q++];switch(z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return f}}),Q<$.length)Y+=` ${$.slice(Q).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${v.blue("◐")} `;console.error(`${Q}${W} ${v.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
48
48
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!k.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=v.green("━".repeat(A)),U=v.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?v.green("✓"):v.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=k.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,k.stdout.write(w.lastRenderedLine),$)k.stdout.write(`
49
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||F0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(F0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await WA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=X1(this.config.logDirectory,A);if(w.before)try{if((await A1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 jA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function rE(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class eJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return dJ.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=fA.env[W]||(Q?fA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=fA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof oJ)throw z;throw W1.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw W1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(fA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
49
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||F0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(F0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await jA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=Y1(this.config.logDirectory,A);if(w.before)try{if((await $1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function aE(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class wU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return nJ.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=zA.env[W]||(Q?zA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=zA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof eJ)throw z;throw J1.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw J1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(zA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
50
50
 
51
51
  `;for(let A of w)Y+=`${A.key}
52
52
  `,Y+=` Type: ${A.type}
@@ -58,28 +58,28 @@ export type ConfigOf = Config
58
58
  `;Y+=`| Variable | Type | Description | Example |
59
59
  `,Y+=`|----------|------|-------------|----------|
60
60
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
61
- `;return Y}}function tE(w,$,Y={}){return Lf(w,$,Y,new WeakMap)}function Lf(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return Sf(w,$,X,A);if(!Jw($)||!Jw(w))return $;return eE(w,$,Y,A)}function Sf(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return aE(w,$);case"smart":return sE(w,$,A);default:return $}return $}function aE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>gJ(X,A)))Y.push(A);return Y}function sE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Jw($[0])&&Jw(w[0]))return oE(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function oE(w,$,Y){let A=[...$];for(let X of w){if(!Jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Jw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function eE(w,$,Y,A){let X=$;if(Jw(X)&&A.has(X))return A.get(X);let J={...w};if(Jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Jw(j)&&Jw(W))J[U]=Lf(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Sf(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function hf(w,$,Y="replace"){return tE(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function gJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!gJ(w[Y],$[Y]))return!1;return!0}if(Jw(w)&&Jw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!gJ(w[X],$[X]))return!1}return!0}return!1}function Jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class Of{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=NA.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!zA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new OA(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new OA(w,Error("Configuration must export a valid object"),"unknown");let F={config:hf($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)NA.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?W1.configLoad(w,Q):W1.configLoad(w,Error(String(Q)))}};if(U)return dJ.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(OJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return rE(async()=>{return zA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!zA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=OJ(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=OJ(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(w))}async validateConfigFile(w){let $=[];try{if(!zA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class _f{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await dJ.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!wK($))throw new _A($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new _A($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:$K},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function YK(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class Df{fileLoader=new Of;envProcessor=new eJ;validator=new _f;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Sw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw Sw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||DA.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(Aw(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw W1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${YK(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?BA(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Sw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Sw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?BA(w,Y,X):Y,j=[Aw(t$(),".config",w),Aw(t$(),".config"),t$()];for(let W of j){if(X)Sw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Sw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?BA(w,A,J):A;try{let W=Aw(Y,"package.json");if(!tG(W))return null;let Q={};try{Q=JSON.parse(aG(W,"utf8"))}catch(B){if(J)Sw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let f=Q[w],z=w;if(!f&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){f=Q[G],z=G;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Sw.success(`Configuration loaded from package.json: ${z}`);return{config:hf(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Sw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,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,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw W1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return NA.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);NA.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Aw(w,"config"),Aw(w,".config"),$?Aw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Aw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Aw(t$(),".config",w),Aw(t$(),".config"),t$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}async function xf(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await _J.loadConfig(w);else A=await _J.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Sw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await _J.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}function BA(w,$,Y=!1){let A=new eJ,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=DA.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}var NA,dJ,Z5,P5=(w)=>w,b5=(w,$)=>{for(var Y in $)Z5(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:i5.bind($,Y)})},u5=(w,$)=>()=>(w&&($=w(w=0)),$),$f,ff,U1,wY,zf,BE,GE,uQ,EA,ZJ,S0,s,EE,cQ,KE,vQ,FE,TE,CJ,NE,mQ,gQ,VJ,qE,HE,RE,ME,KA,Bf,yE,h0,IE,CE,dQ,FA,PJ,K0,b,VE,nQ,LE,lQ,SE,hE,LJ,OE,pQ,rQ,_E,SJ,DE,xE,kE,ZE,PE,TA,Gf,iE,bE="0.15.6",a0,LA,o1,iJ,bJ,SA,uJ,cJ,e1,vJ,mJ,f$,Ef,Kf,Kw,vw,Ff,Tf,uE,vE,Nf,hA,ry,y0,v,ty,gE,ay,dE,sy,oy,tQ,ey,nE,lE,w4,aQ,$4,Y4,A4,X4,J4,hJ,pE,U4,Fw,Hf,OA,Rf,Mf,oJ,yf,If,_A,Cf,Vf,W1,$K,Sw,_J,z4,B4;var kf=a(()=>{NA=new sQ,dJ=new oQ,Z5=Object.defineProperty;$f={};b5($f,{withErrorRecovery:()=>Xf,tryLoadConfig:()=>jE,loadConfigWithResult:()=>UE,loadConfig:()=>Qf,isRetryableError:()=>wE,isConfigNotFoundError:()=>e5,isBunfigError:()=>Jf,globalPerformanceMonitor:()=>wY,globalCache:()=>U1,getEnvOrDefault:()=>$E,generateConfigTypes:()=>QE,defaultGeneratedDir:()=>Tf,defaultConfigDir:()=>Ff,deepMergeWithArrayStrategy:()=>tJ,deepMerge:()=>Uf,createLibraryConfig:()=>fE,config:()=>WE,bunfigPlugin:()=>zE,applyEnvVarsToConfig:()=>a1,TypeGenerationError:()=>cJ,SchemaValidationError:()=>e1,PluginError:()=>mJ,PerformanceMonitor:()=>lJ,FileSystemError:()=>uJ,ErrorFactory:()=>f$,EnvVarError:()=>SA,EnvProcessor:()=>xA,ConfigValidator:()=>aJ,ConfigValidationError:()=>iJ,ConfigNotFoundError:()=>LA,ConfigMergeError:()=>bJ,ConfigLoader:()=>sJ,ConfigLoadError:()=>o1,ConfigFileLoader:()=>kA,ConfigCache:()=>nJ,CacheUtils:()=>zf,BunfigError:()=>a0,BrowserConfigError:()=>vJ,ArrayMergeStrategies:()=>Ef});uE=u5(async()=>{ff=import.meta.require,U1=new nJ,wY=new lJ,zf={createKey:c5,isEquivalent:v5,estimateMemoryUsage:m5},BE=RA(xJ.cwd(),"config"),GE=RA(xJ.cwd(),"src/generated"),uQ=HA.env.CLARITY_LOG_DIR||Y5(n5(),"logs"),EA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},ZJ=await l5(),S0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},s=S0,EE=S0.red,cQ=S0.green,KE=S0.yellow,vQ=S0.blue,FE=S0.magenta,TE=S0.cyan,CJ=S0.white,NE=S0.gray,mQ=S0.bgRed,gQ=S0.bgYellow,VJ=S0.bold,qE=S0.dim,HE=S0.italic,RE=S0.underline,ME=S0.reset,KA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Bf={debug:"\uD83D\uDD0D",info:vQ("ℹ"),success:cQ("✓"),warning:gQ(CJ(VJ(" WARN "))),error:mQ(CJ(VJ(" ERROR ")))},yE=new IA("stacks"),h0=new IA("bunfig",{showTags:!0}),IE=c0(s1.cwd(),"config"),CE=c0(s1.cwd(),"src/generated"),dQ=qA.env.CLARITY_LOG_DIR||w5(a5(),"logs"),FA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:dQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},PJ=await s5(),K0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},b=K0,VE=K0.red,nQ=K0.green,LE=K0.yellow,lQ=K0.blue,SE=K0.magenta,hE=K0.cyan,LJ=K0.white,OE=K0.gray,pQ=K0.bgRed,rQ=K0.bgYellow,_E=K0.bgGray,SJ=K0.bold,DE=K0.dim,xE=K0.italic,kE=K0.underline,ZE=K0.strikethrough,PE=K0.reset,TA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Gf={debug:"\uD83D\uDD0D",info:lQ("ℹ"),success:nQ("✓"),warning:rQ(LJ(SJ(" WARN "))),error:pQ(LJ(SJ(" ERROR ")))},iE=new VA("stacks"),a0=class extends Error{timestamp;context;constructor($,Y={}){super($);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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},LA=class extends a0{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},o1=class extends a0{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},iJ=class extends a0{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},bJ=class extends a0{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},SA=class extends a0{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},uJ=class extends a0{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},cJ=class extends a0{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},e1=class extends a0{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},vJ=class extends a0{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},mJ=class extends a0{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},f$={configNotFound(w,$,Y){return new LA(w,$,Y)},configLoad(w,$,Y){return new o1(w,$,Y)},configValidation(w,$,Y){return new iJ(w,$,Y)},configMerge(w,$,Y,A){return new bJ(w,$,Y,A)},envVar(w,$,Y,A){return new SA(w,$,Y,A)},fileSystem(w,$,Y){return new uJ(w,$,Y)},typeGeneration(w,$,Y){return new cJ(w,$,Y)},schemaValidation(w,$,Y){return new e1(w,$,Y)},browserConfig(w,$,Y,A){return new vJ(w,$,Y,A)},plugin(w,$,Y){return new mJ(w,$,Y)}},Ef={replace:"replace",concat:"concat",smart:"smart"},Kf=/^https?:\/\//,Kw=new VA("bunfig",{showTags:!0}),vw=new sJ,Ff=v0(_$.cwd(),"config"),Tf=v0(_$.cwd(),"src/generated")});vE=MA.env.CLARITY_LOG_DIR||I5(cE(),"logs"),Nf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:vE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},hA={...Nf},ry=(async()=>{try{let{loadConfig:w}=await uE().then(()=>$f),$=await w({name:"clarity",alias:"logging",defaultConfig:Nf,cwd:MA.cwd()});if($)Object.assign(hA,$)}catch{}return hA})();y0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},v=y0,ty=y0.red,gE=y0.green,ay=y0.yellow,dE=y0.blue,sy=y0.magenta,oy=y0.cyan,tQ=y0.white,ey=y0.gray,nE=y0.bgRed,lE=y0.bgYellow,w4=y0.bgGray,aQ=y0.bold,$4=y0.dim,Y4=y0.italic,A4=y0.underline,X4=y0.strikethrough,J4=y0.reset,hJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},pE={debug:"\uD83D\uDD0D",info:dE("ℹ"),success:gE("✓"),warning:lE(tQ(aQ(" WARN "))),error:nE(tQ(aQ(" ERROR ")))};U4=new ZA("stacks");Fw=class Fw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};Hf=class Hf extends Fw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};OA=class OA extends Fw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};Rf=class Rf extends Fw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Mf=class Mf extends Fw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};oJ=class oJ extends Fw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};yf=class yf extends Fw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};If=class If extends Fw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};_A=class _A extends Fw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Cf=class Cf extends Fw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};Vf=class Vf extends Fw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};W1={configNotFound(w,$,Y){return new Hf(w,$,Y)},configLoad(w,$,Y){return new OA(w,$,Y)},configValidation(w,$,Y){return new Rf(w,$,Y)},configMerge(w,$,Y,A){return new Mf(w,$,Y,A)},envVar(w,$,Y,A){return new oJ(w,$,Y,A)},fileSystem(w,$,Y){return new yf(w,$,Y)},typeGeneration(w,$,Y){return new If(w,$,Y)},schemaValidation(w,$,Y){return new _A(w,$,Y)},browserConfig(w,$,Y,A){return new Cf(w,$,Y,A)},plugin(w,$,Y){return new Vf(w,$,Y)}};$K=/^https?:\/\//;Sw=new ZA("bunfig",{showTags:!0});_J=new Df;z4=Aw(DA.cwd(),"config"),B4=Aw(DA.cwd(),"src/generated")});import{homedir as wU}from"node:os";import{join as $U,resolve as AK}from"node:path";async function Pf(){if(!YU)YU=await xf({name:"rpx",cwd:AK(__dirname,".."),defaultConfig:Zf});return YU}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Zf,YU=null,mw;var PA=a(()=>{kf();Zf={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:$U(wU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:$U(wU(),".stacks","ssl","stacks.localhost.crt"),keyPath:$U(wU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};mw=Zf});function j1(w){return w.startsWith("*.")}function $Y(w,$){if(!j1($))return!1;let Y=$.slice(1);return w.length>Y.length&&w.endsWith(Y)}function bf(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!j1(J))continue;if($Y($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}import{existsSync as XK,readdirSync as JK,readFileSync as UK,statSync as WK}from"node:fs";import{homedir as cf}from"node:os";import{isAbsolute as jK,join as Q1}from"node:path";function XU(w,$){if(w==="~")return $;if(w.startsWith("~/"))return Q1($,w.slice(2));return w}function fK(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function iA(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function zK(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function BK(w,$){let Y=$.readText(Q1(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(Q1(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function GK(w){let $=w.selfRegisters??!1;return{command:w.command,env:w.env,urlEnv:w.urlEnv,selfRegisters:$,routes:w.routes??($?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function EK(w,$){let Y=BK(w,$);if(Y?.command)return GK(Y);let A=$.fileExists(Q1(w,"buddy")),X=$.readText(Q1(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((W)=>W==="stacks"||W.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function JU(w,$={}){let Y={dirExists:$.dirExists??AU.dirExists,fileExists:$.fileExists??AU.fileExists,readText:$.readText??AU.readText},A=$.detect??EK,X=$.homeDir??cf(),J=w.tlds??mf,U=(w.roots??vf).map((B)=>XU(B,X)),j=w.idleTimeoutMs??QK,W=new Map;for(let B of w.sites??[])W.set(B.to,B);let Q=(B)=>B.idleTimeoutMs??j;function f(B){let G=bf(W,B);if(!G)return null;let T=jK(G.dir)?G.dir:XU(G.dir,X),K=G.selfRegisters??!1,F=G.routes??[];if(!K&&F.length===0)F=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let N=uf({...G.env??{}},void 0,B);return{host:B,id:iA(B),dir:T,command:G.command,env:N,routes:F,selfRegisters:K,idleTimeoutMs:Q(G),source:"config"}}function z(B){let G=zK(B,J);if(!G)return null;for(let T of U){let K=Q1(T,G);if(!Y.dirExists(K))continue;let F=A(K,Y);if(!F)continue;let N=F.selfRegisters??!1;return{host:B,id:iA(B),dir:K,command:F.command,env:uf({...F.env??{}},F.urlEnv,B),routes:N?[]:F.routes??[],selfRegisters:N,idleTimeoutMs:j,source:"discovered"}}return null}return{resolve(B){let G=fK(B);if(!G)return null;return f(G)??z(G)}}}function KK(w){try{return JK(w,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name)}catch{return[]}}function gf(w,$={}){let Y=$.homeDir??cf(),A=w.tlds??mf,X=(w.roots??vf).map((z)=>XU(z,Y)),J=$.readdir??KK,U=JU(w,$),j=[],W=new Set,Q=(z)=>{if(z&&!W.has(z.host))W.add(z.host),j.push(z)};for(let z of w.sites??[])if(!z.to.includes("*"))Q(U.resolve(z.to));let f=A[0]??"localhost";for(let z of X)for(let B of J(z))Q(U.resolve(`${B}.${f}`));return j}function uf(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}var vf,mf,QK=1800000,AU;var UU=a(()=>{vf=["~/Code"],mf=["localhost","test"],AU={dirExists:(w)=>{try{return WK(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return XK(w)}catch{return!1}},readText:(w)=>{try{return UK(w,"utf8")}catch{return null}}}});var H;var x$=a(()=>{H={info:(...w)=>console.log("[info]",...w),success:(...w)=>console.log("[success]",...w),warn:(...w)=>console.warn("[warn]",...w),error:(...w)=>console.error("[error]",...w),debug:(...w)=>console.debug("[debug]",...w),log:(...w)=>console.log(...w),start:(...w)=>console.log("[start]",...w),box:(...w)=>console.log("[box]",...w)}});import{createRequire as FK}from"node:module";import{Resolver as WU}from"node:dns/promises";import{createHash as NK,sign as qK}from"node:crypto";import{createHash as HK}from"node:crypto";import{sign as RK}from"node:crypto";import{generateKeyPairSync as tz,X509Certificate as OK}from"node:crypto";import jU from"node:os";import QU from"node:path";import{existsSync as nf,statSync as lf}from"fs";import{existsSync as DK,mkdirSync as Z4,readdirSync as P4,readFileSync as xK,writeFileSync as i4}from"fs";import{homedir as f1}from"os";import{dirname as c4,resolve as Ww}from"path";import IX from"process";import{existsSync as pf,statSync as rf}from"fs";import{existsSync as xU,mkdirSync as kK,readdirSync as ZK,writeFileSync as PK}from"fs";import{homedir as z1}from"os";import{dirname as tf,resolve as g0}from"path";import Z$ from"process";import{join as iK,relative as bK,resolve as af}from"path";import WX from"process";import{existsSync as az,mkdirSync as a4,readdirSync as s4,writeFileSync as o4}from"fs";import{homedir as fU}from"os";import{dirname as $I,resolve as m0}from"path";import UY from"process";import{join as uK,relative as cK,resolve as sf}from"path";import jX from"process";import{existsSync as sz,mkdirSync as UI,readdirSync as WI,writeFileSync as jI}from"fs";import{dirname as fI,resolve as QX}from"path";import kU from"process";import{Buffer as z$}from"buffer";import{createCipheriv as vK,createDecipheriv as mK,randomBytes as zU}from"crypto";import{closeSync as BU,createReadStream as of,createWriteStream as gK,existsSync as GU,fsyncSync as ef,openSync as wz,writeFileSync as dK}from"fs";import{access as nK,constants as $z,mkdir as lK,readdir as bA,rename as Yz,stat as B1,unlink as uA,writeFile as EU}from"fs/promises";import{join as G1}from"path";import O0 from"process";import{pipeline as pK}from"stream/promises";import{createGzip as Az}from"zlib";import E1 from"process";import lw from"process";import{Buffer as gw}from"buffer";import{createCipheriv as rK,createDecipheriv as tK,randomBytes as KU}from"crypto";import{closeSync as FU,createReadStream as Xz,createWriteStream as aK,existsSync as cA,fsyncSync as Jz,openSync as Uz,writeFileSync as sK}from"fs";import{access as oK,constants as Wz,mkdir as eK,readdir as vA,rename as jz,stat as K1,unlink as mA,writeFile as TU}from"fs/promises";import{isAbsolute as wF,join as F1,resolve as $F}from"path";import n from"process";import{pipeline as YF}from"stream/promises";import{createGzip as Qz}from"zlib";import T1 from"process";import pw from"process";import gA from"process";import{existsSync as dA}from"fs";import{resolve as NU}from"path";import{existsSync as AF}from"fs";import{existsSync as XF,readdirSync as JF}from"fs";import{extname as qU,resolve as fz}from"path";import UF from"process";import{join as WF,relative as jF,resolve as zz}from"path";import fX from"process";import{Buffer as dw}from"buffer";import{createCipheriv as QF,createDecipheriv as fF,randomBytes as HU}from"crypto";import{closeSync as RU,createReadStream as Bz,createWriteStream as zF,existsSync as nA,fsyncSync as Gz,openSync as Ez,writeFileSync as BF}from"fs";import{access as GF,constants as Kz,mkdir as EF,readdir as lA,rename as Fz,stat as N1,unlink as pA,writeFile as MU}from"fs/promises";import{isAbsolute as KF,join as q1,resolve as FF}from"path";import l from"process";import{pipeline as TF}from"stream/promises";import{createGzip as Tz}from"zlib";import H1 from"process";import rw from"process";import rA from"process";import{existsSync as tA}from"fs";import{resolve as yU}from"path";import{existsSync as NF}from"fs";import{exec as cT}from"node:child_process";import nU from"node:fs";import vT from"node:os";import Tw from"node:path";import xB from"node:process";import{promisify as mT}from"node:util";import I1 from"node:crypto";import tw from"node:fs";import rU from"node:path";import z7 from"node:crypto";import{execSync as E7}from"node:child_process";import MX from"node:os";async function oA(w,$={},Y=30000){try{return await fetch(w,{...$,signal:AbortSignal.timeout(Y)})}catch(A){if(A&&typeof A==="object"&&A.name==="TimeoutError"){let X=Error(`ACME HTTP request to ${w} timed out after ${Y}ms`);throw X.name="AcmeRequestTimeoutError",X}throw A}}async function Pz(w,$,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=w.split(".").slice(-2).join("."),U;try{let Q=new WU,f=await Q.resolveNs(J),z=(await Promise.all(f.map((B)=>Q.resolve4(B).catch(()=>[])))).flat();if(z.length>0)U=new WU,U.setServers(z)}catch{}let j=Date.now()+A,W=U??new WU;for(;;){try{if((await W.resolveTxt(w)).some((Q)=>Q.join("")===$))return!0}catch{}if(Date.now()>=j)return!1;await new Promise((Q)=>setTimeout(Q,X))}}class JY{tokens=new Map;add(w,$){this.tokens.set(w,$)}get(w){return this.tokens.get(w)}remove(w){this.tokens.delete(w)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(w){let $=w.indexOf(JY.PATH_PREFIX);if($===-1)return;let Y=w.slice($+JY.PATH_PREFIX.length);return this.get(Y)}}function eA(w){return(typeof w==="string"?Buffer.from(w,"utf8"):Buffer.from(w)).toString("base64url")}function hU(w){return Buffer.from(w,"base64url")}function iz(w){let $=w.export({format:"jwk"});if($.kty!=="EC"||$.crv!=="P-256"||!$.x||!$.y)throw Error(`Expected a P-256 EC public key, got kty=${$.kty} crv=${$.crv}`);return{crv:"P-256",kty:"EC",x:$.x,y:$.y}}function bz(w){let $=`{"crv":"${w.crv}","kty":"${w.kty}","x":"${w.x}","y":"${w.y}"}`;return NK("sha256").update($).digest("base64url")}function uz(w){let{protectedHeader:$,payload:Y,privateKey:A}=w,X=eA(JSON.stringify($)),J=Y===""?"":eA(JSON.stringify(Y)),U=`${X}.${J}`,j=qK("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:eA(j)}}class UX{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(w){this.directoryUrl=w.directoryUrl,this.accountKey=w.accountKey,this.jwk=iz(w.accountPublicKey),this.thumbprint=bz(this.jwk),this.requestTimeoutMs=w.requestTimeoutMs??Zz}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let w=await oA(this.directoryUrl,{},this.requestTimeoutMs);if(!w.ok)throw Error(`Failed to fetch ACME directory: HTTP ${w.status}`);return this.directoryCache=await w.json(),this.directoryCache}async newNonce(){let w=await this.directory(),$=(await oA(w.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!$)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=$,$}async ensureNonce(){if(this.nonce){let w=this.nonce;return this.nonce=void 0,w}return this.newNonce()}async signedPost(w){let{url:$,payload:Y,useJwk:A}=w,X={alg:"ES256",nonce:await this.ensureNonce(),url:$};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=uz({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await oA($,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)},this.requestTimeoutMs),j=U.headers.get("replay-nonce");if(j)this.nonce=j;let W=U.headers.get("content-type")??"",Q;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))Q=await U.text();else{let f=await U.text();Q=f?JSON.parse(f):{}}if(U.status>=400){let f=Q??{};throw new JX(`ACME request to ${$} failed (HTTP ${U.status}): ${f.type??""} ${f.detail??""}`.trim(),f,U.status)}return{status:U.status,headers:U.headers,body:Q,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(w={}){let $=await this.directory(),Y={termsOfServiceAgreed:!0};if(w.email)Y.contact=[`mailto:${w.email}`];let A=await this.signedPost({url:$.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(w){let $=await this.directory(),Y={identifiers:w.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:$.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(w){return(await this.signedPost({url:w,payload:""})).body}keyAuthorization(w){return`${w}.${this.thumbprint}`}dns01TxtValue(w){return HK("sha256").update(this.keyAuthorization(w)).digest("base64url")}async notifyChallengeReady(w){await this.signedPost({url:w,payload:{}})}async pollAuthorization(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization(w);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((j)=>j.status==="invalid");throw new JX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await df(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${w} to become valid`)}async finalizeOrder(w,$){return(await this.signedPost({url:w,payload:{csr:$}})).body}async getOrder(w){return(await this.signedPost({url:w,payload:""})).body}async pollOrder(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder(w);if(J.status==="valid"){if(!J.certificate)throw Error("ACME order is valid but has no certificate URL");return J.certificate}if(J.status==="invalid")throw Error(`ACME order ${w} became invalid`);await df(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${w} to become valid`)}async downloadCertificate(w){let $=await this.signedPost({url:w,payload:""});return typeof $.body==="string"?$.body:String($.body)}static selectChallenge(w,$){let Y=w.challenges.find((A)=>A.type===$);if(!Y)throw Error(`No ${$} challenge available for ${w.identifier.value}`);return Y}}function mz(w){let $=w.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=$[0];if(!Y)return{certPem:`${w.trim()}
61
+ `;return Y}}function sE(w,$,Y={}){return hf(w,$,Y,new WeakMap)}function hf(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return Of(w,$,X,A);if(!jw($)||!jw(w))return $;return $K(w,$,Y,A)}function Of(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return oE(w,$);case"smart":return eE(w,$,A);default:return $}return $}function oE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>dJ(X,A)))Y.push(A);return Y}function eE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(jw($[0])&&jw(w[0]))return wK(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function wK(w,$,Y){let A=[...$];for(let X of w){if(!jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>jw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function $K(w,$,Y,A){let X=$;if(jw(X)&&A.has(X))return A.get(X);let J={...w};if(jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(jw(j)&&jw(W))J[U]=hf(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=Of(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function _f(w,$,Y="replace"){return sE(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function dJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!dJ(w[Y],$[Y]))return!1;return!0}if(jw(w)&&jw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!dJ(w[X],$[X]))return!1}return!0}return!1}function jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class Df{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=qA.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!BA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new _A(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new _A(w,Error("Configuration must export a valid object"),"unknown");let F={config:_f($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)qA.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?J1.configLoad(w,Q):J1.configLoad(w,Error(String(Q)))}};if(U)return nJ.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(_J($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return aE(async()=>{return BA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!BA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=_J(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=_J(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(w))}async validateConfigFile(w){let $=[];try{if(!BA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class xf{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await nJ.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!YK($))throw new DA($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new DA($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:AK},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function XK(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class kf{fileLoader=new Df;envProcessor=new wU;validator=new xf;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)hw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw hw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||xA.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(Uw(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw J1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${XK(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?GA(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)hw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)hw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?GA(w,Y,X):Y,j=[Uw(p$(),".config",w),Uw(p$(),".config"),p$()];for(let W of j){if(X)hw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)hw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?GA(w,A,J):A;try{let W=Uw(Y,"package.json");if(!sG(W))return null;let Q={};try{Q=JSON.parse(oG(W,"utf8"))}catch(B){if(J)hw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let f=Q[w],z=w;if(!f&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){f=Q[G],z=G;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)hw.success(`Configuration loaded from package.json: ${z}`);return{config:_f(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)hw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:GA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw J1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return qA.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);qA.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Uw(w,"config"),Uw(w,".config"),$?Uw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Uw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Uw(p$(),".config",w),Uw(p$(),".config"),p$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}async function Zf(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await DJ.loadConfig(w);else A=await DJ.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)hw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await DJ.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}function GA(w,$,Y=!1){let A=new wU,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=xA.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}var qA,nJ,i5,b5=(w)=>w,c5=(w,$)=>{for(var Y in $)i5(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:u5.bind($,Y)})},v5=(w,$)=>()=>(w&&($=w(w=0)),$),Af,Bf,X1,e1,Gf,EE,KE,vQ,KA,PJ,S0,o,FE,mQ,TE,gQ,NE,qE,VJ,HE,dQ,nQ,LJ,RE,ME,yE,IE,FA,Ef,CE,h0,VE,LE,lQ,TA,iJ,K0,b,SE,pQ,hE,rQ,OE,_E,SJ,DE,tQ,aQ,xE,hJ,kE,ZE,PE,iE,bE,NA,Kf,uE,cE="0.15.6",o0,SA,s1,bJ,uJ,hA,cJ,vJ,o1,mJ,gJ,Q$,Ff,Tf,Fw,uw,Nf,qf,vE,gE,Hf,OA,ay,y0,v,sy,nE,oy,lE,ey,w4,sQ,$4,pE,rE,Y4,oQ,A4,X4,J4,U4,W4,OJ,tE,j4,Tw,Mf,_A,yf,If,eJ,Cf,Vf,DA,Lf,Sf,J1,AK,hw,DJ,G4,E4;var Pf=s(()=>{qA=new eQ,nJ=new wf,i5=Object.defineProperty;Af={};c5(Af,{withErrorRecovery:()=>Uf,tryLoadConfig:()=>fE,loadConfigWithResult:()=>jE,loadConfig:()=>zf,isRetryableError:()=>YE,isConfigNotFoundError:()=>$E,isBunfigError:()=>Wf,globalPerformanceMonitor:()=>e1,globalCache:()=>X1,getEnvOrDefault:()=>AE,generateConfigTypes:()=>zE,defaultGeneratedDir:()=>qf,defaultConfigDir:()=>Nf,deepMergeWithArrayStrategy:()=>aJ,deepMerge:()=>jf,createLibraryConfig:()=>BE,config:()=>QE,bunfigPlugin:()=>GE,applyEnvVarsToConfig:()=>t1,TypeGenerationError:()=>vJ,SchemaValidationError:()=>o1,PluginError:()=>gJ,PerformanceMonitor:()=>pJ,FileSystemError:()=>cJ,ErrorFactory:()=>Q$,EnvVarError:()=>hA,EnvProcessor:()=>kA,ConfigValidator:()=>sJ,ConfigValidationError:()=>bJ,ConfigNotFoundError:()=>SA,ConfigMergeError:()=>uJ,ConfigLoader:()=>oJ,ConfigLoadError:()=>s1,ConfigFileLoader:()=>ZA,ConfigCache:()=>lJ,CacheUtils:()=>Gf,BunfigError:()=>o0,BrowserConfigError:()=>mJ,ArrayMergeStrategies:()=>Ff});vE=v5(async()=>{Bf=import.meta.require,X1=new lJ,e1=new pJ,Gf={createKey:m5,isEquivalent:g5,estimateMemoryUsage:d5},EE=MA(kJ.cwd(),"config"),KE=MA(kJ.cwd(),"src/generated"),vQ=RA.env.CLARITY_LOG_DIR||X5(p5(),"logs"),KA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:vQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},PJ=await r5(),S0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},o=S0,FE=S0.red,mQ=S0.green,TE=S0.yellow,gQ=S0.blue,NE=S0.magenta,qE=S0.cyan,VJ=S0.white,HE=S0.gray,dQ=S0.bgRed,nQ=S0.bgYellow,LJ=S0.bold,RE=S0.dim,ME=S0.italic,yE=S0.underline,IE=S0.reset,FA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Ef={debug:"\uD83D\uDD0D",info:gQ("ℹ"),success:mQ("✓"),warning:nQ(VJ(LJ(" WARN "))),error:dQ(VJ(LJ(" ERROR ")))},CE=new CA("stacks"),h0=new CA("bunfig",{showTags:!0}),VE=c0(a1.cwd(),"config"),LE=c0(a1.cwd(),"src/generated"),lQ=HA.env.CLARITY_LOG_DIR||Y5(o5(),"logs"),TA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:lQ,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},iJ=await e5(),K0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},b=K0,SE=K0.red,pQ=K0.green,hE=K0.yellow,rQ=K0.blue,OE=K0.magenta,_E=K0.cyan,SJ=K0.white,DE=K0.gray,tQ=K0.bgRed,aQ=K0.bgYellow,xE=K0.bgGray,hJ=K0.bold,kE=K0.dim,ZE=K0.italic,PE=K0.underline,iE=K0.strikethrough,bE=K0.reset,NA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Kf={debug:"\uD83D\uDD0D",info:rQ("ℹ"),success:pQ("✓"),warning:aQ(SJ(hJ(" WARN "))),error:tQ(SJ(hJ(" ERROR ")))},uE=new LA("stacks"),o0=class extends Error{timestamp;context;constructor($,Y={}){super($);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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},SA=class extends o0{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},s1=class extends o0{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},bJ=class extends o0{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},uJ=class extends o0{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},hA=class extends o0{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},cJ=class extends o0{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},vJ=class extends o0{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},o1=class extends o0{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},mJ=class extends o0{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},gJ=class extends o0{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Q$={configNotFound(w,$,Y){return new SA(w,$,Y)},configLoad(w,$,Y){return new s1(w,$,Y)},configValidation(w,$,Y){return new bJ(w,$,Y)},configMerge(w,$,Y,A){return new uJ(w,$,Y,A)},envVar(w,$,Y,A){return new hA(w,$,Y,A)},fileSystem(w,$,Y){return new cJ(w,$,Y)},typeGeneration(w,$,Y){return new vJ(w,$,Y)},schemaValidation(w,$,Y){return new o1(w,$,Y)},browserConfig(w,$,Y,A){return new mJ(w,$,Y,A)},plugin(w,$,Y){return new gJ(w,$,Y)}},Ff={replace:"replace",concat:"concat",smart:"smart"},Tf=/^https?:\/\//,Fw=new LA("bunfig",{showTags:!0}),uw=new oJ,Nf=v0(h$.cwd(),"config"),qf=v0(h$.cwd(),"src/generated")});gE=yA.env.CLARITY_LOG_DIR||V5(mE(),"logs"),Hf={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},OA={...Hf},ay=(async()=>{try{let{loadConfig:w}=await vE().then(()=>Af),$=await w({name:"clarity",alias:"logging",defaultConfig:Hf,cwd:yA.cwd()});if($)Object.assign(OA,$)}catch{}return OA})();y0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},v=y0,sy=y0.red,nE=y0.green,oy=y0.yellow,lE=y0.blue,ey=y0.magenta,w4=y0.cyan,sQ=y0.white,$4=y0.gray,pE=y0.bgRed,rE=y0.bgYellow,Y4=y0.bgGray,oQ=y0.bold,A4=y0.dim,X4=y0.italic,J4=y0.underline,U4=y0.strikethrough,W4=y0.reset,OJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},tE={debug:"\uD83D\uDD0D",info:lE("ℹ"),success:nE("✓"),warning:rE(sQ(oQ(" WARN "))),error:pE(sQ(oQ(" ERROR ")))};j4=new PA("stacks");Tw=class Tw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};Mf=class Mf extends Tw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};_A=class _A extends Tw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};yf=class yf extends Tw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};If=class If extends Tw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};eJ=class eJ extends Tw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};Cf=class Cf extends Tw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};Vf=class Vf extends Tw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};DA=class DA extends Tw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};Lf=class Lf extends Tw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};Sf=class Sf extends Tw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};J1={configNotFound(w,$,Y){return new Mf(w,$,Y)},configLoad(w,$,Y){return new _A(w,$,Y)},configValidation(w,$,Y){return new yf(w,$,Y)},configMerge(w,$,Y,A){return new If(w,$,Y,A)},envVar(w,$,Y,A){return new eJ(w,$,Y,A)},fileSystem(w,$,Y){return new Cf(w,$,Y)},typeGeneration(w,$,Y){return new Vf(w,$,Y)},schemaValidation(w,$,Y){return new DA(w,$,Y)},browserConfig(w,$,Y,A){return new Lf(w,$,Y,A)},plugin(w,$,Y){return new Sf(w,$,Y)}};AK=/^https?:\/\//;hw=new PA("bunfig",{showTags:!0});DJ=new kf;G4=Uw(xA.cwd(),"config"),E4=Uw(xA.cwd(),"src/generated")});import{homedir as $U}from"node:os";import{join as YU,resolve as JK}from"node:path";async function uf(){if(!AU)AU=await Zf({name:"rpx",cwd:JK(__dirname,".."),defaultConfig:bf});return AU}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",bf,AU=null,cw;var iA=s(()=>{Pf();bf={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:YU($U(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:YU($U(),".stacks","ssl","stacks.localhost.crt"),keyPath:YU($U(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};cw=bf});function U1(w){return w.startsWith("*.")}function wY(w,$){if(!U1($))return!1;let Y=$.slice(1);return w.length>Y.length&&w.endsWith(Y)}function cf(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!U1(J))continue;if(wY($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}import{existsSync as UK,readdirSync as WK,readFileSync as jK,statSync as QK}from"node:fs";import{homedir as mf}from"node:os";import{isAbsolute as fK,join as W1}from"node:path";function JU(w,$){if(w==="~")return $;if(w.startsWith("~/"))return W1($,w.slice(2));return w}function BK(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function bA(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function GK(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function EK(w,$){let Y=$.readText(W1(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(W1(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function KK(w){let $=w.selfRegisters??!1;return{command:w.command,env:w.env,urlEnv:w.urlEnv,selfRegisters:$,routes:w.routes??($?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function FK(w,$){let Y=EK(w,$);if(Y?.command)return KK(Y);let A=$.fileExists(W1(w,"buddy")),X=$.readText(W1(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((W)=>W==="stacks"||W.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function UU(w,$={}){let Y={dirExists:$.dirExists??XU.dirExists,fileExists:$.fileExists??XU.fileExists,readText:$.readText??XU.readText},A=$.detect??FK,X=$.homeDir??mf(),J=w.tlds??df,U=(w.roots??gf).map((B)=>JU(B,X)),j=w.idleTimeoutMs??zK,W=new Map;for(let B of w.sites??[])W.set(B.to,B);let Q=(B)=>B.idleTimeoutMs??j;function f(B){let G=cf(W,B);if(!G)return null;let T=fK(G.dir)?G.dir:JU(G.dir,X),K=G.selfRegisters??!1,F=G.routes??[];if(!K&&F.length===0)F=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let N=vf({...G.env??{}},void 0,B);return{host:B,id:bA(B),dir:T,command:G.command,env:N,routes:F,selfRegisters:K,idleTimeoutMs:Q(G),source:"config"}}function z(B){let G=GK(B,J);if(!G)return null;for(let T of U){let K=W1(T,G);if(!Y.dirExists(K))continue;let F=A(K,Y);if(!F)continue;let N=F.selfRegisters??!1;return{host:B,id:bA(B),dir:K,command:F.command,env:vf({...F.env??{}},F.urlEnv,B),routes:N?[]:F.routes??[],selfRegisters:N,idleTimeoutMs:j,source:"discovered"}}return null}return{resolve(B){let G=BK(B);if(!G)return null;return f(G)??z(G)}}}function TK(w){try{return WK(w,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name)}catch{return[]}}function nf(w,$={}){let Y=$.homeDir??mf(),A=w.tlds??df,X=(w.roots??gf).map((z)=>JU(z,Y)),J=$.readdir??TK,U=UU(w,$),j=[],W=new Set,Q=(z)=>{if(z&&!W.has(z.host))W.add(z.host),j.push(z)};for(let z of w.sites??[])if(!z.to.includes("*"))Q(U.resolve(z.to));let f=A[0]??"localhost";for(let z of X)for(let B of J(z))Q(U.resolve(`${B}.${f}`));return j}function vf(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}var gf,df,zK=1800000,XU;var WU=s(()=>{gf=["~/Code"],df=["localhost","test"],XU={dirExists:(w)=>{try{return QK(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return UK(w)}catch{return!1}},readText:(w)=>{try{return jK(w,"utf8")}catch{return null}}}});var H;var _$=s(()=>{H={info:(...w)=>console.log("[info]",...w),success:(...w)=>console.log("[success]",...w),warn:(...w)=>console.warn("[warn]",...w),error:(...w)=>console.error("[error]",...w),debug:(...w)=>console.debug("[debug]",...w),log:(...w)=>console.log(...w),start:(...w)=>console.log("[start]",...w),box:(...w)=>console.log("[box]",...w)}});import{createRequire as NK}from"node:module";import{Resolver as jU}from"node:dns/promises";import{createHash as HK,sign as RK}from"node:crypto";import{createHash as MK}from"node:crypto";import{sign as yK}from"node:crypto";import{generateKeyPairSync as sz,X509Certificate as DK}from"node:crypto";import QU from"node:os";import fU from"node:path";import{existsSync as pf,statSync as rf}from"fs";import{existsSync as kK,mkdirSync as i4,readdirSync as b4,readFileSync as ZK,writeFileSync as u4}from"fs";import{homedir as j1}from"os";import{dirname as m4,resolve as fw}from"path";import CX from"process";import{existsSync as tf,statSync as af}from"fs";import{existsSync as kU,mkdirSync as PK,readdirSync as iK,writeFileSync as bK}from"fs";import{homedir as Q1}from"os";import{dirname as sf,resolve as g0}from"path";import x$ from"process";import{join as uK,relative as cK,resolve as of}from"path";import jX from"process";import{existsSync as oz,mkdirSync as o4,readdirSync as e4,writeFileSync as wI}from"fs";import{homedir as zU}from"os";import{dirname as AI,resolve as m0}from"path";import JY from"process";import{join as vK,relative as mK,resolve as ef}from"path";import QX from"process";import{existsSync as ez,mkdirSync as jI,readdirSync as QI,writeFileSync as fI}from"fs";import{dirname as BI,resolve as fX}from"path";import ZU from"process";import{Buffer as f$}from"buffer";import{createCipheriv as gK,createDecipheriv as dK,randomBytes as BU}from"crypto";import{closeSync as GU,createReadStream as wz,createWriteStream as nK,existsSync as EU,fsyncSync as $z,openSync as Yz,writeFileSync as lK}from"fs";import{access as pK,constants as Az,mkdir as rK,readdir as uA,rename as Xz,stat as f1,unlink as cA,writeFile as KU}from"fs/promises";import{join as z1}from"path";import O0 from"process";import{pipeline as tK}from"stream/promises";import{createGzip as Jz}from"zlib";import B1 from"process";import dw from"process";import{Buffer as vw}from"buffer";import{createCipheriv as aK,createDecipheriv as sK,randomBytes as FU}from"crypto";import{closeSync as TU,createReadStream as Uz,createWriteStream as oK,existsSync as vA,fsyncSync as Wz,openSync as jz,writeFileSync as eK}from"fs";import{access as wF,constants as Qz,mkdir as $F,readdir as mA,rename as fz,stat as G1,unlink as gA,writeFile as NU}from"fs/promises";import{isAbsolute as YF,join as E1,resolve as AF}from"path";import l from"process";import{pipeline as XF}from"stream/promises";import{createGzip as zz}from"zlib";import K1 from"process";import nw from"process";import dA from"process";import{existsSync as nA}from"fs";import{resolve as qU}from"path";import{existsSync as JF}from"fs";import{existsSync as UF,readdirSync as WF}from"fs";import{extname as HU,resolve as Bz}from"path";import jF from"process";import{join as QF,relative as fF,resolve as Gz}from"path";import zX from"process";import{Buffer as mw}from"buffer";import{createCipheriv as zF,createDecipheriv as BF,randomBytes as RU}from"crypto";import{closeSync as MU,createReadStream as Ez,createWriteStream as GF,existsSync as lA,fsyncSync as Kz,openSync as Fz,writeFileSync as EF}from"fs";import{access as KF,constants as Tz,mkdir as FF,readdir as pA,rename as Nz,stat as F1,unlink as rA,writeFile as yU}from"fs/promises";import{isAbsolute as TF,join as T1,resolve as NF}from"path";import p from"process";import{pipeline as qF}from"stream/promises";import{createGzip as qz}from"zlib";import N1 from"process";import lw from"process";import tA from"process";import{existsSync as aA}from"fs";import{resolve as IU}from"path";import{existsSync as HF}from"fs";import{exec as mT}from"node:child_process";import lU from"node:fs";import gT from"node:os";import Nw from"node:path";import ZB from"node:process";import{promisify as dT}from"node:util";import M1 from"node:crypto";import pw from"node:fs";import tU from"node:path";import G7 from"node:crypto";import{execSync as F7}from"node:child_process";import yX from"node:os";async function eA(w,$={},Y=30000){try{return await fetch(w,{...$,signal:AbortSignal.timeout(Y)})}catch(A){if(A&&typeof A==="object"&&A.name==="TimeoutError"){let X=Error(`ACME HTTP request to ${w} timed out after ${Y}ms`);throw X.name="AcmeRequestTimeoutError",X}throw A}}async function bz(w,$,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=w.split(".").slice(-2).join("."),U;try{let Q=new jU,f=await Q.resolveNs(J),z=(await Promise.all(f.map((B)=>Q.resolve4(B).catch(()=>[])))).flat();if(z.length>0)U=new jU,U.setServers(z)}catch{}let j=Date.now()+A,W=U??new jU;for(;;){try{if((await W.resolveTxt(w)).some((Q)=>Q.join("")===$))return!0}catch{}if(Date.now()>=j)return!1;await new Promise((Q)=>setTimeout(Q,X))}}class XY{tokens=new Map;add(w,$){this.tokens.set(w,$)}get(w){return this.tokens.get(w)}remove(w){this.tokens.delete(w)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(w){let $=w.indexOf(XY.PATH_PREFIX);if($===-1)return;let Y=w.slice($+XY.PATH_PREFIX.length);return this.get(Y)}}function wX(w){return(typeof w==="string"?Buffer.from(w,"utf8"):Buffer.from(w)).toString("base64url")}function OU(w){return Buffer.from(w,"base64url")}function uz(w){let $=w.export({format:"jwk"});if($.kty!=="EC"||$.crv!=="P-256"||!$.x||!$.y)throw Error(`Expected a P-256 EC public key, got kty=${$.kty} crv=${$.crv}`);return{crv:"P-256",kty:"EC",x:$.x,y:$.y}}function cz(w){let $=`{"crv":"${w.crv}","kty":"${w.kty}","x":"${w.x}","y":"${w.y}"}`;return HK("sha256").update($).digest("base64url")}function vz(w){let{protectedHeader:$,payload:Y,privateKey:A}=w,X=wX(JSON.stringify($)),J=Y===""?"":wX(JSON.stringify(Y)),U=`${X}.${J}`,j=RK("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:wX(j)}}class WX{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(w){this.directoryUrl=w.directoryUrl,this.accountKey=w.accountKey,this.jwk=uz(w.accountPublicKey),this.thumbprint=cz(this.jwk),this.requestTimeoutMs=w.requestTimeoutMs??iz}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let w=await eA(this.directoryUrl,{},this.requestTimeoutMs);if(!w.ok)throw Error(`Failed to fetch ACME directory: HTTP ${w.status}`);return this.directoryCache=await w.json(),this.directoryCache}async newNonce(){let w=await this.directory(),$=(await eA(w.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!$)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=$,$}async ensureNonce(){if(this.nonce){let w=this.nonce;return this.nonce=void 0,w}return this.newNonce()}async signedPost(w){let{url:$,payload:Y,useJwk:A}=w,X={alg:"ES256",nonce:await this.ensureNonce(),url:$};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=vz({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await eA($,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)},this.requestTimeoutMs),j=U.headers.get("replay-nonce");if(j)this.nonce=j;let W=U.headers.get("content-type")??"",Q;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))Q=await U.text();else{let f=await U.text();Q=f?JSON.parse(f):{}}if(U.status>=400){let f=Q??{};throw new UX(`ACME request to ${$} failed (HTTP ${U.status}): ${f.type??""} ${f.detail??""}`.trim(),f,U.status)}return{status:U.status,headers:U.headers,body:Q,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(w={}){let $=await this.directory(),Y={termsOfServiceAgreed:!0};if(w.email)Y.contact=[`mailto:${w.email}`];let A=await this.signedPost({url:$.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(w){let $=await this.directory(),Y={identifiers:w.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:$.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(w){return(await this.signedPost({url:w,payload:""})).body}keyAuthorization(w){return`${w}.${this.thumbprint}`}dns01TxtValue(w){return MK("sha256").update(this.keyAuthorization(w)).digest("base64url")}async notifyChallengeReady(w){await this.signedPost({url:w,payload:{}})}async pollAuthorization(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization(w);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((j)=>j.status==="invalid");throw new UX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await lf(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${w} to become valid`)}async finalizeOrder(w,$){return(await this.signedPost({url:w,payload:{csr:$}})).body}async getOrder(w){return(await this.signedPost({url:w,payload:""})).body}async pollOrder(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder(w);if(J.status==="valid"){if(!J.certificate)throw Error("ACME order is valid but has no certificate URL");return J.certificate}if(J.status==="invalid")throw Error(`ACME order ${w} became invalid`);await lf(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${w} to become valid`)}async downloadCertificate(w){let $=await this.signedPost({url:w,payload:""});return typeof $.body==="string"?$.body:String($.body)}static selectChallenge(w,$){let Y=w.challenges.find((A)=>A.type===$);if(!Y)throw Error(`No ${$} challenge available for ${w.identifier.value}`);return Y}}function dz(w){let $=w.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=$[0];if(!Y)return{certPem:`${w.trim()}
62
62
  `,chainPem:""};let A=`${Y.trim()}
63
63
  `,X=$.slice(1).map((J)=>J.trim()).join(`
64
64
  `);return{certPem:A,chainPem:X?`${X}
65
- `:""}}function gz(w){return`_acme-challenge.${w.startsWith("*.")?w.slice(2):w}`}function df(w){return new Promise(($)=>setTimeout($,w))}function MK(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function E$(w,$){return Buffer.concat([Buffer.from([w]),MK($.length),$])}function dz(w){let $;if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=[],A=w;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);$=Buffer.from(Y)}else if($=w.length===0?Buffer.from([0]):w,$[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return E$(2,$)}function k$(w){let $=w.split(".").map(Number);if($.length<2)throw Error(`Invalid OID: ${w}`);let Y=[40*$[0]+$[1]];for(let A=2;A<$.length;A++){let X=$[A],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);Y.push(...J)}return E$(6,Buffer.from(Y))}function Uw(...w){return E$(48,Buffer.concat(w))}function OU(...w){return E$(49,Buffer.concat(w))}function _U(w){return E$(3,Buffer.concat([Buffer.from([0]),w]))}function nz(w){return E$(4,w)}function lz(w){return E$(12,Buffer.from(w,"utf8"))}function DU(w,$,Y){let A=128|(Y?32:0)|w;return E$(A,$)}function hK(w){let $=w.export({format:"jwk"});if(!$.x||!$.y)throw Error("Public key JWK is missing x/y coordinates");let Y=hU($.x),A=hU($.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 pz(w){let{domains:$,publicKey:Y,privateKey:A}=w;if($.length===0)throw Error("At least one domain is required to build a CSR");let X=Uw(OU(Uw(k$(VK),lz($[0])))),J=Uw(Uw(k$(yK),k$(IK)),_U(hK(Y))),U=$.map((K)=>DU(2,Buffer.from(K,"ascii"),!1)),j=Uw(...U),W=Uw(k$(SK),nz(j)),Q=Uw(W),f=Uw(k$(LK),OU(Q)),z=DU(0,f,!0),B=Uw(dz(0),X,J,z),G=RK("sha256",B,A),T=Uw(k$(CK));return Uw(B,T,_U(G))}function rz(w){return pz(w).toString("base64url")}function _K(w){if(w){let{createPrivateKey:X,createPublicKey:J}=TK("node:crypto"),U=X(w),j=J(U.export({format:"pem",type:"pkcs8"}));return{privateKey:U,publicKey:j,pem:w}}let{privateKey:$,publicKey:Y}=tz("ec",{namedCurve:"P-256"}),A=$.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:$,publicKey:Y,pem:A}}async function tU(w){let{domains:$,method:Y}=w;if($.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!w.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if($.some((z)=>z.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=w.directoryUrl??(w.staging===!1?vz:cz),X=_K(w.accountKeyPem),J=new UX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey,requestTimeoutMs:w.requestTimeoutMs});await J.newAccount({email:w.email});let{order:U,orderUrl:j}=await J.newOrder($),W=w.http01Store??yX,Q=[],f=[];try{for(let q of U.authorizations){let M=await J.getAuthorization(q);if(M.status==="valid")continue;let C=UX.selectChallenge(M,Y);if(Y==="dns-01"){let O=gz(M.identifier.value),J0=J.dns01TxtValue(C.token);await w.dnsProvider.setTxt(O,J0),Q.push({name:O,value:J0}),await Pz(O,J0,{timeoutMs:w.dnsPropagationTimeoutMs??120000})}else W.add(C.token,J.keyAuthorization(C.token)),f.push(C.token);await J.notifyChallengeReady(C.url),await J.pollAuthorization(q,{timeoutMs:w.timeoutMs})}let{privateKey:z,publicKey:B}=tz("ec",{namedCurve:"P-256"}),G=rz({domains:$,publicKey:B,privateKey:z});await J.finalizeOrder(U.finalize,G);let T=await J.pollOrder(j,{timeoutMs:w.timeoutMs}),K=await J.downloadCertificate(T),{certPem:F,chainPem:N}=mz(K),R=N?`${F}${N}`:F,L=z.export({format:"pem",type:"pkcs8"}).toString(),V=new Date(new OK(F).validTo);return{certPem:F,keyPem:L,chainPem:N,fullChainPem:R,accountKeyPem:X.pem,notAfter:V}}finally{for(let{name:z,value:B}of Q)await w.dnsProvider?.removeTxt(z,B).catch(()=>{});for(let z of f)W.remove(z)}}class oz{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!nf(w))return!0;return lf(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=nf(Y)?lf(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class ez{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function RF(w,$){this[w]=HF.bind(null,$)}class sU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!pf(w))return!0;return rf(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=pf(Y)?rf(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class oU{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function IF(w,$={}){let Y=Object.keys($).sort().map((A)=>`${A}:${$[A]}`).join("|");return Y?`${w}:${Y}`:w}function CF(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function VF(w){return w.getStats().size*2}function eU(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&Y0($[0])&&"id"in $[0]&&$[0].id===3&&Y0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(Y0($)&&Y0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(Y0(w)&&"arr"in w&&Array.isArray(w.arr)&&Y0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&Y0($[0])&&Y0(w[0])){let A=[...$];for(let X of w)if(Y0(X)&&"name"in X){if(!A.find((J)=>Y0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(Y0(X)&&"path"in X){if(!A.find((J)=>Y0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>BX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!Y0($)||!Y0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=eU(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&Y0(X[0])&&Y0(Y[A][0])){let J=[...X];for(let U of Y[A])if(Y0(U)&&"name"in U){if(!J.find((j)=>Y0(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(Y0(U)&&"path"in U){if(!J.find((j)=>Y0(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>BX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function BX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!BX(w[Y],$[Y]))return!1;return!0}if(Y0(w)&&Y0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!BX(w[X],$[X]))return!1}return!0}return!1}function Y0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function LF(w,$){if(!sz(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return eU($,A)}catch{return null}}catch{return null}}async function SF({name:w="",cwd:$,defaultConfig:Y}){let A=$||kU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=QX(A,`${U}${j}`),Q=await LF(W,Y);if(Q!==null)return Q}try{let U=QX(A,"package.json");if(sz(U)){let j=(await import(U))[w];if(j&&typeof j==="object"&&!Array.isArray(j))try{return eU(Y,j)}catch{}}}catch{}return Y}function hF(w,$={}){let Y=jX.cwd();while(Y.includes("storage"))Y=sf(Y,"..");let A=sf(Y,w||"");if($?.relative)return cK(jX.cwd(),A);return A}async function OF(){try{let w=await SF({name:"clarity",defaultConfig:$X,cwd:jX.cwd(),endpoint:"",headers:{}});return{...$X,...w}}catch{return $X}}function W0(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _F(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof lw<"u"){let w=lw.type;if(w==="renderer"||w==="worker")return!1;return!!(lw.versions&&(lw.versions.node||lw.versions.bun))}return!1}class $B{async format(w){let $=await _F(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:E1.pid,hostname:$(),environment:E1.env.NODE_ENV||"development",platform:E1.platform,version:E1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:E1.env.NODE_ENV||E1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class GX{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=w,this.config={...PU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new $B,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...YX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...YX};return{...YX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:PU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await nK(this.config.logDirectory,$z.F_OK|$z.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await lK(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:z$.from(w);try{if(!GU(this.currentLogFile))await EU(this.currentLogFile,"",{mode:420});if(A=wz(this.currentLogFile,"a",420),dK(A,j,{flag:"a"}),ef(A),A!==void 0)BU(A),A=void 0;if((await B1(this.currentLogFile)).size===0){if(await EU(this.currentLogFile,j,{flag:"w",mode:420}),(await B1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{BU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}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 G1(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 G1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return G1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}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 $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,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 w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return zU(16).toString("hex")}generateKey(){return zU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=zU(16),A=vK("aes-256-gcm",$,Y),X=z$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:z$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Az(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(z$.from(z$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(W0())return;let w=await B1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await bA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await B1(Y).catch(()=>null))try{if(await Yz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await uA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await EU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await B1(Y).catch(()=>null))await Yz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await bA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await uA(G1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=of(w),A=gK($),X=Az();await pK(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),GU(this.currentLogFile))try{let w=wz(this.currentLogFile,"r+");ef(w),BU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await bA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await uA(G1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?o.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=O0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${o.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!W0()){let Q=zB[w],f=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:o.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:o.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
66
- `);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:o.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!W0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
65
+ `:""}}function nz(w){return`_acme-challenge.${w.startsWith("*.")?w.slice(2):w}`}function lf(w){return new Promise(($)=>setTimeout($,w))}function IK(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function G$(w,$){return Buffer.concat([Buffer.from([w]),IK($.length),$])}function lz(w){let $;if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=[],A=w;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);$=Buffer.from(Y)}else if($=w.length===0?Buffer.from([0]):w,$[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return G$(2,$)}function D$(w){let $=w.split(".").map(Number);if($.length<2)throw Error(`Invalid OID: ${w}`);let Y=[40*$[0]+$[1]];for(let A=2;A<$.length;A++){let X=$[A],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);Y.push(...J)}return G$(6,Buffer.from(Y))}function Qw(...w){return G$(48,Buffer.concat(w))}function _U(...w){return G$(49,Buffer.concat(w))}function DU(w){return G$(3,Buffer.concat([Buffer.from([0]),w]))}function pz(w){return G$(4,w)}function rz(w){return G$(12,Buffer.from(w,"utf8"))}function xU(w,$,Y){let A=128|(Y?32:0)|w;return G$(A,$)}function _K(w){let $=w.export({format:"jwk"});if(!$.x||!$.y)throw Error("Public key JWK is missing x/y coordinates");let Y=OU($.x),A=OU($.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 tz(w){let{domains:$,publicKey:Y,privateKey:A}=w;if($.length===0)throw Error("At least one domain is required to build a CSR");let X=Qw(_U(Qw(D$(SK),rz($[0])))),J=Qw(Qw(D$(CK),D$(VK)),DU(_K(Y))),U=$.map((K)=>xU(2,Buffer.from(K,"ascii"),!1)),j=Qw(...U),W=Qw(D$(OK),pz(j)),Q=Qw(W),f=Qw(D$(hK),_U(Q)),z=xU(0,f,!0),B=Qw(lz(0),X,J,z),G=yK("sha256",B,A),T=Qw(D$(LK));return Qw(B,T,DU(G))}function az(w){return tz(w).toString("base64url")}function xK(w){if(w){let{createPrivateKey:X,createPublicKey:J}=qK("node:crypto"),U=X(w),j=J(U.export({format:"pem",type:"pkcs8"}));return{privateKey:U,publicKey:j,pem:w}}let{privateKey:$,publicKey:Y}=sz("ec",{namedCurve:"P-256"}),A=$.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:$,publicKey:Y,pem:A}}async function aU(w){let{domains:$,method:Y}=w;if($.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!w.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if($.some((z)=>z.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=w.directoryUrl??(w.staging===!1?gz:mz),X=xK(w.accountKeyPem),J=new WX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey,requestTimeoutMs:w.requestTimeoutMs});await J.newAccount({email:w.email});let{order:U,orderUrl:j}=await J.newOrder($),W=w.http01Store??IX,Q=[],f=[];try{for(let q of U.authorizations){let C=await J.getAuthorization(q);if(C.status==="valid")continue;let M=WX.selectChallenge(C,Y);if(Y==="dns-01"){let D=nz(C.identifier.value),d=J.dns01TxtValue(M.token);await w.dnsProvider.setTxt(D,d),Q.push({name:D,value:d}),await bz(D,d,{timeoutMs:w.dnsPropagationTimeoutMs??120000})}else W.add(M.token,J.keyAuthorization(M.token)),f.push(M.token);await J.notifyChallengeReady(M.url),await J.pollAuthorization(q,{timeoutMs:w.timeoutMs})}let{privateKey:z,publicKey:B}=sz("ec",{namedCurve:"P-256"}),G=az({domains:$,publicKey:B,privateKey:z});await J.finalizeOrder(U.finalize,G);let T=await J.pollOrder(j,{timeoutMs:w.timeoutMs}),K=await J.downloadCertificate(T),{certPem:F,chainPem:N}=dz(K),R=N?`${F}${N}`:F,V=z.export({format:"pem",type:"pkcs8"}).toString(),L=new Date(new DK(F).validTo);return{certPem:F,keyPem:V,chainPem:N,fullChainPem:R,accountKeyPem:X.pem,notAfter:L}}finally{for(let{name:z,value:B}of Q)await w.dnsProvider?.removeTxt(z,B).catch(()=>{});for(let z of f)W.remove(z)}}class wB{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!pf(w))return!0;return rf(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=pf(Y)?rf(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class $B{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function yF(w,$){this[w]=MF.bind(null,$)}class oU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!tf(w))return!0;return af(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=tf(Y)?af(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class eU{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function VF(w,$={}){let Y=Object.keys($).sort().map((A)=>`${A}:${$[A]}`).join("|");return Y?`${w}:${Y}`:w}function LF(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function SF(w){return w.getStats().size*2}function wW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&A0($[0])&&"id"in $[0]&&$[0].id===3&&A0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(A0($)&&A0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(A0(w)&&"arr"in w&&Array.isArray(w.arr)&&A0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&A0($[0])&&A0(w[0])){let A=[...$];for(let X of w)if(A0(X)&&"name"in X){if(!A.find((J)=>A0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(A0(X)&&"path"in X){if(!A.find((J)=>A0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>GX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!A0($)||!A0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(A0(X)&&A0(Y[A]))Y[A]=wW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&A0(X[0])&&A0(Y[A][0])){let J=[...X];for(let U of Y[A])if(A0(U)&&"name"in U){if(!J.find((j)=>A0(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(A0(U)&&"path"in U){if(!J.find((j)=>A0(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>GX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function GX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!GX(w[Y],$[Y]))return!1;return!0}if(A0(w)&&A0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!GX(w[X],$[X]))return!1}return!0}return!1}function A0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function hF(w,$){if(!ez(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return wW($,A)}catch{return null}}catch{return null}}async function OF({name:w="",cwd:$,defaultConfig:Y}){let A=$||ZU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=fX(A,`${U}${j}`),Q=await hF(W,Y);if(Q!==null)return Q}try{let U=fX(A,"package.json");if(ez(U)){let j=(await import(U))[w];if(j&&typeof j==="object"&&!Array.isArray(j))try{return wW(Y,j)}catch{}}}catch{}return Y}function _F(w,$={}){let Y=QX.cwd();while(Y.includes("storage"))Y=ef(Y,"..");let A=ef(Y,w||"");if($?.relative)return mK(QX.cwd(),A);return A}async function DF(){try{let w=await OF({name:"clarity",defaultConfig:YX,cwd:QX.cwd(),endpoint:"",headers:{}});return{...YX,...w}}catch{return YX}}function W0(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xF(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof dw<"u"){let w=dw.type;if(w==="renderer"||w==="worker")return!1;return!!(dw.versions&&(dw.versions.node||dw.versions.bun))}return!1}class AB{async format(w){let $=await xF(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:B1.pid,hostname:$(),environment:B1.env.NODE_ENV||"development",platform:B1.platform,version:B1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:B1.env.NODE_ENV||B1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class EX{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=w,this.config={...iU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new AB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...AX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...AX};return{...AX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:iU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await pK(this.config.logDirectory,Az.F_OK|Az.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await rK(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:f$.from(w);try{if(!EU(this.currentLogFile))await KU(this.currentLogFile,"",{mode:420});if(A=Yz(this.currentLogFile,"a",420),lK(A,j,{flag:"a"}),$z(A),A!==void 0)GU(A),A=void 0;if((await f1(this.currentLogFile)).size===0){if(await KU(this.currentLogFile,j,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{GU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}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 z1(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 z1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return z1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}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 $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,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 w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return BU(16).toString("hex")}generateKey(){return BU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=BU(16),A=gK("aes-256-gcm",$,Y),X=f$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:f$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Jz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(f$.from(f$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(W0())return;let w=await f1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await uA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await f1(Y).catch(()=>null))try{if(await Xz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await cA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await KU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await f1(Y).catch(()=>null))await Xz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await uA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await cA(z1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=wz(w),A=nK($),X=Jz();await tK(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),EU(this.currentLogFile))try{let w=Yz(this.currentLogFile,"r+");$z(w),GU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await uA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await cA(z1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?e.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=O0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${e.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!W0()){let Q=GB[w],f=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:e.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:e.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
66
+ `);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:e.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!W0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
67
67
  `;if(j)W+=`${j}
68
- `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!W0()){let Y=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:o.blue("◐"),tag:Y,message:`${o.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
69
- `,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!W0()){let Q=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:o.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!W0())console.error(W.trim());await this.writeToFile(W)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new GX($,{...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(W0())throw Error("createReadStream is not supported in browser environments");if(!GU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return of(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=z$.isBuffer(w)?w:z$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=mK("aes-256-gcm",Y,X);return j.setAuthTag(J),z$.concat([j.update(U),j.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 W0()}isServerMode(){return!W0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!W0()){let J=w.split(`
70
- `),U=Math.max(...J.map((f)=>f.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((f)=>{let z=" ".repeat(U-f.length-2);return`│ ${f}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:o.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(j)})),Q.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(W),showTimestamp:!1}))}else if(!W0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
71
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(W0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${o.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=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(""),$(X==="y"||X==="yes")};try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!0)}catch{}O0.stdin.resume(),O0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let X=/%([sdijfo%])/g,J=0;if(Y=w.replace(X,(U,j)=>{if(j==="%")return"%";if(J>=$.length)return U;let W=$[J++];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 U}}),J<$.length)Y+=` ${$.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!W0()){let X=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",J=o.blue("◐");console.error(`${J} ${X} ${o.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
72
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress(w,$=""){if(!this.enabled||!this.fancy||W0()||w<=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:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,X)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,A)),X!==void 0)this.activeProgressBar.message=X;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())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,X="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;O0.stdout.write(`${"\r".padEnd(O0.stdout.columns||80)}\r`),this.log(X,A),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||W0()||!O0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=o.green("━".repeat(A)),U=o.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=$||Y===100?o.green("✓"):o.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${o.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=O0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,O0.stdout.write(w.lastRenderedLine),$)O0.stdout.write(`
73
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||W0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await bA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=G1(this.config.logDirectory,A);if(w.before)try{if((await B1(X)).mtime>=w.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 uA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function wX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&p($[0])&&"id"in $[0]&&$[0].id===3&&p($[1])&&"id"in $[1]&&$[1].id===4)return $;if(p($)&&p(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(p(w)&&"arr"in w&&Array.isArray(w.arr)&&p($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&p($[0])&&p(w[0])){let A=[...$];for(let X of w)if(p(X)&&"name"in X){if(!A.find((J)=>p(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(p(X)&&"path"in X){if(!A.find((J)=>p(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>EX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!p($)||!p(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(p(X)&&p(Y[A]))Y[A]=wX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&p(X[0])&&p(Y[A][0])){let J=[...X];for(let U of Y[A])if(p(U)&&"name"in U){if(!J.find((j)=>p(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((j)=>p(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>EX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function wW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:wX(w,$);if(Array.isArray(w))return Y==="replace"?$:wX(w,$);if(!p($)||!p(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=wX(U,J);else if(p(J)&&p(U))A[X]=wW(U,J,Y);else A[X]=J}return A}function EX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!EX(w[Y],$[Y]))return!1;return!0}if(p(w)&&p($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!EX(w[X],$[X]))return!1}return!0}return!1}function p(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function aA(w,$,Y="replace"){if(!az(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return wW($,X,Y)}catch{return null}}catch{return null}}function DF(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)D0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=UY.env[G]||UY.env[T];if(K!==void 0){if(Y)D0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((N)=>N.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function xF({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?DF(w,X,J):X,Q=Y||UY.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,m0(Q,"config"),m0(Q,".config"),A?m0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)D0.info(`Searching for configuration in: ${F}`);let N=[m0(Q,"config"),m0(Q,".config")].concat(A?[m0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let R of N)for(let L of f){let V=m0(F,`${R}${L}`),q=await aA(V,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from: ${V}`);return q}}}if(w){let F=m0(fU(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)D0.info(`Checking user config directory: ${F}`);for(let R of N)for(let L of f){let V=m0(F,`${R}${L}`),q=await aA(V,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user config directory: ${V}`);return q}}}if(w){let F=m0(fU(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of N)for(let L of f){let V=m0(F,`${R}${L}`),q=await aA(V,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${V}`);return q}}}if(w){let F=fU(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of N)for(let L of f){let V=m0(F,`${R}${L}`),q=await aA(V,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user home directory: ${V}`);return q}}}try{let F=m0(Q,"package.json");if(az(F)){let N=await import(F),R=N[w];if(!R&&$){if(R=N[$],R&&J)D0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)D0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return wW(W,R,j)}catch(L){if(J)D0.warn("Failed to merge package.json config:",L)}}}catch(F){if(J)D0.warn("Failed to load package.json:",F)}if(J)D0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function kF(w,$={}){let Y=WX.cwd();while(Y.includes("storage"))Y=af(Y,"..");let A=af(Y,w||"");if($?.relative)return bK(WX.cwd(),A);return A}async function ZF(){try{let w=await xF({name:"clarity",alias:"logging",defaultConfig:AX,cwd:WX.cwd()});return{...AX,...w||{}}}catch{return AX}}function T0(){if(pw.env.NODE_ENV==="test"||pw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function PF(){if(pw.env.NODE_ENV==="test"||pw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pw<"u"){let w=pw.type;if(w==="renderer"||w==="worker")return!1;return!!(pw.versions&&(pw.versions.node||pw.versions.bun))}return!1}class YB{async format(w){let $=await PF(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:T1.pid,hostname:$(),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 KX{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=w,this.config={...iU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new YB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...XX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...XX};return{...XX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:iU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await oK(this.config.logDirectory,Wz.F_OK|Wz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await eK(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:gw.from(w);try{if(!cA(this.currentLogFile))await TU(this.currentLogFile,"",{mode:420});if(A=Uz(this.currentLogFile,"a",420),sK(A,j,{flag:"a"}),Jz(A),A!==void 0)FU(A),A=void 0;if((await K1(this.currentLogFile)).size===0){if(await TU(this.currentLogFile,j,{flag:"w",mode:420}),(await K1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{FU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}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 w=new Date().toISOString().split("T")[0];return F1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}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 $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,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 w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return KU(16).toString("hex")}generateKey(){return KU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=KU(16),A=rK("aes-256-gcm",$,Y),X=gw.isBuffer(w)?w:gw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=gw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Qz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(gw.from(gw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let w=await K1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await vA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await K1(Y).catch(()=>null))try{if(await jz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await mA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await TU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await K1(Y).catch(()=>null))await jz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await vA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await mA(F1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Xz(w),A=aK($),X=Qz();await YF(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),cA(this.currentLogFile))try{let w=Uz(this.currentLogFile,"r+");Jz(w),FU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await vA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await mA(F1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?u.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let w=typeof n.env.NO_COLOR<"u",$=n.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=n.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${u.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),$}supportsHyperlinks(){if(T0())return!1;let w=n.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=n.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(wF($)||$.startsWith("./")||$.startsWith("../"))$=$F($);else return null;return cA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":BB[w],B=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:u.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:u.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
68
+ `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!W0()){let Y=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:e.blue("◐"),tag:Y,message:`${e.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
69
+ `,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!W0()){let Q=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:e.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!W0())console.error(W.trim());await this.writeToFile(W)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new EX($,{...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(W0())throw Error("createReadStream is not supported in browser environments");if(!EU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wz(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=f$.isBuffer(w)?w:f$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=dK("aes-256-gcm",Y,X);return j.setAuthTag(J),f$.concat([j.update(U),j.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 W0()}isServerMode(){return!W0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!W0()){let J=w.split(`
70
+ `),U=Math.max(...J.map((f)=>f.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((f)=>{let z=" ".repeat(U-f.length-2);return`│ ${f}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:e.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(j)})),Q.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(W),showTimestamp:!1}))}else if(!W0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
71
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(W0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${e.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=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(""),$(X==="y"||X==="yes")};try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!0)}catch{}O0.stdin.resume(),O0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let X=/%([sdijfo%])/g,J=0;if(Y=w.replace(X,(U,j)=>{if(j==="%")return"%";if(J>=$.length)return U;let W=$[J++];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 U}}),J<$.length)Y+=` ${$.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!W0()){let X=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",J=e.blue("◐");console.error(`${J} ${X} ${e.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
72
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress(w,$=""){if(!this.enabled||!this.fancy||W0()||w<=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:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,X)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,A)),X!==void 0)this.activeProgressBar.message=X;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())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,X="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;O0.stdout.write(`${"\r".padEnd(O0.stdout.columns||80)}\r`),this.log(X,A),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||W0()||!O0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=e.green("━".repeat(A)),U=e.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=$||Y===100?e.green("✓"):e.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${e.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=O0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,O0.stdout.write(w.lastRenderedLine),$)O0.stdout.write(`
73
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||W0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await uA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=z1(this.config.logDirectory,A);if(w.before)try{if((await f1(X)).mtime>=w.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 cA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function $X(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&r($[0])&&"id"in $[0]&&$[0].id===3&&r($[1])&&"id"in $[1]&&$[1].id===4)return $;if(r($)&&r(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(r(w)&&"arr"in w&&Array.isArray(w.arr)&&r($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&r($[0])&&r(w[0])){let A=[...$];for(let X of w)if(r(X)&&"name"in X){if(!A.find((J)=>r(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(r(X)&&"path"in X){if(!A.find((J)=>r(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>KX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!r($)||!r(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(r(X)&&r(Y[A]))Y[A]=$X(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&r(X[0])&&r(Y[A][0])){let J=[...X];for(let U of Y[A])if(r(U)&&"name"in U){if(!J.find((j)=>r(j)&&("name"in j)&&j.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((j)=>r(j)&&("path"in j)&&j.path===U.path))J.push(U)}else if(!J.some((j)=>KX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function $W(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:$X(w,$);if(Array.isArray(w))return Y==="replace"?$:$X(w,$);if(!r($)||!r(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=$X(U,J);else if(r(J)&&r(U))A[X]=$W(U,J,Y);else A[X]=J}return A}function KX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!KX(w[Y],$[Y]))return!1;return!0}if(r(w)&&r($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!KX(w[X],$[X]))return!1}return!0}return!1}function r(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function sA(w,$,Y="replace"){if(!oz(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return $W($,X,Y)}catch{return null}}catch{return null}}function kF(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)D0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=JY.env[G]||JY.env[T];if(K!==void 0){if(Y)D0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((N)=>N.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function ZF({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?kF(w,X,J):X,Q=Y||JY.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,m0(Q,"config"),m0(Q,".config"),A?m0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)D0.info(`Searching for configuration in: ${F}`);let N=[m0(Q,"config"),m0(Q,".config")].concat(A?[m0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let R of N)for(let V of f){let L=m0(F,`${R}${V}`),q=await sA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from: ${L}`);return q}}}if(w){let F=m0(zU(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)D0.info(`Checking user config directory: ${F}`);for(let R of N)for(let V of f){let L=m0(F,`${R}${V}`),q=await sA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let F=m0(zU(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=m0(F,`${R}${V}`),q=await sA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let F=zU(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=m0(F,`${R}${V}`),q=await sA(L,W,j);if(q!==null){if(J)D0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let F=m0(Q,"package.json");if(oz(F)){let N=await import(F),R=N[w];if(!R&&$){if(R=N[$],R&&J)D0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)D0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return $W(W,R,j)}catch(V){if(J)D0.warn("Failed to merge package.json config:",V)}}}catch(F){if(J)D0.warn("Failed to load package.json:",F)}if(J)D0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function PF(w,$={}){let Y=jX.cwd();while(Y.includes("storage"))Y=of(Y,"..");let A=of(Y,w||"");if($?.relative)return cK(jX.cwd(),A);return A}async function iF(){try{let w=await ZF({name:"clarity",alias:"logging",defaultConfig:XX,cwd:jX.cwd()});return{...XX,...w||{}}}catch{return XX}}function T0(){if(nw.env.NODE_ENV==="test"||nw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bF(){if(nw.env.NODE_ENV==="test"||nw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof nw<"u"){let w=nw.type;if(w==="renderer"||w==="worker")return!1;return!!(nw.versions&&(nw.versions.node||nw.versions.bun))}return!1}class XB{async format(w){let $=await bF(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:K1.pid,hostname:$(),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 FX{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=w,this.config={...bU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new XB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...JX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...JX};return{...JX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:bU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await wF(this.config.logDirectory,Qz.F_OK|Qz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await $F(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:vw.from(w);try{if(!vA(this.currentLogFile))await NU(this.currentLogFile,"",{mode:420});if(A=jz(this.currentLogFile,"a",420),eK(A,j,{flag:"a"}),Wz(A),A!==void 0)TU(A),A=void 0;if((await G1(this.currentLogFile)).size===0){if(await NU(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(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{TU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}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 E1(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 E1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return E1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}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 $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,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 w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return FU(16).toString("hex")}generateKey(){return FU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=FU(16),A=aK("aes-256-gcm",$,Y),X=vw.isBuffer(w)?w:vw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=vw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=zz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(vw.from(vw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let w=await G1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await mA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await G1(Y).catch(()=>null))try{if(await fz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await gA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await NU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await G1(Y).catch(()=>null))await fz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await mA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await gA(E1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Uz(w),A=oK($),X=zz();await XF(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),vA(this.currentLogFile))try{let w=jz(this.currentLogFile,"r+");Wz(w),TU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await mA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await gA(E1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?u.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let w=typeof l.env.NO_COLOR<"u",$=l.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof l.stderr<"u"&&l.stderr.isTTY||typeof l.stdout<"u"&&l.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=l.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${u.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),$}supportsHyperlinks(){if(T0())return!1;let w=l.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=l.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(YF($)||$.startsWith("./")||$.startsWith("../"))$=AF($);else return null;return vA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":EB[w],B=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:u.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:u.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
74
74
  `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:u.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
75
75
  `;if(j)f+=`${j}
76
- `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!T0()&&n.stdout.isTTY)n.stdout.write(`
77
- `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=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(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
78
- `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":u.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new KX($,{...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(!cA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xz(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=gw.isBuffer(w)?w:gw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=tK("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=gw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
76
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!T0()&&l.stdout.isTTY)l.stdout.write(`
77
+ `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=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(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
78
+ `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":u.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new FX($,{...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 Uz(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=vw.isBuffer(w)?w:vw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=sK("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=vw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
79
79
  `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(f),showTimestamp:!1}))}else if(!T0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
80
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(T0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${u.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();n.stdin.removeListener("data",Y);try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!1)}catch{}n.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!0)}catch{}n.stdin.resume(),n.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){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 W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${j}${U} ${u.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
81
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!n.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?u.green("✓"):u.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=n.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,n.stdout.write(w.lastRenderedLine),$)n.stdout.write(`
82
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||T0()||!n.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await vA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=F1(this.config.logDirectory,A);if(w.before)try{if((await K1(X)).mtime>=w.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 mA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function AB(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function XB(w){return w instanceof s0}function iF(w){return w instanceof FX}function bF(w){if(XB(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some(($)=>w.message.toLowerCase().includes($.toLowerCase()))}class CX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return fY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=gA.env[W]||(Q?gA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=gA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof TX)throw z;throw G$.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw G$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(gA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
80
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(T0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${u.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();l.stdin.removeListener("data",Y);try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!1)}catch{}l.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!0)}catch{}l.stdin.resume(),l.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){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 W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${j}${U} ${u.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
81
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!l.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?u.green("✓"):u.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=l.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,l.stdout.write(w.lastRenderedLine),$)l.stdout.write(`
82
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||T0()||!l.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await mA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=E1(this.config.logDirectory,A);if(w.before)try{if((await G1(X)).mtime>=w.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 gA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function JB(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function UB(w){return w instanceof e0}function uF(w){return w instanceof TX}function cF(w){if(UB(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some(($)=>w.message.toLowerCase().includes($.toLowerCase()))}class VX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return QY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=dA.env[W]||(Q?dA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=dA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof NX)throw z;throw B$.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw B$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(dA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
83
83
 
84
84
  `;for(let A of w)Y+=`${A.key}
85
85
  `,Y+=` Type: ${A.type}
@@ -91,25 +91,25 @@ export type ConfigOf = Config
91
91
  `;Y+=`| Variable | Type | Description | Example |
92
92
  `,Y+=`|----------|------|-------------|----------|
93
93
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
94
- `;return Y}}function uF(w,$){let Y=QB("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function JB(w,$,Y={}){return UB(w,$,Y,new WeakMap)}function UB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return WB(w,$,X,A);if(!jw($)||!jw(w))return $;return gF(w,$,Y,A)}function WB(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return cF(w,$);case"smart":return vF(w,$,A);default:return $}return $}function cF(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>ZU(X,A)))Y.push(A);return Y}function vF(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(jw($[0])&&jw(w[0]))return mF(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function mF(w,$,Y){let A=[...$];for(let X of w){if(!jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>jw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function gF(w,$,Y,A){let X=$;if(jw(X)&&A.has(X))return A.get(X);let J={...w};if(jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(jw(j)&&jw(W))J[U]=UB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=WB(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function $W(w,$,Y="replace"){return JB(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function ZU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!ZU(w[Y],$[Y]))return!1;return!0}if(jw(w)&&jw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!ZU(w[X],$[X]))return!1}return!0}return!1}function jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class VX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=M1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!dA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new WY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new WY(w,Error("Configuration must export a valid object"),"unknown");let T={config:$W($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)M1.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?G$.configLoad(w,Q):G$.configLoad(w,Error(String(Q)))}};if(U)return fY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(NU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return AB(async()=>{return dA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!dA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=NU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=NU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!dA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class YW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await fY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!AF($))throw new jY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new jY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:EB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class AW{fileLoader=new VX;envProcessor=new CX;validator=new YW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Nw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Nw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||Z$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(g0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw G$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?AY(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Nw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Nw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?AY(w,Y,X):Y,j=[g0(z1(),".config",w),g0(z1(),".config"),z1()];for(let W of j){if(X)Nw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Nw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?AY(w,A,J):A;try{let W=g0(Y,"package.json");if(!xU(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Nw.success(`Configuration loaded from package.json: ${z}`);return{config:$W(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Nw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:AY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw G$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return M1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);M1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,g0(w,"config"),g0(w,".config"),$?g0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(g0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[g0(z1(),".config",w),g0(z1(),".config"),z1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Nz(w){let $=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),Y=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return $||Y}async function dF(w){return aw.loadConfig({...w,__strictErrorHandling:!0})}async function jB(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await aw.loadConfig(w);else A=await aw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Nw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await aw.applyEnvironmentVariables(U.name||"",$,!0,U.verbose||!1))?.config??$;return $}}async function nF(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await aw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Nz(Y)))return(await aw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await aw.loadConfig({...w,cwd:w.cwd||Z$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Nz($)))return(await aw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function lF(w,$,Y="replace"){let A=new VX;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function AY(w,$,Y=!1){let A=new CX,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=Z$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function pF(w){let $=g0(Z$.cwd(),w.configDir),Y=g0(Z$.cwd(),w.generatedDir),A=g0(Y,"config-types.ts");if(!xU(tf(A)))kK(tf(A),{recursive:!0,mode:511});let X=xU($)?ZK($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${MT}
94
+ `;return Y}}function vF(w,$){let Y=zB("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function WB(w,$,Y={}){return jB(w,$,Y,new WeakMap)}function jB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return QB(w,$,X,A);if(!zw($)||!zw(w))return $;return nF(w,$,Y,A)}function QB(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return mF(w,$);case"smart":return gF(w,$,A);default:return $}return $}function mF(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>PU(X,A)))Y.push(A);return Y}function gF(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(zw($[0])&&zw(w[0]))return dF(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function dF(w,$,Y){let A=[...$];for(let X of w){if(!zw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>zw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function nF(w,$,Y,A){let X=$;if(zw(X)&&A.has(X))return A.get(X);let J={...w};if(zw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(zw(j)&&zw(W))J[U]=jB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=QB(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function YW(w,$,Y="replace"){return WB(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function PU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!PU(w[Y],$[Y]))return!1;return!0}if(zw(w)&&zw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!PU(w[X],$[X]))return!1}return!0}return!1}function zw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class LX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=H1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!nA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new UY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new UY(w,Error("Configuration must export a valid object"),"unknown");let T={config:YW($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)H1.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?B$.configLoad(w,Q):B$.configLoad(w,Error(String(Q)))}};if(U)return QY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(qU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return JB(async()=>{return nA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!nA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=qU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=qU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!nA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class AW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await QY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!JF($))throw new WY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new WY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:FB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class XW{fileLoader=new LX;envProcessor=new VX;validator=new AW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)qw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw qw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||x$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(g0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw B$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?YY(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)qw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)qw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?YY(w,Y,X):Y,j=[g0(Q1(),".config",w),g0(Q1(),".config"),Q1()];for(let W of j){if(X)qw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)qw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?YY(w,A,J):A;try{let W=g0(Y,"package.json");if(!kU(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)qw.success(`Configuration loaded from package.json: ${z}`);return{config:YW(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)qw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:YY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw B$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return H1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);H1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,g0(w,"config"),g0(w,".config"),$?g0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(g0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[g0(Q1(),".config",w),g0(Q1(),".config"),Q1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Hz(w){let $=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),Y=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return $||Y}async function lF(w){return rw.loadConfig({...w,__strictErrorHandling:!0})}async function fB(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await rw.loadConfig(w);else A=await rw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)qw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await rw.applyEnvironmentVariables(U.name||"",$,!0,U.verbose||!1))?.config??$;return $}}async function pF(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await rw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Hz(Y)))return(await rw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await rw.loadConfig({...w,cwd:w.cwd||x$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Hz($)))return(await rw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function rF(w,$,Y="replace"){let A=new LX;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function YY(w,$,Y=!1){let A=new VX,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=x$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function tF(w){let $=g0(x$.cwd(),w.configDir),Y=g0(x$.cwd(),w.generatedDir),A=g0(Y,"config-types.ts");if(!kU(sf(A)))PK(sf(A),{recursive:!0,mode:511});let X=kU($)?iK($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${IT}
95
95
  export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
96
- `;PK(A,J,{mode:438})}function rF(w){let $=null,Y=null,A=()=>{if(!Y)Y=jB(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Nw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function tF(w){let $=fz(UF.cwd(),w?.configDir||"./config");function Y(){if(!XF($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=JF($).filter((W)=>X.has(qU(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let f=qU(Q).toLowerCase(),z=j.get(W);if(!z){j.set(W,Q);continue}let B=qU(z).toLowerCase();if(J.indexOf(f)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((W)=>W.base),U=J.length?J.map((W)=>`'${W}'`).join(" | "):"string",j=X.length?`{
97
- ${X.map((W)=>{let Q=fz($,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${Q}').default`}).join(`,
96
+ `;bK(A,J,{mode:438})}function aF(w){let $=null,Y=null,A=()=>{if(!Y)Y=fB(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)qw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function sF(w){let $=Bz(jF.cwd(),w?.configDir||"./config");function Y(){if(!UF($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=WF($).filter((W)=>X.has(HU(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let f=HU(Q).toLowerCase(),z=j.get(W);if(!z){j.set(W,Q);continue}let B=HU(z).toLowerCase();if(J.indexOf(f)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((W)=>W.base),U=J.length?J.map((W)=>`'${W}'`).join(" | "):"string",j=X.length?`{
97
+ ${X.map((W)=>{let Q=Bz($,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${Q}').default`}).join(`,
98
98
  `)}
99
99
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
100
100
  export type ConfigByName = ${j}
101
101
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
102
102
  export type ConfigOf = Config
103
- `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function IT(w,$={}){let Y=fX.cwd();while(Y.includes("storage"))Y=zz(Y,"..");let A=zz(Y,w||"");if($?.relative)return jF(fX.cwd(),A);return A}function q0(){if(rw.env.NODE_ENV==="test"||rw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function VT(){if(rw.env.NODE_ENV==="test"||rw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof rw<"u"){let w=rw.type;if(w==="renderer"||w==="worker")return!1;return!!(rw.versions&&(rw.versions.node||rw.versions.bun))}return!1}class NB{async format(w){let $=await VT(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:H1.pid,hostname:$(),environment:H1.env.NODE_ENV||"development",platform:H1.platform,version:H1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H1.env.NODE_ENV||H1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class LX{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=w,this.config={...NX},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new NB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...SU,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...SU};return{...SU,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:NX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await GF(this.config.logDirectory,Kz.F_OK|Kz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await EF(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:dw.from(w);try{if(!nA(this.currentLogFile))await MU(this.currentLogFile,"",{mode:420});if(A=Ez(this.currentLogFile,"a",420),BF(A,j,{flag:"a"}),Gz(A),A!==void 0)RU(A),A=void 0;if((await N1(this.currentLogFile)).size===0){if(await MU(this.currentLogFile,j,{flag:"w",mode:420}),(await N1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{RU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}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 q1(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 q1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return q1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}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 $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,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 w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))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 w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=HU(16),A=QF("aes-256-gcm",$,Y),X=dw.isBuffer(w)?w:dw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=dw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Tz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(dw.from(dw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let w=await N1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await lA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await N1(Y).catch(()=>null))try{if(await Fz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await pA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await MU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await N1(Y).catch(()=>null))await Fz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await lA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await pA(q1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Bz(w),A=zF($),X=Tz();await TF(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),nA(this.currentLogFile))try{let w=Ez(this.currentLogFile,"r+");Gz(w),RU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await lA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await pA(q1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?m.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let w=typeof l.env.NO_COLOR<"u",$=l.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof l.stderr<"u"&&l.stderr.isTTY||typeof l.stdout<"u"&&l.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=l.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${m.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),$}supportsHyperlinks(){if(q0())return!1;let w=l.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=l.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(KF($)||$.startsWith("./")||$.startsWith("../"))$=FF($);else return null;return nA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":_T[w],B=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:m.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:m.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
103
+ `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function VT(w,$={}){let Y=zX.cwd();while(Y.includes("storage"))Y=Gz(Y,"..");let A=Gz(Y,w||"");if($?.relative)return fF(zX.cwd(),A);return A}function q0(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function ST(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof lw<"u"){let w=lw.type;if(w==="renderer"||w==="worker")return!1;return!!(lw.versions&&(lw.versions.node||lw.versions.bun))}return!1}class HB{async format(w){let $=await ST(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:N1.pid,hostname:$(),environment:N1.env.NODE_ENV||"development",platform:N1.platform,version:N1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:N1.env.NODE_ENV||N1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class SX{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=w,this.config={...qX},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new HB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??p.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...hU,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...hU};return{...hU,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:qX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await KF(this.config.logDirectory,Tz.F_OK|Tz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await FF(this.config.logDirectory,{recursive:!0,mode:493});else if(W.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw W;else throw W}}catch(W){throw console.error("Debug: [writeToFile] Failed to create log directory:",W),W}let j=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:mw.from(w);try{if(!lA(this.currentLogFile))await yU(this.currentLogFile,"",{mode:420});if(A=Fz(this.currentLogFile,"a",420),EF(A,j,{flag:"a"}),Kz(A),A!==void 0)MU(A),A=void 0;if((await F1(this.currentLogFile)).size===0){if(await yU(this.currentLogFile,j,{flag:"w",mode:420}),(await F1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let Q=W;if(Q.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(Q.code)){if(X<J-1){let f=typeof Q.message==="string"?Q.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,f);let z=U*2**X;await new Promise((B)=>setTimeout(B,z)),X++;continue}}if(Q?.code&&["ENOSPC","EDQUOT"].includes(Q.code))throw Error(`Disk quota exceeded or no space left on device: ${Q.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",Q),Q}finally{if(A!==void 0)try{MU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(j){if(X===J-1){let Q=j,f=typeof Q.message==="string"?Q.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),j}X++;let W=U*2**(X-1);await new Promise((Q)=>setTimeout(Q,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}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 T1(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 T1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return T1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}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 $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,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 w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,j])=>j.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return RU(16).toString("hex")}generateKey(){return RU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=RU(16),A=zF("aes-256-gcm",$,Y),X=mw.isBuffer(w)?w:mw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=mw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=qz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(mw.from(mw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let w=await F1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await pA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await F1(Y).catch(()=>null))try{if(await Nz(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await rA(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await yU(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await F1(Y).catch(()=>null))await Nz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await pA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await rA(T1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Ez(w),A=GF($),X=qz();await qF(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),lA(this.currentLogFile))try{let w=Fz(this.currentLogFile,"r+");Kz(w),MU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await pA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await rA(T1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?m.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let w=typeof p.env.NO_COLOR<"u",$=p.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof p.stderr<"u"&&p.stderr.isTTY||typeof p.stdout<"u"&&p.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=p.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${m.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),$}supportsHyperlinks(){if(q0())return!1;let w=p.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=p.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(TF($)||$.startsWith("./")||$.startsWith("../"))$=NF($);else return null;return lA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":xT[w],B=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:m.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:m.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
104
104
  `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:m.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!q0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
105
105
  `;if(j)f+=`${j}
106
- `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!q0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!q0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!q0()&&l.stdout.isTTY)l.stdout.write(`
107
- `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!q0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":m.blue("◐"),tag:Y,message:`${m.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
108
- `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":m.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!q0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new LX($,{...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(!nA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Bz(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=dw.isBuffer(w)?w:dw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=fF("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=dw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
106
+ `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!q0()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!q0()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!q0()&&p.stdout.isTTY)p.stdout.write(`
107
+ `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!q0()&&p.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":m.blue("◐"),tag:Y,message:`${m.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
108
+ `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":m.green("✓"),tag:Q,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!q0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new SX($,{...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(!lA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ez(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=mw.isBuffer(w)?w:mw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=BF("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=mw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
109
109
  `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:m.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(f),showTimestamp:!1}))}else if(!q0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
110
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(q0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${m.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();l.stdin.removeListener("data",Y);try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!1)}catch{}l.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!0)}catch{}l.stdin.resume(),l.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){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 W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${m.blue("◐")} `;console.error(`${j}${U} ${m.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
111
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!l.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=m.green("━".repeat(A)),U=m.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?m.green("✓"):m.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=l.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,l.stdout.write(w.lastRenderedLine),$)l.stdout.write(`
112
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||q0()||!l.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await lA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=q1(this.config.logDirectory,A);if(w.before)try{if((await N1(X)).mtime>=w.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 pA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function DT(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class JW{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return aU.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=rA.env[W]||(Q?rA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=rA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof XW)throw z;throw y1.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw y1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(rA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
110
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(q0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${m.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();p.stdin.removeListener("data",Y);try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!1)}catch{}p.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof p.stdin.setRawMode==="function")p.stdin.setRawMode(!0)}catch{}p.stdin.resume(),p.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){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 W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${m.blue("◐")} `;console.error(`${j}${U} ${m.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
111
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!p.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=m.green("━".repeat(A)),U=m.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?m.green("✓"):m.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=p.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,p.stdout.write(w.lastRenderedLine),$)p.stdout.write(`
112
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||q0()||!p.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await pA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=T1(this.config.logDirectory,A);if(w.before)try{if((await F1(X)).mtime>=w.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 rA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function kT(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class UW{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return sU.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=tA.env[W]||(Q?tA.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=tA.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof JW)throw z;throw R1.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw R1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(tA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
113
113
 
114
114
  `;for(let A of w)Y+=`${A.key}
115
115
  `,Y+=` Type: ${A.type}
@@ -121,32 +121,32 @@ export type ConfigOf = Config
121
121
  `;Y+=`| Variable | Type | Description | Example |
122
122
  `,Y+=`|----------|------|-------------|----------|
123
123
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
124
- `;return Y}}function xT(w,$,Y={}){return VB(w,$,Y,new WeakMap)}function VB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return LB(w,$,X,A);if(!Qw($)||!Qw(w))return $;return iT(w,$,Y,A)}function LB(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return kT(w,$);case"smart":return ZT(w,$,A);default:return $}return $}function kT(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>dU(X,A)))Y.push(A);return Y}function ZT(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Qw($[0])&&Qw(w[0]))return PT(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function PT(w,$,Y){let A=[...$];for(let X of w){if(!Qw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>Qw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function iT(w,$,Y,A){let X=$;if(Qw(X)&&A.has(X))return A.get(X);let J={...w};if(Qw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Qw(j)&&Qw(W))J[U]=VB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=LB(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function SB(w,$,Y="replace"){return xT(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function dU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!dU(w[Y],$[Y]))return!1;return!0}if(Qw(w)&&Qw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!dU(w[X],$[X]))return!1}return!0}return!1}function Qw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class hB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=zX.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!tA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new qX(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new qX(w,Error("Configuration must export a valid object"),"unknown");let T={config:SB($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)zX.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?y1.configLoad(w,Q):y1.configLoad(w,Error(String(Q)))}};if(U)return aU.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(yU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return DT(async()=>{return tA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!tA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=yU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=yU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!tA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class OB{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await aU.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!NF($))throw new HX($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new HX($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:bT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function uT(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class _B{fileLoader=new hB;envProcessor=new JW;validator=new OB;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)nw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw nw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||IX.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(Ww(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw y1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${uT(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?sA(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)nw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)nw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?sA(w,Y,X):Y,j=[Ww(f1(),".config",w),Ww(f1(),".config"),f1()];for(let W of j){if(X)nw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)nw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?sA(w,A,J):A;try{let W=Ww(Y,"package.json");if(!DK(W))return null;let Q={};try{Q=JSON.parse(xK(W,"utf8"))}catch(B){if(J)nw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let f=Q[w],z=w;if(!f&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){f=Q[G],z=G;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)nw.success(`Configuration loaded from package.json: ${z}`);return{config:SB(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)nw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:sA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw y1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return zX.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);zX.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Ww(w,"config"),Ww(w,".config"),$?Ww(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Ww(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Ww(f1(),".config",w),Ww(f1(),".config"),f1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function sA(w,$,Y=!1){let A=new JW,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=IX.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function kB(w){return nU.readFileSync(w,"utf8")}function lU(w,$){let Y=[];function A(X){let J;try{J=nU.readdirSync(X)}catch{return}for(let U of J){let j=Tw.join(X,U);try{if(nU.statSync(j).isDirectory())A(j);else if(U===$)Y.push(X)}catch{continue}}}return A(w),Y}function S(w,$,Y){if(Y||f0.verbose)console.debug(`[tlsx:${w}] ${$}`)}function ZB(){return xB.env.SUDO_PASSWORD}function lT(w){let $=w.toLowerCase();return dT.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function RX(w){if(Array.isArray(w))return w.map((Y)=>RX(Y));if(typeof w==="string")return nT.test(w)?_z:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(lT(Y)){$[Y]=_z;continue}$[Y]=RX(A)}return $}function SX(w){return JSON.stringify(RX(w))}function pT(w){let $=ZB();if(!$||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(w))return w;let Y=$.replace(/'/g,"'\\''"),A=w.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function B$(w,$={}){let Y=pT(w);try{let{stdout:A,stderr:X}=await gT(Y,{cwd:$.cwd||xB.cwd(),timeout:$.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${w}
125
- Error: ${A.message}`);throw X.stack=A.stack,X}}function PB(w){if(w.domain)return w.domain;if(w.domains?.length)return w.domains[0];throw Error("Either domain or domains must be specified")}function UW(w){let $=Tw.join(vT.homedir(),".stacks","ssl"),Y=w.basePath&&w.basePath.trim()!==""?w.basePath:f0.basePath&&f0.basePath.trim()!==""?f0.basePath:$,A=w.certPath?Tw.isAbsolute(w.certPath)?w.certPath:Tw.join(Y,w.certPath):Tw.join(Y,f0.certPath),X=w.keyPath?Tw.isAbsolute(w.keyPath)?w.keyPath:Tw.join(Y,w.keyPath):Tw.join(Y,f0.keyPath),J=w.caCertPath?Tw.isAbsolute(w.caCertPath)?w.caCertPath:Tw.join(Y,w.caCertPath):Tw.join(Y,f0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function iB(w){let $=[],Y=new Set;if(w.domain)Y.add(w.domain);if(w.domains?.length)w.domains.forEach((A)=>Y.add(A));for(let A of Y)$.push({type:2,value:A});if(w.altNameIPs?.length)for(let A of w.altNameIPs)$.push({type:7,ip:A});if(w.altNameURIs?.length)for(let A of w.altNameURIs)$.push({type:6,value:A});if(w.subjectAltNames?.length)$.push(...w.subjectAltNames);return S(h.CERT,`Generated ${$.length} Subject Alternative Names`,w.verbose),$}function WW(w){let $=w.notBeforeDays??qw.DEFAULT_NOT_BEFORE_DAYS,Y=w.validityDays??(w.validityYears?w.validityYears*365:qw.DEFAULT_VALIDITY_DAYS);S(h.CERT,"Calculating certificate validity dates",w.verbose);let A=new Date(Date.now()-86400*$*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),S(h.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,w.verbose),{notBefore:A,notAfter:X}}function XY(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function e0(w,$){let Y=XY($.length);return Buffer.concat([Buffer.from([w]),Y,$])}function QY(w){let $=w.split(".").map(Number),Y=[];Y.push(40*$[0]+$[1]);for(let A=2;A<$.length;A++){let X=$[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return e0(Hw.OID,Buffer.from(Y))}function pU(w){let $;if(typeof w==="bigint"){let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else $=w;if($[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return e0(Hw.INTEGER,$)}function bB(w,$=0){return e0(Hw.BIT_STRING,Buffer.concat([Buffer.from([$]),w]))}function uB(w){return e0(Hw.OCTET_STRING,w)}function o0(...w){return e0(Hw.SEQUENCE,Buffer.concat(w))}function rT(...w){return e0(Hw.SET,Buffer.concat(w))}function tT(w){return e0(Hw.PRINTABLE_STRING,Buffer.from(w,"ascii"))}function aT(w){return e0(Hw.UTF8_STRING,Buffer.from(w,"utf8"))}function sT(){return Buffer.from([Hw.NULL,0])}function Dz(w,$,Y=!0){let A=160|w|(Y?0:0),X=XY($.length);return Buffer.concat([Buffer.from([A]),X,$])}function xz(w){let $=w.getUTCFullYear();if($>=2050){let Y=w.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return e0(Hw.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=($%100).toString().padStart(2,"0"),A=(w.getUTCMonth()+1).toString().padStart(2,"0"),X=w.getUTCDate().toString().padStart(2,"0"),J=w.getUTCHours().toString().padStart(2,"0"),U=w.getUTCMinutes().toString().padStart(2,"0"),j=w.getUTCSeconds().toString().padStart(2,"0"),W=`${Y}${A}${X}${J}${U}${j}Z`;return e0(Hw.UTC_TIME,Buffer.from(W,"ascii"))}}function oT(w,$){return o0(xz(w),xz($))}function kz(w){let $=[];for(let Y of w){let A;switch(Y.shortName){case"CN":A=d0.COMMON_NAME;break;case"C":A=d0.COUNTRY;break;case"L":A=d0.LOCALITY;break;case"ST":A=d0.STATE;break;case"O":A=d0.ORGANIZATION;break;case"OU":A=d0.ORGANIZATIONAL_UNIT;break;default:continue}let X=Y.shortName==="C"?tT(Y.value):aT(Y.value),J=o0(QY(A),X);$.push(rT(J))}return o0(...$)}function cB(w){return o0(QY(w),sT())}function eT(w){return w.export({type:"spki",format:"der"})}function w7(w){if(w.includes(":")){let $=w;if(w.includes("::")){let X=w.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],j=8-J.length-U.length,W=Array.from({length:j},()=>"0");$=[...J,...W,...U].join(":")}let Y=$.split(":"),A=Buffer.alloc(16);for(let X=0;X<8;X++){let J=Number.parseInt(Y[X]||"0",16);A.writeUInt16BE(J,X*2)}return A}else{let $=w.split(".").map((Y)=>Number.parseInt(Y,10));return Buffer.from($)}}function $7(w){let $=[];for(let Y of w)if(Y.type===2&&Y.value){let A=XY(Y.value.length);$.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=w7(Y.ip),X=XY(A.length);$.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=XY(Y.value.length);$.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return o0(...$)}function Y7(w,$){if(w){if($!==void 0)return o0(e0(1,Buffer.from([255])),pU($));return o0(e0(1,Buffer.from([255])))}return o0()}function A7(w){let $=0;if(w.digitalSignature)$|=128;if(w.keyEncipherment)$|=32;if(w.keyCertSign)$|=4;if(w.cRLSign)$|=2;let Y=0,A=$;while(A>0&&(A&1)===0)Y++,A>>=1;if($===0)Y=7;return bB(Buffer.from([$]),Y)}function X7(w){let $=[];if(w.serverAuth)$.push(QY(d0.SERVER_AUTH));if(w.clientAuth)$.push(QY(d0.CLIENT_AUTH));return o0(...$)}function YY(w,$,Y){let A=[QY(w)];if($)A.push(e0(1,Buffer.from([255])));return A.push(uB(Y)),o0(...A)}function J7(w){let $=[];if($.push(Dz(0,pU(2))),$.push(pU(w.serialNumber)),$.push(cB(d0.SHA256_WITH_RSA)),$.push(kz(w.issuer)),$.push(oT(w.notBefore,w.notAfter)),$.push(kz(w.subject)),$.push(eT(w.publicKey)),w.extensions){let Y=[];if(w.extensions.basicConstraints)Y.push(YY(d0.BASIC_CONSTRAINTS,w.extensions.basicConstraints.critical??!0,Y7(w.extensions.basicConstraints.isCA,w.extensions.basicConstraints.pathLenConstraint)));if(w.extensions.keyUsage)Y.push(YY(d0.KEY_USAGE,w.extensions.keyUsage.critical??!0,A7(w.extensions.keyUsage)));if(w.extensions.extendedKeyUsage)Y.push(YY(d0.EXTENDED_KEY_USAGE,!1,X7(w.extensions.extendedKeyUsage)));if(w.extensions.subjectAltName?.length)Y.push(YY(d0.SUBJECT_ALT_NAME,!1,$7(w.extensions.subjectAltName)));if(w.extensions.subjectKeyIdentifier)Y.push(YY(d0.SUBJECT_KEY_IDENTIFIER,!1,uB(w.extensions.subjectKeyIdentifier)));if(Y.length>0)$.push(Dz(3,o0(...Y)))}return o0(...$)}function U7(w,$){let Y=I1.createSign("SHA256");Y.update(w);let A=Y.sign($);return o0(w,cB(d0.SHA256_WITH_RSA),bB(A))}function W7(w,$){let Y=w.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${$}-----
124
+ `;return Y}}function ZT(w,$,Y={}){return SB(w,$,Y,new WeakMap)}function SB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return hB(w,$,X,A);if(!Bw($)||!Bw(w))return $;return uT(w,$,Y,A)}function hB(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return PT(w,$);case"smart":return iT(w,$,A);default:return $}return $}function PT(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>nU(X,A)))Y.push(A);return Y}function iT(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Bw($[0])&&Bw(w[0]))return bT(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function bT(w,$,Y){let A=[...$];for(let X of w){if(!Bw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((W)=>Bw(W)&&(j in W)&&W[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function uT(w,$,Y,A){let X=$;if(Bw(X)&&A.has(X))return A.get(X);let J={...w};if(Bw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Bw(j)&&Bw(W))J[U]=SB(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=hB(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function OB(w,$,Y="replace"){return ZT(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function nU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!nU(w[Y],$[Y]))return!1;return!0}if(Bw(w)&&Bw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!nU(w[X],$[X]))return!1}return!0}return!1}function Bw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class _B{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=BX.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!aA(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new HX(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new HX(w,Error("Configuration must export a valid object"),"unknown");let T={config:OB($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)BX.setWithFileCheck("file",T,w,J);return T}catch(Q){throw Q instanceof Error?R1.configLoad(w,Q):R1.configLoad(w,Error(String(Q)))}};if(U)return sU.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(IU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return kT(async()=>{return aA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!aA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=IU(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=IU(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!aA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class DB{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await sU.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!HF($))throw new RX($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new RX($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:cT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function vT(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class xB{fileLoader=new _B;envProcessor=new UW;validator=new DB;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)gw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){if(j instanceof Error&&j.name==="ConfigNotFoundError")throw j;let W=Date.now()-$;throw gw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||CX.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(fw(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw R1.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${vT(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?oA(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)gw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)gw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?oA(w,Y,X):Y,j=[fw(j1(),".config",w),fw(j1(),".config"),j1()];for(let W of j){if(X)gw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)gw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?oA(w,A,J):A;try{let W=fw(Y,"package.json");if(!kK(W))return null;let Q={};try{Q=JSON.parse(ZK(W,"utf8"))}catch(B){if(J)gw.warn("Failed to parse package.json:",[B instanceof Error?B:Error(String(B))]);return null}let f=Q[w],z=w;if(!f&&$){let B=Array.isArray($)?$:[$];for(let G of B){if(!G)continue;if(Q[G]){f=Q[G],z=G;break}}}if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)gw.success(`Configuration loaded from package.json: ${z}`);return{config:OB(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)gw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:oA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw R1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return BX.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);BX.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,fw(w,"config"),fw(w,".config"),$?fw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(fw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[fw(j1(),".config",w),fw(j1(),".config"),j1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function oA(w,$,Y=!1){let A=new UW,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=CX.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function PB(w){return lU.readFileSync(w,"utf8")}function pU(w,$){let Y=[];function A(X){let J;try{J=lU.readdirSync(X)}catch{return}for(let U of J){let j=Nw.join(X,U);try{if(lU.statSync(j).isDirectory())A(j);else if(U===$)Y.push(X)}catch{continue}}}return A(w),Y}function S(w,$,Y){if(Y||f0.verbose)console.debug(`[tlsx:${w}] ${$}`)}function iB(){return ZB.env.SUDO_PASSWORD}function rT(w){let $=w.toLowerCase();return lT.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function MX(w){if(Array.isArray(w))return w.map((Y)=>MX(Y));if(typeof w==="string")return pT.test(w)?xz:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(rT(Y)){$[Y]=xz;continue}$[Y]=MX(A)}return $}function hX(w){return JSON.stringify(MX(w))}function tT(w){let $=iB();if(!$||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(w))return w;let Y=$.replace(/'/g,"'\\''"),A=w.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function z$(w,$={}){let Y=tT(w);try{let{stdout:A,stderr:X}=await nT(Y,{cwd:$.cwd||ZB.cwd(),timeout:$.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${w}
125
+ Error: ${A.message}`);throw X.stack=A.stack,X}}function bB(w){if(w.domain)return w.domain;if(w.domains?.length)return w.domains[0];throw Error("Either domain or domains must be specified")}function WW(w){let $=Nw.join(gT.homedir(),".stacks","ssl"),Y=w.basePath&&w.basePath.trim()!==""?w.basePath:f0.basePath&&f0.basePath.trim()!==""?f0.basePath:$,A=w.certPath?Nw.isAbsolute(w.certPath)?w.certPath:Nw.join(Y,w.certPath):Nw.join(Y,f0.certPath),X=w.keyPath?Nw.isAbsolute(w.keyPath)?w.keyPath:Nw.join(Y,w.keyPath):Nw.join(Y,f0.keyPath),J=w.caCertPath?Nw.isAbsolute(w.caCertPath)?w.caCertPath:Nw.join(Y,w.caCertPath):Nw.join(Y,f0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function uB(w){let $=[],Y=new Set;if(w.domain)Y.add(w.domain);if(w.domains?.length)w.domains.forEach((A)=>Y.add(A));for(let A of Y)$.push({type:2,value:A});if(w.altNameIPs?.length)for(let A of w.altNameIPs)$.push({type:7,ip:A});if(w.altNameURIs?.length)for(let A of w.altNameURIs)$.push({type:6,value:A});if(w.subjectAltNames?.length)$.push(...w.subjectAltNames);return S(h.CERT,`Generated ${$.length} Subject Alternative Names`,w.verbose),$}function jW(w){let $=w.notBeforeDays??Hw.DEFAULT_NOT_BEFORE_DAYS,Y=w.validityDays??(w.validityYears?w.validityYears*365:Hw.DEFAULT_VALIDITY_DAYS);S(h.CERT,"Calculating certificate validity dates",w.verbose);let A=new Date(Date.now()-86400*$*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),S(h.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,w.verbose),{notBefore:A,notAfter:X}}function AY(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function $w(w,$){let Y=AY($.length);return Buffer.concat([Buffer.from([w]),Y,$])}function jY(w){let $=w.split(".").map(Number),Y=[];Y.push(40*$[0]+$[1]);for(let A=2;A<$.length;A++){let X=$[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return $w(Rw.OID,Buffer.from(Y))}function rU(w){let $;if(typeof w==="bigint"){let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else $=w;if($[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return $w(Rw.INTEGER,$)}function cB(w,$=0){return $w(Rw.BIT_STRING,Buffer.concat([Buffer.from([$]),w]))}function vB(w){return $w(Rw.OCTET_STRING,w)}function ww(...w){return $w(Rw.SEQUENCE,Buffer.concat(w))}function aT(...w){return $w(Rw.SET,Buffer.concat(w))}function sT(w){return $w(Rw.PRINTABLE_STRING,Buffer.from(w,"ascii"))}function oT(w){return $w(Rw.UTF8_STRING,Buffer.from(w,"utf8"))}function eT(){return Buffer.from([Rw.NULL,0])}function kz(w,$,Y=!0){let A=160|w|(Y?0:0),X=AY($.length);return Buffer.concat([Buffer.from([A]),X,$])}function Zz(w){let $=w.getUTCFullYear();if($>=2050){let Y=w.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return $w(Rw.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=($%100).toString().padStart(2,"0"),A=(w.getUTCMonth()+1).toString().padStart(2,"0"),X=w.getUTCDate().toString().padStart(2,"0"),J=w.getUTCHours().toString().padStart(2,"0"),U=w.getUTCMinutes().toString().padStart(2,"0"),j=w.getUTCSeconds().toString().padStart(2,"0"),W=`${Y}${A}${X}${J}${U}${j}Z`;return $w(Rw.UTC_TIME,Buffer.from(W,"ascii"))}}function w7(w,$){return ww(Zz(w),Zz($))}function Pz(w){let $=[];for(let Y of w){let A;switch(Y.shortName){case"CN":A=d0.COMMON_NAME;break;case"C":A=d0.COUNTRY;break;case"L":A=d0.LOCALITY;break;case"ST":A=d0.STATE;break;case"O":A=d0.ORGANIZATION;break;case"OU":A=d0.ORGANIZATIONAL_UNIT;break;default:continue}let X=Y.shortName==="C"?sT(Y.value):oT(Y.value),J=ww(jY(A),X);$.push(aT(J))}return ww(...$)}function mB(w){return ww(jY(w),eT())}function $7(w){return w.export({type:"spki",format:"der"})}function Y7(w){if(w.includes(":")){let $=w;if(w.includes("::")){let X=w.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],j=8-J.length-U.length,W=Array.from({length:j},()=>"0");$=[...J,...W,...U].join(":")}let Y=$.split(":"),A=Buffer.alloc(16);for(let X=0;X<8;X++){let J=Number.parseInt(Y[X]||"0",16);A.writeUInt16BE(J,X*2)}return A}else{let $=w.split(".").map((Y)=>Number.parseInt(Y,10));return Buffer.from($)}}function A7(w){let $=[];for(let Y of w)if(Y.type===2&&Y.value){let A=AY(Y.value.length);$.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=Y7(Y.ip),X=AY(A.length);$.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=AY(Y.value.length);$.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return ww(...$)}function X7(w,$){if(w){if($!==void 0)return ww($w(1,Buffer.from([255])),rU($));return ww($w(1,Buffer.from([255])))}return ww()}function J7(w){let $=0;if(w.digitalSignature)$|=128;if(w.keyEncipherment)$|=32;if(w.keyCertSign)$|=4;if(w.cRLSign)$|=2;let Y=0,A=$;while(A>0&&(A&1)===0)Y++,A>>=1;if($===0)Y=7;return cB(Buffer.from([$]),Y)}function U7(w){let $=[];if(w.serverAuth)$.push(jY(d0.SERVER_AUTH));if(w.clientAuth)$.push(jY(d0.CLIENT_AUTH));return ww(...$)}function $Y(w,$,Y){let A=[jY(w)];if($)A.push($w(1,Buffer.from([255])));return A.push(vB(Y)),ww(...A)}function W7(w){let $=[];if($.push(kz(0,rU(2))),$.push(rU(w.serialNumber)),$.push(mB(d0.SHA256_WITH_RSA)),$.push(Pz(w.issuer)),$.push(w7(w.notBefore,w.notAfter)),$.push(Pz(w.subject)),$.push($7(w.publicKey)),w.extensions){let Y=[];if(w.extensions.basicConstraints)Y.push($Y(d0.BASIC_CONSTRAINTS,w.extensions.basicConstraints.critical??!0,X7(w.extensions.basicConstraints.isCA,w.extensions.basicConstraints.pathLenConstraint)));if(w.extensions.keyUsage)Y.push($Y(d0.KEY_USAGE,w.extensions.keyUsage.critical??!0,J7(w.extensions.keyUsage)));if(w.extensions.extendedKeyUsage)Y.push($Y(d0.EXTENDED_KEY_USAGE,!1,U7(w.extensions.extendedKeyUsage)));if(w.extensions.subjectAltName?.length)Y.push($Y(d0.SUBJECT_ALT_NAME,!1,A7(w.extensions.subjectAltName)));if(w.extensions.subjectKeyIdentifier)Y.push($Y(d0.SUBJECT_KEY_IDENTIFIER,!1,vB(w.extensions.subjectKeyIdentifier)));if(Y.length>0)$.push(kz(3,ww(...Y)))}return ww(...$)}function j7(w,$){let Y=M1.createSign("SHA256");Y.update(w);let A=Y.sign($);return ww(w,mB(d0.SHA256_WITH_RSA),cB(A))}function Q7(w,$){let Y=w.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${$}-----
126
126
  ${A.join(`
127
127
  `)}
128
128
  -----END ${$}-----
129
- `}function jW(){let w=I1.randomBytes(20);return w[0]=w[0]&127||1,w}function vB(w=2048){let{privateKey:$,publicKey:Y}=I1.generateKeyPairSync("rsa",{modulusLength:w});return{privateKey:$,publicKey:Y}}function j7(w){let $=w.export({type:"spki",format:"der"});return I1.createHash("sha1").update($).digest()}function mB(w){let $={serialNumber:w.serialNumber||jW(),notBefore:w.notBefore,notAfter:w.notAfter,subject:w.subject,issuer:w.issuer||w.subject,publicKey:w.publicKey,extensions:{basicConstraints:{isCA:w.isCA??!1,critical:!0,pathLenConstraint:w.pathLenConstraint},subjectKeyIdentifier:j7(w.publicKey)}};if(w.keyUsage)$.extensions.keyUsage={...w.keyUsage,critical:!0};if(w.extendedKeyUsage)$.extensions.extendedKeyUsage=w.extendedKeyUsage;if(w.subjectAltName?.length)$.extensions.subjectAltName=w.subjectAltName;let Y=J7($),A=U7(Y,w.signingKey);return{certificate:W7(A,"CERTIFICATE"),certificateDer:A}}function gB(w){return w.export({type:"pkcs8",format:"pem"})}function Q7(w){return I1.createPrivateKey(w)}function f7(w){let $=new I1.X509Certificate(w),Y=$.publicKey,A=[],X=$.subject.split(`
130
- `);for(let J of X){let[U,...j]=J.split("="),W=j.join("=");if(U&&W)A.push({shortName:U.trim(),value:W.trim()})}return{publicKey:Y,subject:A}}async function QW(w={}){S("ca","Creating new Root CA Certificate",w.verbose);let $=w.keySize||qw.DEFAULT_KEY_SIZE;S("ca",`Generating ${$}-bit RSA key pair`,w.verbose);let{privateKey:Y,publicKey:A}=vB($),X=[{shortName:"C",value:w.countryName||f0.countryName},{shortName:"ST",value:w.stateName||f0.stateName},{shortName:"L",value:w.localityName||f0.localityName},{shortName:"O",value:w.organization||"Local Development CA"},{shortName:"OU",value:w.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:w.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=WW({validityYears:w.validityYears||qw.DEFAULT_CA_VALIDITY_YEARS,verbose:w.verbose}),{certificate:j}=mB({serialNumber:jW(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:j,privateKey:gB(Y),notBefore:J,notAfter:U}}async function fW(w){if(S("ca","Generating new certificate",w.verbose),S("ca",`Options: ${SX(w)}`,w.verbose),!w.domain&&!w.domains?.length)throw Error("Either domain or domains must be specified");if(!w.rootCA?.certificate||!w.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:$}=f7(w.rootCA.certificate),Y=Q7(w.rootCA.privateKey);S("ca",`Generating ${qw.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,w.verbose);let A=qw.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=vB(A),U=w.commonName||PB(w),j=w.certificateAttributes||[{shortName:"C",value:w.countryName||f0.countryName},{shortName:"ST",value:w.stateName||f0.stateName},{shortName:"L",value:w.localityName||f0.localityName},{shortName:"O",value:w.organizationName||f0.organizationName},{shortName:"CN",value:U}],{notBefore:W,notAfter:Q}=WW({validityDays:w.validityDays||qw.DEFAULT_VALIDITY_DAYS,verbose:w.verbose}),f=iB(w),z=w.keyUsage||{digitalSignature:!0,keyEncipherment:!0},B=w.extKeyUsage||{serverAuth:!0},{certificate:G}=mB({serialNumber:jW(),notBefore:W,notAfter:Q,subject:j,issuer:$,publicKey:J,signingKey:Y,isCA:w.basicConstraints?.cA??!1,pathLenConstraint:w.basicConstraints?.pathLenConstraint,keyUsage:z,extendedKeyUsage:B,subjectAltName:f});return{certificate:G,privateKey:gB(X),notBefore:W,notAfter:Q}}function dB(w,$){S(h.STORAGE,`Storing certificate and private key with options: ${SX($)}`,$?.verbose);let{certPath:Y,keyPath:A}=UW({basePath:$?.basePath,certPath:$?.certPath,keyPath:$?.keyPath});S(h.STORAGE,`Certificate path: ${Y}`,$?.verbose),S(h.STORAGE,`Private key path: ${A}`,$?.verbose);let X=rU.dirname(Y);if(!tw.existsSync(X))S(h.STORAGE,`Creating certificate directory: ${X}`,$?.verbose),tw.mkdirSync(X,{recursive:!0});S(h.STORAGE,"Writing certificate file",$?.verbose),tw.writeFileSync(Y,w.certificate);let J=rU.dirname(A);if(!tw.existsSync(J))S(h.STORAGE,`Creating private key directory: ${J}`,$?.verbose),tw.mkdirSync(J,{recursive:!0});return S(h.STORAGE,"Writing private key file",$?.verbose),tw.writeFileSync(A,w.privateKey),S(h.STORAGE,"Certificate and private key stored successfully",$?.verbose),Y}function nB(w,$){S(h.STORAGE,"Storing CA certificate",$?.verbose);let{caCertPath:Y}=UW({basePath:$?.basePath,caCertPath:$?.caCertPath});S(h.STORAGE,`CA certificate path: ${Y}`,$?.verbose);let A=rU.dirname(Y);if(!tw.existsSync(A))S(h.STORAGE,`Creating CA certificate directory: ${A}`,$?.verbose),tw.mkdirSync(A,{recursive:!0});return S(h.STORAGE,"Writing CA certificate file",$?.verbose),tw.writeFileSync(Y,w),S(h.STORAGE,"CA certificate stored successfully",$?.verbose),Y}function hX(w){let $;if(w.startsWith("-----BEGIN CERTIFICATE-----"))$=w;else $=kB(w);return new z7.X509Certificate($)}function OX(w){return hX(w).fingerprint256.replace(/:/g,"").toUpperCase()}function zW(w){return lB(hX(w).subject)}function B7(w){let $=[],Y=w.split(`
131
- `);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)$.push({shortName:X.trim(),value:U.trim()})}return $}function lB(w){return B7(w).find(($)=>$.shortName==="CN")?.value||""}function G7(w){let $=[],Y=lB(w.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))$.push(Y);let A=w.subjectAltName;if(A){let X=A.split(", ");for(let J of X)if(J.startsWith("DNS:"))$.push(J.slice(4))}return[...new Set($)]}function BW(w,$){let Y=hX(w),A=G7(Y);for(let X of A){if(X===$)return!0;if(X.startsWith("*.")){let J=X.slice(2);if($.endsWith(J)&&$.indexOf(".")===$.lastIndexOf("."))return!0}}return!1}async function K7(w,$){if(MX.platform()!=="darwin")return!1;try{let Y=OX(w);if(!Y)return S(h.TRUST,"Could not extract certificate fingerprint",$),!1;try{if(E7("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
132
- `).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return S(h.TRUST,"Certificate fingerprint found in system keychain",$),!0}catch{}return S(h.TRUST,"Certificate fingerprint not found in system keychain",$),!1}catch(Y){return S(h.TRUST,`Error checking certificate trust: ${Y}`,$),!1}}async function GW(w,$,Y){S(h.TRUST,`Adding certificate to system trust store with options: ${SX(Y)}`,Y?.verbose),S(h.TRUST,"Storing certificate and private key",Y?.verbose);let A=dB(w,Y);S(h.TRUST,"Storing CA certificate",Y?.verbose);let X=nB($,Y),J=MX.platform();S(h.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=q7[J];if(!U){let j=`Unsupported platform: ${J}`;throw S(h.TRUST,`Error: ${j}`,Y?.verbose),Error(j)}return await U.addCertificate(X,Y),S(h.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var TK,Zz=30000,yX,cz="https://acme-staging-v02.api.letsencrypt.org/directory",vz="https://acme-v02.api.letsencrypt.org/directory",JX,yK="1.2.840.10045.2.1",IK="1.2.840.10045.3.1.7",CK="1.2.840.10045.4.3.2",VK="2.5.4.3",LK="1.2.840.113549.1.9.14",SK="2.5.29.17",zX,aU,qF,HF=(w)=>w,MF=(w,$)=>{for(var Y in $)qF(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:RF.bind($,Y)})},yF=(w,$)=>()=>(w&&($=w(w=0)),$),wB,QB,M1,fY,fB,aF,sF,qz,$X,PU,_0,o,oF,Hz,eF,Rz,wT,$T,IU,YT,Mz,yz,CU,AT,XT,JT,UT,YX,zB,WT,D0,jT,QT,Iz,AX,iU,N0,u,fT,Cz,zT,Vz,BT,GT,VU,ET,Lz,Sz,KT,LU,FT,TT,NT,qT,HT,XX,BB,RT,MT="0.15.6",s0,FX,WY,bU,uU,TX,cU,vU,jY,mU,gU,G$,GB,EB,Nw,aw,KB,FB,yT,CT,TB,NX,$C,I0,m,YC,LT,AC,ST,XC,JC,hz,UC,hT,OT,WC,Oz,jC,QC,fC,zC,BC,SU,_T,GC,Rw,qB,qX,HB,RB,XW,MB,yB,HX,IB,CB,y1,bT,nw,EC,KC,FC,DB,f0,qw,h,R1,gT,_z="[redacted]",dT,nT,Hw,d0,F7,T7,N7,q7;var pB=a(()=>{TK=FK(import.meta.url);yX=new JY;JX=class JX extends Error{problem;httpStatus;constructor(w,$,Y){super(w);this.name="AcmeError",this.problem=$,this.httpStatus=Y}};zX=new oz,aU=new ez,qF=Object.defineProperty;wB={};MF(wB,{withErrorRecovery:()=>AB,tryLoadConfig:()=>lF,loadConfigWithResult:()=>dF,loadConfig:()=>jB,isRetryableError:()=>bF,isConfigNotFoundError:()=>iF,isBunfigError:()=>XB,globalPerformanceMonitor:()=>fY,globalCache:()=>M1,getEnvOrDefault:()=>uF,generateConfigTypes:()=>pF,defaultGeneratedDir:()=>FB,defaultConfigDir:()=>KB,deepMergeWithArrayStrategy:()=>$W,deepMerge:()=>JB,createLibraryConfig:()=>rF,config:()=>nF,bunfigPlugin:()=>tF,applyEnvVarsToConfig:()=>AY,TypeGenerationError:()=>vU,SchemaValidationError:()=>jY,PluginError:()=>gU,PerformanceMonitor:()=>oU,FileSystemError:()=>cU,ErrorFactory:()=>G$,EnvVarError:()=>TX,EnvProcessor:()=>CX,ConfigValidator:()=>YW,ConfigValidationError:()=>bU,ConfigNotFoundError:()=>FX,ConfigMergeError:()=>uU,ConfigLoader:()=>AW,ConfigLoadError:()=>WY,ConfigFileLoader:()=>VX,ConfigCache:()=>sU,CacheUtils:()=>fB,BunfigError:()=>s0,BrowserConfigError:()=>mU,ArrayMergeStrategies:()=>GB});yT=yF(async()=>{QB=import.meta.require,M1=new sU,fY=new oU,fB={createKey:IF,isEquivalent:CF,estimateMemoryUsage:VF},aF=QX(kU.cwd(),"config"),sF=QX(kU.cwd(),"src/generated"),qz=jX.env.CLARITY_LOG_DIR||uK(hF(),"logs"),$X={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:qz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},PU=await OF(),_0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},o=_0,oF=_0.red,Hz=_0.green,eF=_0.yellow,Rz=_0.blue,wT=_0.magenta,$T=_0.cyan,IU=_0.white,YT=_0.gray,Mz=_0.bgRed,yz=_0.bgYellow,CU=_0.bold,AT=_0.dim,XT=_0.italic,JT=_0.underline,UT=_0.reset,YX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},zB={debug:"\uD83D\uDD0D",info:Rz("ℹ"),success:Hz("✓"),warning:yz(IU(CU(" WARN "))),error:Mz(IU(CU(" ERROR ")))},WT=new GX("stacks"),D0=new GX("bunfig",{showTags:!0}),jT=m0(UY.cwd(),"config"),QT=m0(UY.cwd(),"src/generated"),Iz=WX.env.CLARITY_LOG_DIR||iK(kF(),"logs"),AX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Iz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},iU=await ZF(),N0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},u=N0,fT=N0.red,Cz=N0.green,zT=N0.yellow,Vz=N0.blue,BT=N0.magenta,GT=N0.cyan,VU=N0.white,ET=N0.gray,Lz=N0.bgRed,Sz=N0.bgYellow,KT=N0.bgGray,LU=N0.bold,FT=N0.dim,TT=N0.italic,NT=N0.underline,qT=N0.strikethrough,HT=N0.reset,XX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},BB={debug:"\uD83D\uDD0D",info:Vz("ℹ"),success:Cz("✓"),warning:Sz(VU(LU(" WARN "))),error:Lz(VU(LU(" ERROR ")))},RT=new KX("stacks"),s0=class extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},FX=class extends s0{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${A} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}},WY=class extends s0{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}},bU=class extends s0{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},uU=class extends s0{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},TX=class extends s0{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}},cU=class extends s0{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},vU=class extends s0{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,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:w,configName:Y,validationErrors:$,errorCount:$.length})}},mU=class extends s0{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}},gU=class extends s0{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},G$={configNotFound(w,$,Y){return new FX(w,$,Y)},configLoad(w,$,Y){return new WY(w,$,Y)},configValidation(w,$,Y){return new bU(w,$,Y)},configMerge(w,$,Y,A){return new uU(w,$,Y,A)},envVar(w,$,Y,A){return new TX(w,$,Y,A)},fileSystem(w,$,Y){return new cU(w,$,Y)},typeGeneration(w,$,Y){return new vU(w,$,Y)},schemaValidation(w,$,Y){return new jY(w,$,Y)},browserConfig(w,$,Y,A){return new mU(w,$,Y,A)},plugin(w,$,Y){return new gU(w,$,Y)}},GB={replace:"replace",concat:"concat",smart:"smart"},EB=/^https?:\/\//,Nw=new KX("bunfig",{showTags:!0}),aw=new AW,KB=g0(Z$.cwd(),"config"),FB=g0(Z$.cwd(),"src/generated")});CT=fX.env.CLARITY_LOG_DIR||WF(IT(),"logs"),TB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:CT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},NX={...TB},$C=(async()=>{try{let{loadConfig:w}=await yT().then(()=>wB),$=await w({name:"clarity",alias:"logging",defaultConfig:TB,cwd:fX.cwd()});if($)Object.assign(NX,$)}catch{}return NX})();I0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},m=I0,YC=I0.red,LT=I0.green,AC=I0.yellow,ST=I0.blue,XC=I0.magenta,JC=I0.cyan,hz=I0.white,UC=I0.gray,hT=I0.bgRed,OT=I0.bgYellow,WC=I0.bgGray,Oz=I0.bold,jC=I0.dim,QC=I0.italic,fC=I0.underline,zC=I0.strikethrough,BC=I0.reset,SU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_T={debug:"\uD83D\uDD0D",info:ST("ℹ"),success:LT("✓"),warning:OT(hz(Oz(" WARN "))),error:hT(hz(Oz(" ERROR ")))};GC=new LX("stacks");Rw=class Rw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};qB=class qB extends Rw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};qX=class qX extends Rw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};HB=class HB extends Rw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};RB=class RB extends Rw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};XW=class XW extends Rw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};MB=class MB extends Rw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};yB=class yB extends Rw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};HX=class HX extends Rw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};IB=class IB extends Rw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};CB=class CB extends Rw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};y1={configNotFound(w,$,Y){return new qB(w,$,Y)},configLoad(w,$,Y){return new qX(w,$,Y)},configValidation(w,$,Y){return new HB(w,$,Y)},configMerge(w,$,Y,A){return new RB(w,$,Y,A)},envVar(w,$,Y,A){return new XW(w,$,Y,A)},fileSystem(w,$,Y){return new MB(w,$,Y)},typeGeneration(w,$,Y){return new yB(w,$,Y)},schemaValidation(w,$,Y){return new HX(w,$,Y)},browserConfig(w,$,Y,A){return new IB(w,$,Y,A)},plugin(w,$,Y){return new CB(w,$,Y)}};bT=/^https?:\/\//;nw=new LX("bunfig",{showTags:!0});EC=new _B;KC=Ww(IX.cwd(),"config"),FC=Ww(IX.cwd(),"src/generated"),DB={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:QU.join(jU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:QU.join(jU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:QU.join(jU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},f0=DB,qw={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"},h={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},R1={info:(...w)=>console.log(...w),warn:(...w)=>console.warn(...w),success:(...w)=>console.log(...w),error:(...w)=>console.error(...w),debug:(...w)=>console.debug(...w)};gT=mT(cT);dT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),nT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;Hw={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},d0={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"};F7={platform:"darwin",async addCertificate(w,$){if(await K7(w,$?.verbose)){S(h.TRUST,"Certificate is already trusted, skipping trust store update",$?.verbose),R1.success("Certificate is already trusted in system keychain");return}S(h.TRUST,"Adding certificate to macOS keychain",$?.verbose),await B$(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${w}`)},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(h.TRUST,`Removing certificate ${A} from macOS keychain`,$?.verbose);try{await B$(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),S(h.TRUST,`Removed certificate ${A} from macOS keychain`,$?.verbose)}catch(X){throw S(h.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},T7={platform:"win32",async addCertificate(w,$){S(h.TRUST,"Adding certificate to Windows certificate store",$?.verbose),await B$(`certutil -f -v -addstore -enterprise Root ${w}`)},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(h.TRUST,`Removing certificate ${A} from Windows certificate store`,$?.verbose);try{await B$(`certutil -delstore -enterprise Root "${A}"`),S(h.TRUST,`Removed certificate ${A} from Windows certificate store`,$?.verbose)}catch(X){throw S(h.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},N7={platform:"linux",async addCertificate(w,$){S(h.TRUST,"Adding certificate to Linux certificate store",$?.verbose);let Y=MX.homedir(),A=qw.LINUX_CERT_DB_FILENAME,X=qw.LINUX_TRUST_ARGS;S(h.TRUST,`Searching for certificate databases in ${Y}`,$?.verbose);let J=lU(Y,A);if(J.length===0){R1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){S(h.TRUST,`Processing certificate database in ${U}`,$?.verbose);try{S(h.TRUST,`Attempting to delete existing cert for ${f0.commonName}`,$?.verbose),await B$(`certutil -d sql:${U} -D -n ${f0.commonName}`)}catch(j){S(h.TRUST,`Warning: Error deleting existing cert: ${j}`,$?.verbose),console.warn(`Error deleting existing cert: ${j}`)}S(h.TRUST,`Adding new certificate to ${U}`,$?.verbose),await B$(`certutil -d sql:${U} -A -t ${X} -n ${f0.commonName} -i ${w}`),R1.info(`Cert added to ${U}`)}},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(h.TRUST,`Removing certificate ${A} from Linux certificate store`,$?.verbose);let X=MX.homedir(),J=qw.LINUX_CERT_DB_FILENAME;S(h.TRUST,`Searching for certificate databases in ${X}`,$?.verbose);let U=lU(X,J);if(U.length===0){R1.warn("No certificate databases found. Cannot remove certificate.");return}for(let j of U){S(h.TRUST,`Processing certificate database in ${j}`,$?.verbose);try{await B$(`certutil -d sql:${j} -D -n "${A}"`),R1.info(`Cert removed from ${j}`)}catch(W){S(h.TRUST,`Error removing cert from ${j}: ${W}`,$?.verbose),console.warn(`Error removing cert from ${j}: ${W}`)}}}},q7={darwin:F7,win32:T7,linux:N7}});var _X=a(()=>{pB()});function P$(w){try{return OX(w)}catch{return null}}function EW(w){try{return zW(w)||null}catch{return null}}function KW(w,$){try{return $.every((Y)=>BW(w,Y))}catch{return!1}}var DX=a(()=>{_X()});import{existsSync as rB,statSync as tB}from"fs";import{existsSync as kW,mkdirSync as V7,readdirSync as L7,writeFileSync as S7}from"fs";import{homedir as C1}from"os";import{dirname as aB,resolve as l0}from"path";import i$ from"process";import{join as h7,relative as O7,resolve as sB}from"path";import tX from"process";import{existsSync as x9,mkdirSync as HV,readdirSync as RV,writeFileSync as MV}from"fs";import{homedir as FW}from"os";import{dirname as CV,resolve as n0}from"path";import BY from"process";import{join as _7,relative as D7,resolve as oB}from"path";import aX from"process";import{existsSync as k9,mkdirSync as OV,readdirSync as _V,writeFileSync as DV}from"fs";import{dirname as kV,resolve as sX}from"path";import ZW from"process";import{Buffer as K$}from"buffer";import{createCipheriv as x7,createDecipheriv as k7,randomBytes as TW}from"crypto";import{closeSync as NW,createReadStream as eB,createWriteStream as Z7,existsSync as qW,fsyncSync as w9,openSync as $9,writeFileSync as P7}from"fs";import{access as i7,constants as Y9,mkdir as b7,readdir as xX,rename as A9,stat as V1,unlink as kX,writeFile as HW}from"fs/promises";import{join as L1}from"path";import x0 from"process";import{pipeline as u7}from"stream/promises";import{createGzip as X9}from"zlib";import S1 from"process";import ew from"process";import{Buffer as sw}from"buffer";import{createCipheriv as c7,createDecipheriv as v7,randomBytes as RW}from"crypto";import{closeSync as MW,createReadStream as J9,createWriteStream as m7,existsSync as ZX,fsyncSync as U9,openSync as W9,writeFileSync as g7}from"fs";import{access as d7,constants as j9,mkdir as n7,readdir as PX,rename as Q9,stat as h1,unlink as iX,writeFile as yW}from"fs/promises";import{isAbsolute as l7,join as O1,resolve as p7}from"path";import Z from"process";import{pipeline as r7}from"stream/promises";import{createGzip as f9}from"zlib";import _1 from"process";import w$ from"process";import bX from"process";import{existsSync as uX}from"fs";import{resolve as IW}from"path";import{existsSync as t7}from"fs";import{existsSync as a7,readdirSync as s7}from"fs";import{extname as CW,resolve as z9}from"path";import o7 from"process";import{join as eN,relative as wq,resolve as y9}from"path";import X8 from"process";import{Buffer as ow}from"buffer";import{createCipheriv as Aq,createDecipheriv as Xq,randomBytes as OW}from"crypto";import{closeSync as _W,createReadStream as I9,createWriteStream as Jq,existsSync as vX,fsyncSync as C9,openSync as V9,writeFileSync as Uq}from"fs";import{access as Wq,constants as L9,mkdir as jq,readdir as mX,rename as S9,stat as D1,unlink as gX,writeFile as DW}from"fs/promises";import{isAbsolute as Qq,join as x1,resolve as fq}from"path";import P from"process";import{pipeline as zq}from"stream/promises";import{createGzip as h9}from"zlib";import k1 from"process";import $$ from"process";function y7(w,$){this[w]=M7.bind(null,$)}class nW{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!rB(w))return!0;return tB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=rB(Y)?tB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class lW{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function e7(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function wN(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function $N(w){return w.getStats().size*2}function pW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&A0($[0])&&"id"in $[0]&&$[0].id===3&&A0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(A0($)&&A0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(A0(w)&&"arr"in w&&Array.isArray(w.arr)&&A0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&A0($[0])&&A0(w[0])){let A=[...$];for(let X of w)if(A0(X)&&"name"in X){if(!A.find((U)=>A0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(A0(X)&&"path"in X){if(!A.find((U)=>A0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>oX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!A0($)||!A0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(A0(X)&&A0(Y[A]))Y[A]=pW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&A0(X[0])&&A0(Y[A][0])){let J=[...X];for(let U of Y[A])if(A0(U)&&"name"in U){if(!J.find((W)=>A0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(A0(U)&&"path"in U){if(!J.find((W)=>A0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>oX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function oX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!oX(w[Y],$[Y]))return!1;return!0}if(A0(w)&&A0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!oX(w[X],$[X]))return!1}return!0}return!1}function A0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function YN(w,$){if(!k9(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return pW($,A)}catch{return null}}catch{return null}}async function AN({name:w="",cwd:$,defaultConfig:Y}){let A=$||ZW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=sX(A,`${U}${j}`),Q=await YN(W,Y);if(Q!==null)return Q}try{let U=sX(A,"package.json");if(k9(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return pW(Y,W)}catch{}}}catch{}return Y}function XN(w,$={}){let Y=aX.cwd();while(Y.includes("storage"))Y=oB(Y,"..");let A=oB(Y,w||"");if($?.relative)return D7(aX.cwd(),A);return A}async function JN(){try{let w=await AN({name:"clarity",defaultConfig:nX,cwd:aX.cwd(),endpoint:"",headers:{}});return{...nX,...w}}catch{return nX}}function j0(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UN(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ew<"u"){let w=ew.type;if(w==="renderer"||w==="worker")return!1;return!!(ew.versions&&(ew.versions.node||ew.versions.bun))}return!1}class Z9{async format(w){let $=await UN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:S1.pid,hostname:$(),environment:S1.env.NODE_ENV||"development",platform:S1.platform,version:S1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:S1.env.NODE_ENV||S1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class eX{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=w,this.config={...iW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Z9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...lX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...lX};return{...lX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:iW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await i7(this.config.logDirectory,Y9.F_OK|Y9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await b7(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:K$.from(w);try{if(!qW(this.currentLogFile))await HW(this.currentLogFile,"",{mode:420});if(X=$9(this.currentLogFile,"a",420),P7(X,W,{flag:"a"}),w9(X),X!==void 0)NW(X),X=void 0;if((await V1(this.currentLogFile)).size===0){if(await HW(this.currentLogFile,W,{flag:"w",mode:420}),(await V1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{NW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 L1(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 L1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return L1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(j0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return TW(16).toString("hex")}generateKey(){return TW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=TW(16),A=x7("aes-256-gcm",$,Y),X=K$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:K$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=X9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(K$.from(K$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(j0())return;let w=await V1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await xX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await V1(Y).catch(()=>null))try{if(await A9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await kX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await HW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await V1(Y).catch(()=>null))await A9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await xX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await kX(L1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=eB(w),A=Z7($),X=X9();await u7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),qW(this.currentLogFile))try{let w=$9(this.currentLogFile,"r+");w9(w),NW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!j0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await xX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await kX(L1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?e.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${e.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!j0()){let Q=n9[w],f=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:e.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:e.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
133
- `);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:e.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!j0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
129
+ `}function QW(){let w=M1.randomBytes(20);return w[0]=w[0]&127||1,w}function gB(w=2048){let{privateKey:$,publicKey:Y}=M1.generateKeyPairSync("rsa",{modulusLength:w});return{privateKey:$,publicKey:Y}}function f7(w){let $=w.export({type:"spki",format:"der"});return M1.createHash("sha1").update($).digest()}function dB(w){let $={serialNumber:w.serialNumber||QW(),notBefore:w.notBefore,notAfter:w.notAfter,subject:w.subject,issuer:w.issuer||w.subject,publicKey:w.publicKey,extensions:{basicConstraints:{isCA:w.isCA??!1,critical:!0,pathLenConstraint:w.pathLenConstraint},subjectKeyIdentifier:f7(w.publicKey)}};if(w.keyUsage)$.extensions.keyUsage={...w.keyUsage,critical:!0};if(w.extendedKeyUsage)$.extensions.extendedKeyUsage=w.extendedKeyUsage;if(w.subjectAltName?.length)$.extensions.subjectAltName=w.subjectAltName;let Y=W7($),A=j7(Y,w.signingKey);return{certificate:Q7(A,"CERTIFICATE"),certificateDer:A}}function nB(w){return w.export({type:"pkcs8",format:"pem"})}function z7(w){return M1.createPrivateKey(w)}function B7(w){let $=new M1.X509Certificate(w),Y=$.publicKey,A=[],X=$.subject.split(`
130
+ `);for(let J of X){let[U,...j]=J.split("="),W=j.join("=");if(U&&W)A.push({shortName:U.trim(),value:W.trim()})}return{publicKey:Y,subject:A}}async function fW(w={}){S("ca","Creating new Root CA Certificate",w.verbose);let $=w.keySize||Hw.DEFAULT_KEY_SIZE;S("ca",`Generating ${$}-bit RSA key pair`,w.verbose);let{privateKey:Y,publicKey:A}=gB($),X=[{shortName:"C",value:w.countryName||f0.countryName},{shortName:"ST",value:w.stateName||f0.stateName},{shortName:"L",value:w.localityName||f0.localityName},{shortName:"O",value:w.organization||"Local Development CA"},{shortName:"OU",value:w.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:w.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=jW({validityYears:w.validityYears||Hw.DEFAULT_CA_VALIDITY_YEARS,verbose:w.verbose}),{certificate:j}=dB({serialNumber:QW(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:j,privateKey:nB(Y),notBefore:J,notAfter:U}}async function zW(w){if(S("ca","Generating new certificate",w.verbose),S("ca",`Options: ${hX(w)}`,w.verbose),!w.domain&&!w.domains?.length)throw Error("Either domain or domains must be specified");if(!w.rootCA?.certificate||!w.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:$}=B7(w.rootCA.certificate),Y=z7(w.rootCA.privateKey);S("ca",`Generating ${Hw.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,w.verbose);let A=Hw.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=gB(A),U=w.commonName||bB(w),j=w.certificateAttributes||[{shortName:"C",value:w.countryName||f0.countryName},{shortName:"ST",value:w.stateName||f0.stateName},{shortName:"L",value:w.localityName||f0.localityName},{shortName:"O",value:w.organizationName||f0.organizationName},{shortName:"CN",value:U}],{notBefore:W,notAfter:Q}=jW({validityDays:w.validityDays||Hw.DEFAULT_VALIDITY_DAYS,verbose:w.verbose}),f=uB(w),z=w.keyUsage||{digitalSignature:!0,keyEncipherment:!0},B=w.extKeyUsage||{serverAuth:!0},{certificate:G}=dB({serialNumber:QW(),notBefore:W,notAfter:Q,subject:j,issuer:$,publicKey:J,signingKey:Y,isCA:w.basicConstraints?.cA??!1,pathLenConstraint:w.basicConstraints?.pathLenConstraint,keyUsage:z,extendedKeyUsage:B,subjectAltName:f});return{certificate:G,privateKey:nB(X),notBefore:W,notAfter:Q}}function lB(w,$){S(h.STORAGE,`Storing certificate and private key with options: ${hX($)}`,$?.verbose);let{certPath:Y,keyPath:A}=WW({basePath:$?.basePath,certPath:$?.certPath,keyPath:$?.keyPath});S(h.STORAGE,`Certificate path: ${Y}`,$?.verbose),S(h.STORAGE,`Private key path: ${A}`,$?.verbose);let X=tU.dirname(Y);if(!pw.existsSync(X))S(h.STORAGE,`Creating certificate directory: ${X}`,$?.verbose),pw.mkdirSync(X,{recursive:!0});S(h.STORAGE,"Writing certificate file",$?.verbose),pw.writeFileSync(Y,w.certificate);let J=tU.dirname(A);if(!pw.existsSync(J))S(h.STORAGE,`Creating private key directory: ${J}`,$?.verbose),pw.mkdirSync(J,{recursive:!0});return S(h.STORAGE,"Writing private key file",$?.verbose),pw.writeFileSync(A,w.privateKey),S(h.STORAGE,"Certificate and private key stored successfully",$?.verbose),Y}function pB(w,$){S(h.STORAGE,"Storing CA certificate",$?.verbose);let{caCertPath:Y}=WW({basePath:$?.basePath,caCertPath:$?.caCertPath});S(h.STORAGE,`CA certificate path: ${Y}`,$?.verbose);let A=tU.dirname(Y);if(!pw.existsSync(A))S(h.STORAGE,`Creating CA certificate directory: ${A}`,$?.verbose),pw.mkdirSync(A,{recursive:!0});return S(h.STORAGE,"Writing CA certificate file",$?.verbose),pw.writeFileSync(Y,w),S(h.STORAGE,"CA certificate stored successfully",$?.verbose),Y}function OX(w){let $;if(w.startsWith("-----BEGIN CERTIFICATE-----"))$=w;else $=PB(w);return new G7.X509Certificate($)}function _X(w){return OX(w).fingerprint256.replace(/:/g,"").toUpperCase()}function BW(w){return rB(OX(w).subject)}function E7(w){let $=[],Y=w.split(`
131
+ `);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)$.push({shortName:X.trim(),value:U.trim()})}return $}function rB(w){return E7(w).find(($)=>$.shortName==="CN")?.value||""}function K7(w){let $=[],Y=rB(w.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))$.push(Y);let A=w.subjectAltName;if(A){let X=A.split(", ");for(let J of X)if(J.startsWith("DNS:"))$.push(J.slice(4))}return[...new Set($)]}function GW(w,$){let Y=OX(w),A=K7(Y);for(let X of A){if(X===$)return!0;if(X.startsWith("*.")){let J=X.slice(2);if($.endsWith(J)&&$.indexOf(".")===$.lastIndexOf("."))return!0}}return!1}async function T7(w,$){if(yX.platform()!=="darwin")return!1;try{let Y=_X(w);if(!Y)return S(h.TRUST,"Could not extract certificate fingerprint",$),!1;try{if(F7("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
132
+ `).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return S(h.TRUST,"Certificate fingerprint found in system keychain",$),!0}catch{}return S(h.TRUST,"Certificate fingerprint not found in system keychain",$),!1}catch(Y){return S(h.TRUST,`Error checking certificate trust: ${Y}`,$),!1}}async function EW(w,$,Y){S(h.TRUST,`Adding certificate to system trust store with options: ${hX(Y)}`,Y?.verbose),S(h.TRUST,"Storing certificate and private key",Y?.verbose);let A=lB(w,Y);S(h.TRUST,"Storing CA certificate",Y?.verbose);let X=pB($,Y),J=yX.platform();S(h.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=R7[J];if(!U){let j=`Unsupported platform: ${J}`;throw S(h.TRUST,`Error: ${j}`,Y?.verbose),Error(j)}return await U.addCertificate(X,Y),S(h.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var qK,iz=30000,IX,mz="https://acme-staging-v02.api.letsencrypt.org/directory",gz="https://acme-v02.api.letsencrypt.org/directory",UX,CK="1.2.840.10045.2.1",VK="1.2.840.10045.3.1.7",LK="1.2.840.10045.4.3.2",SK="2.5.4.3",hK="1.2.840.113549.1.9.14",OK="2.5.29.17",BX,sU,RF,MF=(w)=>w,IF=(w,$)=>{for(var Y in $)RF(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:yF.bind($,Y)})},CF=(w,$)=>()=>(w&&($=w(w=0)),$),YB,zB,H1,QY,BB,oF,eF,Rz,YX,iU,_0,e,wT,Mz,$T,yz,YT,AT,CU,XT,Iz,Cz,VU,JT,UT,WT,jT,AX,GB,QT,D0,fT,zT,Vz,XX,bU,N0,u,BT,Lz,GT,Sz,ET,KT,LU,FT,hz,Oz,TT,SU,NT,qT,HT,RT,MT,JX,EB,yT,IT="0.15.6",e0,TX,UY,uU,cU,NX,vU,mU,WY,gU,dU,B$,KB,FB,qw,rw,TB,NB,CT,LT,qB,qX,AC,I0,m,XC,hT,JC,OT,UC,WC,_z,jC,_T,DT,QC,Dz,fC,zC,BC,GC,EC,hU,xT,KC,Mw,RB,HX,MB,yB,JW,IB,CB,RX,VB,LB,R1,cT,gw,FC,TC,NC,kB,f0,Hw,h,q1,nT,xz="[redacted]",lT,pT,Rw,d0,N7,q7,H7,R7;var tB=s(()=>{qK=NK(import.meta.url);IX=new XY;UX=class UX extends Error{problem;httpStatus;constructor(w,$,Y){super(w);this.name="AcmeError",this.problem=$,this.httpStatus=Y}};BX=new wB,sU=new $B,RF=Object.defineProperty;YB={};IF(YB,{withErrorRecovery:()=>JB,tryLoadConfig:()=>rF,loadConfigWithResult:()=>lF,loadConfig:()=>fB,isRetryableError:()=>cF,isConfigNotFoundError:()=>uF,isBunfigError:()=>UB,globalPerformanceMonitor:()=>QY,globalCache:()=>H1,getEnvOrDefault:()=>vF,generateConfigTypes:()=>tF,defaultGeneratedDir:()=>NB,defaultConfigDir:()=>TB,deepMergeWithArrayStrategy:()=>YW,deepMerge:()=>WB,createLibraryConfig:()=>aF,config:()=>pF,bunfigPlugin:()=>sF,applyEnvVarsToConfig:()=>YY,TypeGenerationError:()=>mU,SchemaValidationError:()=>WY,PluginError:()=>dU,PerformanceMonitor:()=>eU,FileSystemError:()=>vU,ErrorFactory:()=>B$,EnvVarError:()=>NX,EnvProcessor:()=>VX,ConfigValidator:()=>AW,ConfigValidationError:()=>uU,ConfigNotFoundError:()=>TX,ConfigMergeError:()=>cU,ConfigLoader:()=>XW,ConfigLoadError:()=>UY,ConfigFileLoader:()=>LX,ConfigCache:()=>oU,CacheUtils:()=>BB,BunfigError:()=>e0,BrowserConfigError:()=>gU,ArrayMergeStrategies:()=>KB});CT=CF(async()=>{zB=import.meta.require,H1=new oU,QY=new eU,BB={createKey:VF,isEquivalent:LF,estimateMemoryUsage:SF},oF=fX(ZU.cwd(),"config"),eF=fX(ZU.cwd(),"src/generated"),Rz=QX.env.CLARITY_LOG_DIR||vK(_F(),"logs"),YX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Rz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},iU=await DF(),_0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},e=_0,wT=_0.red,Mz=_0.green,$T=_0.yellow,yz=_0.blue,YT=_0.magenta,AT=_0.cyan,CU=_0.white,XT=_0.gray,Iz=_0.bgRed,Cz=_0.bgYellow,VU=_0.bold,JT=_0.dim,UT=_0.italic,WT=_0.underline,jT=_0.reset,AX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},GB={debug:"\uD83D\uDD0D",info:yz("ℹ"),success:Mz("✓"),warning:Cz(CU(VU(" WARN "))),error:Iz(CU(VU(" ERROR ")))},QT=new EX("stacks"),D0=new EX("bunfig",{showTags:!0}),fT=m0(JY.cwd(),"config"),zT=m0(JY.cwd(),"src/generated"),Vz=jX.env.CLARITY_LOG_DIR||uK(PF(),"logs"),XX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Vz,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 iF(),N0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},u=N0,BT=N0.red,Lz=N0.green,GT=N0.yellow,Sz=N0.blue,ET=N0.magenta,KT=N0.cyan,LU=N0.white,FT=N0.gray,hz=N0.bgRed,Oz=N0.bgYellow,TT=N0.bgGray,SU=N0.bold,NT=N0.dim,qT=N0.italic,HT=N0.underline,RT=N0.strikethrough,MT=N0.reset,JX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},EB={debug:"\uD83D\uDD0D",info:Sz("ℹ"),success:Lz("✓"),warning:Oz(LU(SU(" WARN "))),error:hz(LU(SU(" ERROR ")))},yT=new FX("stacks"),e0=class extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},TX=class extends e0{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${A} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}},UY=class extends e0{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}},uU=class extends e0{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},cU=class extends e0{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},NX=class extends e0{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}},vU=class extends e0{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},mU=class extends e0{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},WY=class extends e0{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},gU=class extends e0{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}},dU=class extends e0{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},B$={configNotFound(w,$,Y){return new TX(w,$,Y)},configLoad(w,$,Y){return new UY(w,$,Y)},configValidation(w,$,Y){return new uU(w,$,Y)},configMerge(w,$,Y,A){return new cU(w,$,Y,A)},envVar(w,$,Y,A){return new NX(w,$,Y,A)},fileSystem(w,$,Y){return new vU(w,$,Y)},typeGeneration(w,$,Y){return new mU(w,$,Y)},schemaValidation(w,$,Y){return new WY(w,$,Y)},browserConfig(w,$,Y,A){return new gU(w,$,Y,A)},plugin(w,$,Y){return new dU(w,$,Y)}},KB={replace:"replace",concat:"concat",smart:"smart"},FB=/^https?:\/\//,qw=new FX("bunfig",{showTags:!0}),rw=new XW,TB=g0(x$.cwd(),"config"),NB=g0(x$.cwd(),"src/generated")});LT=zX.env.CLARITY_LOG_DIR||QF(VT(),"logs"),qB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:LT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},qX={...qB},AC=(async()=>{try{let{loadConfig:w}=await CT().then(()=>YB),$=await w({name:"clarity",alias:"logging",defaultConfig:qB,cwd:zX.cwd()});if($)Object.assign(qX,$)}catch{}return qX})();I0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},m=I0,XC=I0.red,hT=I0.green,JC=I0.yellow,OT=I0.blue,UC=I0.magenta,WC=I0.cyan,_z=I0.white,jC=I0.gray,_T=I0.bgRed,DT=I0.bgYellow,QC=I0.bgGray,Dz=I0.bold,fC=I0.dim,zC=I0.italic,BC=I0.underline,GC=I0.strikethrough,EC=I0.reset,hU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xT={debug:"\uD83D\uDD0D",info:OT("ℹ"),success:hT("✓"),warning:DT(_z(Dz(" WARN "))),error:_T(_z(Dz(" ERROR ")))};KC=new SX("stacks");Mw=class Mw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,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])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};RB=class RB extends Mw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};HX=class HX extends Mw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};MB=class MB extends Mw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};yB=class yB extends Mw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};JW=class JW extends Mw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};IB=class IB extends Mw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};CB=class CB extends Mw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};RX=class RX extends Mw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};VB=class VB extends Mw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};LB=class LB extends Mw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};R1={configNotFound(w,$,Y){return new RB(w,$,Y)},configLoad(w,$,Y){return new HX(w,$,Y)},configValidation(w,$,Y){return new MB(w,$,Y)},configMerge(w,$,Y,A){return new yB(w,$,Y,A)},envVar(w,$,Y,A){return new JW(w,$,Y,A)},fileSystem(w,$,Y){return new IB(w,$,Y)},typeGeneration(w,$,Y){return new CB(w,$,Y)},schemaValidation(w,$,Y){return new RX(w,$,Y)},browserConfig(w,$,Y,A){return new VB(w,$,Y,A)},plugin(w,$,Y){return new LB(w,$,Y)}};cT=/^https?:\/\//;gw=new SX("bunfig",{showTags:!0});FC=new xB;TC=fw(CX.cwd(),"config"),NC=fw(CX.cwd(),"src/generated"),kB={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:fU.join(QU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:fU.join(QU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:fU.join(QU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},f0=kB,Hw={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"},h={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},q1={info:(...w)=>console.log(...w),warn:(...w)=>console.warn(...w),success:(...w)=>console.log(...w),error:(...w)=>console.error(...w),debug:(...w)=>console.debug(...w)};nT=dT(mT);lT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),pT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;Rw={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},d0={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"};N7={platform:"darwin",async addCertificate(w,$){if(await T7(w,$?.verbose)){S(h.TRUST,"Certificate is already trusted, skipping trust store update",$?.verbose),q1.success("Certificate is already trusted in system keychain");return}S(h.TRUST,"Adding certificate to macOS keychain",$?.verbose),await z$(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${w}`)},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(h.TRUST,`Removing certificate ${A} from macOS keychain`,$?.verbose);try{await z$(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),S(h.TRUST,`Removed certificate ${A} from macOS keychain`,$?.verbose)}catch(X){throw S(h.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},q7={platform:"win32",async addCertificate(w,$){S(h.TRUST,"Adding certificate to Windows certificate store",$?.verbose),await z$(`certutil -f -v -addstore -enterprise Root ${w}`)},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(h.TRUST,`Removing certificate ${A} from Windows certificate store`,$?.verbose);try{await z$(`certutil -delstore -enterprise Root "${A}"`),S(h.TRUST,`Removed certificate ${A} from Windows certificate store`,$?.verbose)}catch(X){throw S(h.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},H7={platform:"linux",async addCertificate(w,$){S(h.TRUST,"Adding certificate to Linux certificate store",$?.verbose);let Y=yX.homedir(),A=Hw.LINUX_CERT_DB_FILENAME,X=Hw.LINUX_TRUST_ARGS;S(h.TRUST,`Searching for certificate databases in ${Y}`,$?.verbose);let J=pU(Y,A);if(J.length===0){q1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){S(h.TRUST,`Processing certificate database in ${U}`,$?.verbose);try{S(h.TRUST,`Attempting to delete existing cert for ${f0.commonName}`,$?.verbose),await z$(`certutil -d sql:${U} -D -n ${f0.commonName}`)}catch(j){S(h.TRUST,`Warning: Error deleting existing cert: ${j}`,$?.verbose),console.warn(`Error deleting existing cert: ${j}`)}S(h.TRUST,`Adding new certificate to ${U}`,$?.verbose),await z$(`certutil -d sql:${U} -A -t ${X} -n ${f0.commonName} -i ${w}`),q1.info(`Cert added to ${U}`)}},async removeCertificate(w,$,Y){let A=Y||f0.commonName;S(h.TRUST,`Removing certificate ${A} from Linux certificate store`,$?.verbose);let X=yX.homedir(),J=Hw.LINUX_CERT_DB_FILENAME;S(h.TRUST,`Searching for certificate databases in ${X}`,$?.verbose);let U=pU(X,J);if(U.length===0){q1.warn("No certificate databases found. Cannot remove certificate.");return}for(let j of U){S(h.TRUST,`Processing certificate database in ${j}`,$?.verbose);try{await z$(`certutil -d sql:${j} -D -n "${A}"`),q1.info(`Cert removed from ${j}`)}catch(W){S(h.TRUST,`Error removing cert from ${j}: ${W}`,$?.verbose),console.warn(`Error removing cert from ${j}: ${W}`)}}}},R7={darwin:N7,win32:q7,linux:H7}});var DX=s(()=>{tB()});function k$(w){try{return _X(w)}catch{return null}}function KW(w){try{return BW(w)||null}catch{return null}}function FW(w,$){try{return $.every((Y)=>GW(w,Y))}catch{return!1}}var xX=s(()=>{DX()});import{existsSync as aB,statSync as sB}from"fs";import{existsSync as ZW,mkdirSync as S7,readdirSync as h7,writeFileSync as O7}from"fs";import{homedir as y1}from"os";import{dirname as oB,resolve as l0}from"path";import Z$ from"process";import{join as _7,relative as D7,resolve as eB}from"path";import aX from"process";import{existsSync as Z9,mkdirSync as MV,readdirSync as yV,writeFileSync as IV}from"fs";import{homedir as TW}from"os";import{dirname as LV,resolve as n0}from"path";import zY from"process";import{join as x7,relative as k7,resolve as w9}from"path";import sX from"process";import{existsSync as P9,mkdirSync as DV,readdirSync as xV,writeFileSync as kV}from"fs";import{dirname as PV,resolve as oX}from"path";import PW from"process";import{Buffer as E$}from"buffer";import{createCipheriv as Z7,createDecipheriv as P7,randomBytes as NW}from"crypto";import{closeSync as qW,createReadStream as $9,createWriteStream as i7,existsSync as HW,fsyncSync as Y9,openSync as A9,writeFileSync as b7}from"fs";import{access as u7,constants as X9,mkdir as c7,readdir as kX,rename as J9,stat as I1,unlink as ZX,writeFile as RW}from"fs/promises";import{join as C1}from"path";import x0 from"process";import{pipeline as v7}from"stream/promises";import{createGzip as U9}from"zlib";import V1 from"process";import sw from"process";import{Buffer as tw}from"buffer";import{createCipheriv as m7,createDecipheriv as g7,randomBytes as MW}from"crypto";import{closeSync as yW,createReadStream as W9,createWriteStream as d7,existsSync as PX,fsyncSync as j9,openSync as Q9,writeFileSync as n7}from"fs";import{access as l7,constants as f9,mkdir as p7,readdir as iX,rename as z9,stat as L1,unlink as bX,writeFile as IW}from"fs/promises";import{isAbsolute as r7,join as S1,resolve as t7}from"path";import Z from"process";import{pipeline as a7}from"stream/promises";import{createGzip as B9}from"zlib";import h1 from"process";import ow from"process";import uX from"process";import{existsSync as cX}from"fs";import{resolve as CW}from"path";import{existsSync as s7}from"fs";import{existsSync as o7,readdirSync as e7}from"fs";import{extname as VW,resolve as G9}from"path";import wN from"process";import{join as $q,relative as Yq,resolve as C9}from"path";import J8 from"process";import{Buffer as aw}from"buffer";import{createCipheriv as Jq,createDecipheriv as Uq,randomBytes as _W}from"crypto";import{closeSync as DW,createReadStream as V9,createWriteStream as Wq,existsSync as mX,fsyncSync as L9,openSync as S9,writeFileSync as jq}from"fs";import{access as Qq,constants as h9,mkdir as fq,readdir as gX,rename as O9,stat as O1,unlink as dX,writeFile as xW}from"fs/promises";import{isAbsolute as zq,join as _1,resolve as Bq}from"path";import P from"process";import{pipeline as Gq}from"stream/promises";import{createGzip as _9}from"zlib";import D1 from"process";import ew from"process";function C7(w,$){this[w]=I7.bind(null,$)}class lW{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=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<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),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(!aB(w))return!0;return sB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=aB(Y)?sB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},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 w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,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 w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class pW{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function $N(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function YN(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function AN(w){return w.getStats().size*2}function rW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&X0($[0])&&"id"in $[0]&&$[0].id===3&&X0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(X0($)&&X0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(X0(w)&&"arr"in w&&Array.isArray(w.arr)&&X0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&X0($[0])&&X0(w[0])){let A=[...$];for(let X of w)if(X0(X)&&"name"in X){if(!A.find((U)=>X0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(X0(X)&&"path"in X){if(!A.find((U)=>X0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>eX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!X0($)||!X0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(X0(X)&&X0(Y[A]))Y[A]=rW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&X0(X[0])&&X0(Y[A][0])){let J=[...X];for(let U of Y[A])if(X0(U)&&"name"in U){if(!J.find((W)=>X0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(X0(U)&&"path"in U){if(!J.find((W)=>X0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>eX(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function eX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!eX(w[Y],$[Y]))return!1;return!0}if(X0(w)&&X0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!eX(w[X],$[X]))return!1}return!0}return!1}function X0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function XN(w,$){if(!P9(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return rW($,A)}catch{return null}}catch{return null}}async function JN({name:w="",cwd:$,defaultConfig:Y}){let A=$||PW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let j of X){let W=oX(A,`${U}${j}`),Q=await XN(W,Y);if(Q!==null)return Q}try{let U=oX(A,"package.json");if(P9(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return rW(Y,W)}catch{}}}catch{}return Y}function UN(w,$={}){let Y=sX.cwd();while(Y.includes("storage"))Y=w9(Y,"..");let A=w9(Y,w||"");if($?.relative)return k7(sX.cwd(),A);return A}async function WN(){try{let w=await JN({name:"clarity",defaultConfig:lX,cwd:sX.cwd(),endpoint:"",headers:{}});return{...lX,...w}}catch{return lX}}function j0(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function jN(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof sw<"u"){let w=sw.type;if(w==="renderer"||w==="worker")return!1;return!!(sw.versions&&(sw.versions.node||sw.versions.bun))}return!1}class i9{async format(w){let $=await jN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:V1.pid,hostname:$(),environment:V1.env.NODE_ENV||"development",platform:V1.platform,version:V1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:V1.env.NODE_ENV||V1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class w8{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=w,this.config={...bW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new i9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...pX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...pX};return{...pX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:bW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await u7(this.config.logDirectory,X9.F_OK|X9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await c7(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:E$.from(w);try{if(!HW(this.currentLogFile))await RW(this.currentLogFile,"",{mode:420});if(X=A9(this.currentLogFile,"a",420),b7(X,W,{flag:"a"}),Y9(X),X!==void 0)qW(X),X=void 0;if((await I1(this.currentLogFile)).size===0){if(await RW(this.currentLogFile,W,{flag:"w",mode:420}),(await I1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{qW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 C1(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 C1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return C1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(j0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return NW(16).toString("hex")}generateKey(){return NW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=NW(16),A=Z7("aes-256-gcm",$,Y),X=E$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:E$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=U9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(E$.from(E$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(j0())return;let w=await I1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await kX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await I1(Y).catch(()=>null))try{if(await J9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await ZX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await RW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await I1(Y).catch(()=>null))await J9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await kX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await ZX(C1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=$9(w),A=i7($),X=U9();await v7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),HW(this.currentLogFile))try{let w=A9(this.currentLogFile,"r+");Y9(w),qW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!j0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await kX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await ZX(C1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?w0.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x0.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${w0.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!j0()){let Q=p9[w],f=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:w0.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:w0.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:Q,tag:f,message:U,level:w}),console.error(z),j){let B=j.split(`
133
+ `);for(let G of B)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:w0.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!j0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
134
134
  `;if(j)W+=`${j}
135
- `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!j0()){let Y=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:e.blue("◐"),tag:Y,message:`${e.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
136
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!j0()){let f=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:e.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!j0())console.error(Q.trim());await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new eX($,{...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(!qW(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return eB(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=K$.isBuffer(w)?w:K$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=k7("aes-256-gcm",Y,X);return j.setAuthTag(J),K$.concat([j.update(U),j.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!j0()){let J=w.split(`
137
- `),U=Math.max(...J.map((f)=>f.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((f)=>{let z=" ".repeat(U-f.length-2);return`│ ${f}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:e.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(j)})),Q.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(W),showTimestamp:!1}))}else if(!j0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
138
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(j0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${e.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();x0.stdin.removeListener("data",Y);try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!1)}catch{}x0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!0)}catch{}x0.stdin.resume(),x0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){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 W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!j0()){let U=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",j=e.blue("◐");console.error(`${j} ${U} ${e.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
139
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||j0()||w<=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:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),j!==void 0)this.activeProgressBar.message=j;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;x0.stdout.write(`${"\r".padEnd(x0.stdout.columns||80)}\r`),this.log(j,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||j0()||!x0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=e.green("━".repeat(A)),U=e.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=$||Y===100?e.green("✓"):e.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${e.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=x0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,x0.stdout.write(w.lastRenderedLine),$)x0.stdout.write(`
140
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||j0()||!x0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(j0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await xX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=L1(this.config.logDirectory,A);if(w.before)try{if((await V1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 kX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function dX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&r($[0])&&"id"in $[0]&&$[0].id===3&&r($[1])&&"id"in $[1]&&$[1].id===4)return $;if(r($)&&r(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(r(w)&&"arr"in w&&Array.isArray(w.arr)&&r($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&r($[0])&&r(w[0])){let A=[...$];for(let X of w)if(r(X)&&"name"in X){if(!A.find((U)=>r(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(r(X)&&"path"in X){if(!A.find((U)=>r(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>w8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!r($)||!r(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(r(X)&&r(Y[A]))Y[A]=dX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&r(X[0])&&r(Y[A][0])){let J=[...X];for(let U of Y[A])if(r(U)&&"name"in U){if(!J.find((W)=>r(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((W)=>r(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>w8(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function rW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:dX(w,$);if(Array.isArray(w))return Y==="replace"?$:dX(w,$);if(!r($)||!r(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=dX(U,J);else if(r(J)&&r(U))A[X]=rW(U,J,Y);else A[X]=J}return A}function w8(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!w8(w[Y],$[Y]))return!1;return!0}if(r(w)&&r($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!w8(w[X],$[X]))return!1}return!0}return!1}function r(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function cX(w,$,Y="replace"){if(!x9(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return rW($,X,Y)}catch{return null}}catch{return null}}function WN(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=BY.env[G]||BY.env[T];if(K!==void 0){if(Y)Z0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((N)=>N.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function jN({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?WN(w,X,J):X,Q=Y||BY.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)Z0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,n0(Q,"config"),n0(Q,".config"),A?n0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)Z0.info(`Searching for configuration in: ${F}`);let R=[n0(Q,"config"),n0(Q,".config")].concat(A?[n0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let L of R)for(let V of f){let q=n0(F,`${L}${V}`),M=await cX(q,W,j);if(M!==null){if(J)Z0.success(`Configuration loaded from: ${q}`);return M}}}if(w){let F=n0(FW(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)Z0.info(`Checking user config directory: ${F}`);for(let R of N)for(let L of f){let V=n0(F,`${R}${L}`),q=await cX(V,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user config directory: ${V}`);return q}}}if(w){let F=n0(FW(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)Z0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of N)for(let L of f){let V=n0(F,`${R}${L}`),q=await cX(V,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user config directory dotfile: ${V}`);return q}}}if(w){let F=FW(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)Z0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of N)for(let L of f){let V=n0(F,`${R}${L}`),q=await cX(V,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user home directory: ${V}`);return q}}}try{let F=n0(Q,"package.json");if(x9(F)){let N=await import(F),R=N[w];if(!R&&$){if(R=N[$],R&&J)Z0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)Z0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return rW(W,R,j)}catch(L){if(J)Z0.warn("Failed to merge package.json config:",L)}}}catch(F){if(J)Z0.warn("Failed to load package.json:",F)}if(J)Z0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function QN(w,$={}){let Y=tX.cwd();while(Y.includes("storage"))Y=sB(Y,"..");let A=sB(Y,w||"");if($?.relative)return O7(tX.cwd(),A);return A}async function fN(){try{let w=await jN({name:"clarity",alias:"logging",defaultConfig:pX,cwd:tX.cwd()});return{...pX,...w||{}}}catch{return pX}}function H0(){if(w$.env.NODE_ENV==="test"||w$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zN(){if(w$.env.NODE_ENV==="test"||w$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof w$<"u"){let w=w$.type;if(w==="renderer"||w==="worker")return!1;return!!(w$.versions&&(w$.versions.node||w$.versions.bun))}return!1}class P9{async format(w){let $=await zN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:_1.pid,hostname:$(),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 $8{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=w,this.config={...bW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new P9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...rX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...rX};return{...rX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:bW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await d7(this.config.logDirectory,j9.F_OK|j9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await n7(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:sw.from(w);try{if(!ZX(this.currentLogFile))await yW(this.currentLogFile,"",{mode:420});if(X=W9(this.currentLogFile,"a",420),g7(X,W,{flag:"a"}),U9(X),X!==void 0)MW(X),X=void 0;if((await h1(this.currentLogFile)).size===0){if(await yW(this.currentLogFile,W,{flag:"w",mode:420}),(await h1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{MW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 O1(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 O1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return O1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return RW(16).toString("hex")}generateKey(){return RW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=RW(16),A=c7("aes-256-gcm",$,Y),X=sw.isBuffer(w)?w:sw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=sw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=f9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(sw.from(sw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let w=await h1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await PX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await h1(Y).catch(()=>null))try{if(await Q9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await iX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await yW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await h1(Y).catch(()=>null))await Q9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await PX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await iX(O1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=J9(w),A=m7($),X=f9();await r7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),ZX(this.currentLogFile))try{let w=W9(this.currentLogFile,"r+");U9(w),MW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await PX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await iX(O1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?c.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let w=typeof Z.env.NO_COLOR<"u",$=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(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=Z.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${c.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),$}supportsHyperlinks(){if(H0())return!1;let w=Z.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=Z.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(l7($)||$.startsWith("./")||$.startsWith("../"))$=p7($);else return null;return ZX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":l9[w],B=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:c.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:c.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
135
+ `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!j0()){let Y=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:w0.blue("◐"),tag:Y,message:`${w0.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
136
+ `,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!j0()){let f=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:w0.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!j0())console.error(Q.trim());await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new w8($,{...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(!HW(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=E$.isBuffer(w)?w:E$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),j=P7("aes-256-gcm",Y,X);return j.setAuthTag(J),E$.concat([j.update(U),j.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!j0()){let J=w.split(`
137
+ `),U=Math.max(...J.map((f)=>f.length))+2,j=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,Q=J.map((f)=>{let z=" ".repeat(U-f.length-2);return`│ ${f}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:w0.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:w0.cyan(j)})),Q.forEach((f)=>console.error(this.formatConsoleMessage({timestamp:Y,message:w0.cyan(f),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:w0.cyan(W),showTimestamp:!1}))}else if(!j0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
138
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(j0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${w0.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();x0.stdin.removeListener("data",Y);try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!1)}catch{}x0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof x0.stdin.setRawMode==="function")x0.stdin.setRawMode(!0)}catch{}x0.stdin.resume(),x0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,j=0;if(Y=w.replace(U,(W,Q)=>{if(Q==="%")return"%";if(j>=$.length)return W;let f=$[j++];switch(Q){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 W}}),j<$.length)Y+=` ${$.slice(j).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!j0()){let U=this.options.showTags!==!1&&this.name?w0.gray(this.formatTag(this.name)):"",j=w0.blue("◐");console.error(`${j} ${U} ${w0.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
139
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||j0()||w<=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:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,j)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),j!==void 0)this.activeProgressBar.message=j;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,U!==void 0)this.activeProgressBar.message=U;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(U,j="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||j0())return;x0.stdout.write(`${"\r".padEnd(x0.stdout.columns||80)}\r`),this.log(j,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||j0()||!x0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=w0.green("━".repeat(A)),U=w0.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=$||Y===100?w0.green("✓"):w0.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${w0.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=x0.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,x0.stdout.write(w.lastRenderedLine),$)x0.stdout.write(`
140
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||j0()||!x0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(j0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await kX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=C1(this.config.logDirectory,A);if(w.before)try{if((await I1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 ZX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function nX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&t($[0])&&"id"in $[0]&&$[0].id===3&&t($[1])&&"id"in $[1]&&$[1].id===4)return $;if(t($)&&t(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(t(w)&&"arr"in w&&Array.isArray(w.arr)&&t($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&t($[0])&&t(w[0])){let A=[...$];for(let X of w)if(t(X)&&"name"in X){if(!A.find((U)=>t(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(t(X)&&"path"in X){if(!A.find((U)=>t(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>$8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!t($)||!t(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(t(X)&&t(Y[A]))Y[A]=nX(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&t(X[0])&&t(Y[A][0])){let J=[...X];for(let U of Y[A])if(t(U)&&"name"in U){if(!J.find((W)=>t(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(t(U)&&"path"in U){if(!J.find((W)=>t(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((j)=>$8(j,U)))J.push(U);Y[A]=J}else if(X.every((J)=>typeof J==="string")&&Y[A].every((J)=>typeof J==="string")){let J=[...X];for(let U of Y[A])if(!J.includes(U))J.push(U);Y[A]=J}else Y[A]=X;else Y[A]=X}return Y}function tW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:nX(w,$);if(Array.isArray(w))return Y==="replace"?$:nX(w,$);if(!t($)||!t(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=nX(U,J);else if(t(J)&&t(U))A[X]=tW(U,J,Y);else A[X]=J}return A}function $8(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!$8(w[Y],$[Y]))return!1;return!0}if(t(w)&&t($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!$8(w[X],$[X]))return!1}return!0}return!1}function t(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function vX(w,$,Y="replace"){if(!Z9(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return tW($,X,Y)}catch{return null}}catch{return null}}function QN(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${z.map(B).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${G} for config ${w}.${z.join(".")}`);if(typeof f==="object"&&f!==null&&!Array.isArray(f))W[Q]=J(f,z);else{let K=zY.env[G]||zY.env[T];if(K!==void 0){if(Y)Z0.info(`Using environment variable ${K?G:T} for config ${w}.${z.join(".")}`);if(typeof f==="number")W[Q]=Number(K);else if(typeof f==="boolean")W[Q]=K.toLowerCase()==="true";else if(Array.isArray(f))try{let F=JSON.parse(K);if(Array.isArray(F))W[Q]=F;else W[Q]=K.split(",").map((N)=>N.trim())}catch{W[Q]=K.split(",").map((F)=>F.trim())}else W[Q]=K}}}return W}return J(X)}async function fN({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:j="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?QN(w,X,J):X,Q=Y||zY.cwd(),f=[".ts",".js",".mjs",".cjs",".json"];if(J)Z0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${Q}`);let z=[w,`.${w}`].filter(Boolean),B=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([Q,n0(Q,"config"),n0(Q,".config"),A?n0(Q,A):void 0].filter(Boolean)));for(let F of K){if(J)Z0.info(`Searching for configuration in: ${F}`);let R=[n0(Q,"config"),n0(Q,".config")].concat(A?[n0(Q,A)]:[]).includes(F)?[...z,...B,...G,...T]:[...B,...z,...T,...G];for(let V of R)for(let L of f){let q=n0(F,`${V}${L}`),C=await vX(q,W,j);if(C!==null){if(J)Z0.success(`Configuration loaded from: ${q}`);return C}}}if(w){let F=n0(TW(),".config",w),N=["config",`${w}.config`];if($)N.push(`${$}.config`);if(J)Z0.info(`Checking user config directory: ${F}`);for(let R of N)for(let V of f){let L=n0(F,`${R}${V}`),q=await vX(L,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user config directory: ${L}`);return q}}}if(w){let F=n0(TW(),".config"),N=[`.${w}.config`];if($)N.push(`.${$}.config`);if(J)Z0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=n0(F,`${R}${V}`),q=await vX(L,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user config directory dotfile: ${L}`);return q}}}if(w){let F=TW(),N=[`.${w}.config`,`.${w}`];if($)N.push(`.${$}.config`),N.push(`.${$}`);if(J)Z0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of N)for(let V of f){let L=n0(F,`${R}${V}`),q=await vX(L,W,j);if(q!==null){if(J)Z0.success(`Configuration loaded from user home directory: ${L}`);return q}}}try{let F=n0(Q,"package.json");if(Z9(F)){let N=await import(F),R=N[w];if(!R&&$){if(R=N[$],R&&J)Z0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)Z0.success(`Configuration loaded from package.json: ${R===N[w]?w:$}`);return tW(W,R,j)}catch(V){if(J)Z0.warn("Failed to merge package.json config:",V)}}}catch(F){if(J)Z0.warn("Failed to load package.json:",F)}if(J)Z0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function zN(w,$={}){let Y=aX.cwd();while(Y.includes("storage"))Y=eB(Y,"..");let A=eB(Y,w||"");if($?.relative)return D7(aX.cwd(),A);return A}async function BN(){try{let w=await fN({name:"clarity",alias:"logging",defaultConfig:rX,cwd:aX.cwd()});return{...rX,...w||{}}}catch{return rX}}function H0(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function GN(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ow<"u"){let w=ow.type;if(w==="renderer"||w==="worker")return!1;return!!(ow.versions&&(ow.versions.node||ow.versions.bun))}return!1}class b9{async format(w){let $=await GN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:h1.pid,hostname:$(),environment:h1.env.NODE_ENV||"development",platform:h1.platform,version:h1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:h1.env.NODE_ENV||h1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Y8{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=w,this.config={...uW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new b9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...tX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...tX};return{...tX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:uW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await l7(this.config.logDirectory,f9.F_OK|f9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await p7(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:tw.from(w);try{if(!PX(this.currentLogFile))await IW(this.currentLogFile,"",{mode:420});if(X=Q9(this.currentLogFile,"a",420),n7(X,W,{flag:"a"}),j9(X),X!==void 0)yW(X),X=void 0;if((await L1(this.currentLogFile)).size===0){if(await IW(this.currentLogFile,W,{flag:"w",mode:420}),(await L1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{yW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 S1(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 S1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return S1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return MW(16).toString("hex")}generateKey(){return MW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=MW(16),A=m7("aes-256-gcm",$,Y),X=tw.isBuffer(w)?w:tw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=tw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=B9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(tw.from(tw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let w=await L1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await iX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await L1(Y).catch(()=>null))try{if(await z9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await bX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await IW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await L1(Y).catch(()=>null))await z9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await iX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await bX(S1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=W9(w),A=d7($),X=B9();await a7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),PX(this.currentLogFile))try{let w=Q9(this.currentLogFile,"r+");j9(w),yW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await iX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await bX(S1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?c.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let w=typeof Z.env.NO_COLOR<"u",$=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(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=Z.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${c.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),$}supportsHyperlinks(){if(H0())return!1;let w=Z.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=Z.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(r7($)||$.startsWith("./")||$.startsWith("../"))$=t7($);else return null;return PX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":r9[w],B=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:c.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:c.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
141
141
  `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:c.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}if(!this.shouldLog(w))return;let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
142
142
  `;if(j)f+=`${j}
143
143
  `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!H0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!H0()&&Z.stdout.isTTY)Z.stdout.write(`
144
144
  `);if(this[W==="warning"?"warn":W](j),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=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(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
145
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":c.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!H0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new $8($,{...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(H0())throw Error("createReadStream is not supported in browser environments");if(!ZX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return J9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=sw.isBuffer(w)?w:sw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=v7("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=sw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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 H0()}isServerMode(){return!H0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
145
+ `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":c.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!H0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new Y8($,{...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(H0())throw Error("createReadStream is not supported in browser environments");if(!PX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return W9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=tw.isBuffer(w)?w:tw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=g7("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=tw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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 H0()}isServerMode(){return!H0()}setTestEncryptionKey(w,$){this.currentKeyId=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
146
146
  `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(f),showTimestamp:!1}))}else if(!H0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
147
147
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(H0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${c.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=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(""),$(X==="y"||X==="yes")};try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!0)}catch{}Z.stdin.resume(),Z.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(f,z)=>{if(z==="%")return"%";if(Q>=$.length)return f;let B=$[Q++];switch(z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return f}}),Q<$.length)Y+=` ${$.slice(Q).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${Q}${W} ${c.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
148
148
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!Z.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=c.green("━".repeat(A)),U=c.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?c.green("✓"):c.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=Z.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,Z.stdout.write(w.lastRenderedLine),$)Z.stdout.write(`
149
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||H0()||!Z.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await PX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=O1(this.config.logDirectory,A);if(w.before)try{if((await h1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 iX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function i9(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function b9(w){return w instanceof ww}function BN(w){return w instanceof Y8}function GN(w){if(b9(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class U8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return KY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=bX.env[W]||(Q?bX.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=bX.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof A8)throw z;throw F$.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw F$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(bX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
149
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||H0()||!Z.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await iX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=S1(this.config.logDirectory,A);if(w.before)try{if((await L1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 bX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function u9(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let j=0;j<=Y;j++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),j===Y||!X(U))break;if(A>0)await new Promise((Q)=>setTimeout(Q,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function c9(w){return w instanceof Yw}function EN(w){return w instanceof A8}function KN(w){if(c9(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class W8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:j=!1,trackPerformance:W=!0}=Y,Q=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let f=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],f,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:j,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return EY.track("applyEnvironmentVariables",Q,{configName:w});return Q()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=U.map((f)=>this.formatEnvKey(f,A.useCamelCase)),W=`${Y}_${j.join("_")}`,Q=A.useBackwardCompatibility?`${Y}_${U.map((f)=>f.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let f=uX.env[W]||(Q?uX.env[Q]:void 0);if(f!==void 0){if(A.verbose){let z=uX.env[W]?W:Q}try{w[X]=this.parseEnvironmentValue(f,typeof J,W,A.customParsers,A.configName)}catch(z){if(z instanceof X8)throw z;throw K$.envVar(W,f,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw K$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(uX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],j=`${Y}_${U.map((W)=>this.formatEnvKey(W,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:j,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
150
150
 
151
151
  `;for(let A of w)Y+=`${A.key}
152
152
  `,Y+=` Type: ${A.type}
@@ -158,36 +158,36 @@ ${A.join(`
158
158
  `;Y+=`| Variable | Type | Description | Example |
159
159
  `,Y+=`|----------|------|-------------|----------|
160
160
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
161
- `;return Y}}function EN(w,$){let Y=g9("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function u9(w,$,Y={}){return c9(w,$,Y,new WeakMap)}function c9(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return v9(w,$,X,A);if(!fw($)||!fw(w))return $;return NN(w,$,Y,A)}function v9(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return KN(w,$);case"smart":return FN(w,$,A);default:return $}return $}function KN(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>PW(X,A)))Y.push(A);return Y}function FN(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(fw($[0])&&fw(w[0]))return TN(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function TN(w,$,Y){let A=[...$];for(let X of w){if(!fw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>fw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function NN(w,$,Y,A){let X=$;if(fw(X)&&A.has(X))return A.get(X);let J={...w};if(fw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(fw(j)&&fw(W))J[U]=c9(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=v9(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function tW(w,$,Y="replace"){return u9(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function PW(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!PW(w[Y],$[Y]))return!1;return!0}if(fw(w)&&fw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!PW(w[X],$[X]))return!1}return!0}return!1}function fw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class W8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=Z1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!uX(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new GY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new GY(w,Error("Configuration must export a valid object"),"unknown");let F={config:tW($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)Z1.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?F$.configLoad(w,Q):F$.configLoad(w,Error(String(Q)))}};if(U)return KY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(IW($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return i9(async()=>{return uX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!uX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=IW(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=IW(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(w))}async validateConfigFile(w){let $=[];try{if(!uX(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class aW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await KY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!t7($))throw new EY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new EY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:r9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class sW{fileLoader=new W8;envProcessor=new U8;validator=new aW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Mw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw Mw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||i$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(l0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw F$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?zY(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)Mw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Mw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?zY(w,Y,X):Y,j=[l0(C1(),".config",w),l0(C1(),".config"),C1()];for(let W of j){if(X)Mw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)Mw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?zY(w,A,J):A;try{let W=l0(Y,"package.json");if(!kW(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)Mw.success(`Configuration loaded from package.json: ${z}`);return{config:tW(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Mw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:zY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw F$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return Z1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);Z1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,l0(w,"config"),l0(w,".config"),$?l0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(l0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[l0(C1(),".config",w),l0(C1(),".config"),C1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function B9(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function qN(w){return Y$.loadConfig({...w,__strictErrorHandling:!0})}async function m9(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await Y$.loadConfig(w);else A=await Y$.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Mw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await Y$.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function HN(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await Y$.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&B9(Y)))return(await Y$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await Y$.loadConfig({...w,cwd:w.cwd||i$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&B9($)))return(await Y$.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function RN(w,$,Y="replace"){let A=new W8;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function zY(w,$,Y=!1){let A=new U8,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=i$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function MN(w){let $=l0(i$.cwd(),w.configDir),Y=l0(i$.cwd(),w.generatedDir),A=l0(Y,"config-types.ts");if(!kW(aB(A)))V7(aB(A),{recursive:!0,mode:511});let X=kW($)?L7($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${sN}
161
+ `;return Y}}function FN(w,$){let Y=n9("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function v9(w,$,Y={}){return m9(w,$,Y,new WeakMap)}function m9(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let j=U(w,$);if(j!==void 0)return j}if(Array.isArray($)||Array.isArray(w))return g9(w,$,X,A);if(!Gw($)||!Gw(w))return $;return HN(w,$,Y,A)}function g9(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return TN(w,$);case"smart":return NN(w,$,A);default:return $}return $}function TN(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>iW(X,A)))Y.push(A);return Y}function NN(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Gw($[0])&&Gw(w[0]))return qN(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function qN(w,$,Y){let A=[...$];for(let X of w){if(!Gw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let j of J)if(j in X){if(A.find((Q)=>Gw(Q)&&(j in Q)&&Q[j]===X[j])){U=!0;break}}if(!U)A.push(X)}return A}function HN(w,$,Y,A){let X=$;if(Gw(X)&&A.has(X))return A.get(X);let J={...w};if(Gw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let j=X[U],W=J[U];if(Y.skipNullish&&(j===null||j===void 0))continue;if(j===null||j===void 0){J[U]=j;continue}if(Gw(j)&&Gw(W))J[U]=m9(W,j,Y,A);else if(Array.isArray(j)||Array.isArray(W))J[U]=g9(W,j,Y.arrayMergeMode||"smart",A);else J[U]=j}return J}function aW(w,$,Y="replace"){return v9(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function iW(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!iW(w[Y],$[Y]))return!1;return!0}if(Gw(w)&&Gw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!iW(w[X],$[X]))return!1}return!0}return!1}function Gw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class j8{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:j=!1}=Y;if(X){let Q=x1.getWithFileCheck("file",w);if(Q){if(j)console.log(`Configuration loaded from cache: ${w}`);return Q}}let W=async()=>{if(!cX(w))return null;try{let Q=`?t=${Date.now()}`,f=await import(w+Q),z=f.default||f,B="default"in f,G=Object.keys(f).length>0;if(!B&&!G)throw new BY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new BY(w,Error("Configuration must export a valid object"),"unknown");let F={config:aW($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)x1.setWithFileCheck("file",F,w,J);return F}catch(Q){throw Q instanceof Error?K$.configLoad(w,Q):K$.configLoad(w,Error(String(Q)))}};if(U)return EY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(CW($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return u9(async()=>{return cX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!cX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let j=CW(w,`${J}${U}`);if(await this.checkFileAccess(j))A.push(j)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let j=CW(w,U);if(await this.checkFileAccess(j))A.push(j)}}catch{return[]}return A}looksLikeConfigFile(w){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(w))}async validateConfigFile(w){let $=[];try{if(!cX(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class sW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:j=!0,verbose:W=!1}=Y,Q=async()=>{let f=[],z=[],B={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:j,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,B);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],B);else return this.validateWithJSONSchema(w,$,B)}catch(G){return f.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:f,warnings:z}}};if(j)return await EY.track("validateConfiguration",Q);return Q()}async validateWithSchemaFile(w,$,Y){try{if(!s7($))throw new GY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new GY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,j=Array.isArray($.type)?$.type:[$.type];if(!j.includes(U)){if(A.push({path:Y,message:`Expected type ${j.join(" or ")}, got ${U}`,expected:j.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let j=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,j,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let j of $.required)if(!(j in U)){if(A.push({path:Y?`${Y}.${j}`:j,message:`Missing required property '${j}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[j,W]of Object.entries($.properties))if(j in U){let Q=Y?`${Y}.${j}`:j;if(this.validateObjectAgainstSchema(U[j],W,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let j=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!j.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),j=this.validateWithRule(U,J,J.path);if(A.push(...j),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.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:a9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class oW{fileLoader=new j8;envProcessor=new W8;validator=new sW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let j;try{j=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let Q=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(Q)throw W;j={...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(W instanceof Error&&W.name==="ConfigLoadError"){let f=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),z=!f&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),B=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(Q&&(B||f))throw W;if(z&&(!Q||!B))j={...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(!Q)j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${W.message}`]};else throw W}else j={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${W instanceof Error?W.message:String(W)}`]}}if(X||J)await this.validateConfiguration(j.config,X,J,U.name);if(Y?.enabled&&j)this.cacheResult(U.name||"",j,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)yw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);j.metrics=W}return j}catch(j){let W=Date.now()-$;throw yw.error(`Configuration loading failed after ${W}ms:`,[j instanceof Error?j:Error(String(j))]),j}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:j,checkEnv:W=!0,arrayStrategy:Q="replace",verbose:f=!1}=w,z=J||Z$.cwd(),B=[],G=await this.loadLocalConfiguration(A,X,z,U,j,Q,f,W,Y);if(G)return B.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(G,B,W,A,f);let T=await this.loadHomeConfiguration(A,X,j,Q,f,W);if(T)return B.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,B,W,A,f);let K=await this.loadPackageJsonConfiguration(A,X,z,j,Q,f,W);if(K)return B.push(l0(z,"package.json")),this.finalizeResult(K,B,W,A,f);if(B.push(...this.getAllSearchPaths(A,X,z,U)),$)throw K$.configNotFound(A,B,X);return{...await this.applyEnvironmentVariables(A,j,W,f),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,j,W){let Q=j?fY(w,X,U):X,f=this.getLocalDirectories(Y,A);for(let z of f){if(U)yw.info(`Searching for configuration in: ${z}`);let B=this.fileLoader.generateConfigPaths(w,z,$),G=await this.fileLoader.tryLoadFromPaths(B,Q,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)yw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?fY(w,Y,X):Y,j=[l0(y1(),".config",w),l0(y1(),".config"),y1()];for(let W of j){if(X)yw.info(`Checking home directory: ${W}`);let Q=this.fileLoader.generateConfigPaths(w,W,$),f=await this.fileLoader.tryLoadFromPaths(Q,U,{arrayStrategy:A,verbose:X});if(f){if(X)yw.success(`Configuration loaded from home directory: ${f.source.path}`);return f}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let j=U?fY(w,A,J):A;try{let W=l0(Y,"package.json");if(!ZW(W))return null;let Q=await import(W),f=Q[w],z=w;if(!f&&$)f=Q[$],z=$;if(f&&typeof f==="object"&&!Array.isArray(f)){if(J)yw.success(`Configuration loaded from package.json: ${z}`);return{config:aW(j,f,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)yw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:fY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw K$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return x1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);x1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,l0(w,"config"),l0(w,".config"),$?l0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(l0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[l0(y1(),".config",w),l0(y1(),".config"),y1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function E9(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function RN(w){return w$.loadConfig({...w,__strictErrorHandling:!0})}async function d9(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await w$.loadConfig(w);else A=await w$.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)yw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let j=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await w$.applyEnvironmentVariables(j.name||"",$,!0,j.verbose||!1))?.config??$;return $}}async function MN(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await w$.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&E9(Y)))return(await w$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await w$.loadConfig({...w,cwd:w.cwd||Z$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&E9($)))return(await w$.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function yN(w,$,Y="replace"){let A=new j8;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function fY(w,$,Y=!1){let A=new W8,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,j=[]){let W={...U};for(let[Q,f]of Object.entries(U)){let z=[...j,Q],B=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of B)if(G=Z$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof f==="boolean")W[Q]=["true","1","yes"].includes(G.toLowerCase());else if(typeof f==="number"){let K=Number(G);if(!Number.isNaN(K))W[Q]=K}else if(Array.isArray(f))try{W[Q]=JSON.parse(G)}catch{W[Q]=G.split(",").map((K)=>K.trim())}else W[Q]=G;else if(f&&typeof f==="object"&&!Array.isArray(f))W[Q]=J(f,z)}return W}return J($)}function IN(w){let $=l0(Z$.cwd(),w.configDir),Y=l0(Z$.cwd(),w.generatedDir),A=l0(Y,"config-types.ts");if(!ZW(oB(A)))S7(oB(A),{recursive:!0,mode:511});let X=ZW($)?h7($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${eN}
162
162
  export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
163
- `;S7(A,J,{mode:438})}function yN(w){let $=null,Y=null,A=()=>{if(!Y)Y=m9(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Mw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function IN(w){let $=z9(o7.cwd(),w?.configDir||"./config");function Y(){if(!a7($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=s7($).filter((W)=>X.has(CW(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let f=CW(Q).toLowerCase(),z=j.get(W);if(!z){j.set(W,Q);continue}let B=CW(z).toLowerCase();if(J.indexOf(f)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",j=X.length?`{
164
- ${X.map((Q)=>{let f=z9($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${f}').default`}).join(`,
163
+ `;O7(A,J,{mode:438})}function CN(w){let $=null,Y=null,A=()=>{if(!Y)Y=d9(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)yw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let j=X[U];return A(),j},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,j){if(!$)$={...X};return $[U]=j,!0}})}function VN(w){let $=G9(wN.cwd(),w?.configDir||"./config");function Y(){if(!o7($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=e7($).filter((W)=>X.has(VW(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),j=new Map;for(let{base:W,file:Q}of U){let f=VW(Q).toLowerCase(),z=j.get(W);if(!z){j.set(W,Q);continue}let B=VW(z).toLowerCase();if(J.indexOf(f)<J.indexOf(B))j.set(W,Q)}return Array.from(j.entries()).map(([W,Q])=>({base:W,file:Q})).sort((W,Q)=>W.base.localeCompare(Q.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",j=X.length?`{
164
+ ${X.map((Q)=>{let f=G9($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${f}').default`}).join(`,
165
165
  `)}
166
166
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
167
167
  export type ConfigByName = ${j}
168
168
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
169
169
  export type ConfigOf = Config
170
- `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function $q(w,$={}){let Y=X8.cwd();while(Y.includes("storage"))Y=y9(Y,"..");let A=y9(Y,w||"");if($?.relative)return wq(X8.cwd(),A);return A}function M0(){if($$.env.NODE_ENV==="test"||$$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Bq(){if($$.env.NODE_ENV==="test"||$$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $$<"u"){let w=$$.type;if(w==="renderer"||w==="worker")return!1;return!!($$.versions&&($$.versions.node||$$.versions.bun))}return!1}class o9{async format(w){let $=await Bq(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:k1.pid,hostname:$(),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 FY{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=w,this.config={...J8},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new o9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...xW,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...xW};return{...xW,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:J8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await Wq(this.config.logDirectory,L9.F_OK|L9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await jq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:ow.from(w);try{if(!vX(this.currentLogFile))await DW(this.currentLogFile,"",{mode:420});if(X=V9(this.currentLogFile,"a",420),Uq(X,W,{flag:"a"}),C9(X),X!==void 0)_W(X),X=void 0;if((await D1(this.currentLogFile)).size===0){if(await DW(this.currentLogFile,W,{flag:"w",mode:420}),(await D1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{_W(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 w=new Date().toISOString().split("T")[0];return x1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return OW(16).toString("hex")}generateKey(){return OW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=OW(16),A=Aq("aes-256-gcm",$,Y),X=ow.isBuffer(w)?w:ow.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=ow.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=h9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(ow.from(ow.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let w=await D1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await mX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await D1(Y).catch(()=>null))try{if(await S9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await gX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await DW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await D1(Y).catch(()=>null))await S9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await mX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await gX(x1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=I9(w),A=Jq($),X=h9();await zq(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),vX(this.currentLogFile))try{let w=V9(this.currentLogFile,"r+");C9(w),_W(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await mX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await gX(x1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?g.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let w=typeof P.env.NO_COLOR<"u",$=P.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof P.stderr<"u"&&P.stderr.isTTY||typeof P.stdout<"u"&&P.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=P.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${g.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),$}supportsHyperlinks(){if(M0())return!1;let w=P.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=P.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(Qq($)||$.startsWith("./")||$.startsWith("../"))$=fq($);else return null;return vX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":Tq[w],B=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:g.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:g.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
170
+ `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function Aq(w,$={}){let Y=J8.cwd();while(Y.includes("storage"))Y=C9(Y,"..");let A=C9(Y,w||"");if($?.relative)return Yq(J8.cwd(),A);return A}function M0(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Eq(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ew<"u"){let w=ew.type;if(w==="renderer"||w==="worker")return!1;return!!(ew.versions&&(ew.versions.node||ew.versions.bun))}return!1}class w2{async format(w){let $=await Eq(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:D1.pid,hostname:$(),environment:D1.env.NODE_ENV||"development",platform:D1.platform,version:D1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D1.env.NODE_ENV||D1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class KY{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=w,this.config={...U8},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new w2,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.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 X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...kW,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...kW};return{...kW,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:U8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,j=1000;while(J<U)try{try{try{await Qq(this.config.logDirectory,h9.F_OK|h9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await fq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:aw.from(w);try{if(!mX(this.currentLogFile))await xW(this.currentLogFile,"",{mode:420});if(X=S9(this.currentLogFile,"a",420),jq(X,W,{flag:"a"}),L9(X),X!==void 0)DW(X),X=void 0;if((await O1(this.currentLogFile)).size===0){if(await xW(this.currentLogFile,W,{flag:"w",mode:420}),(await O1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let f=Q;if(f.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(f.code)){if(J<U-1){let z=typeof f.message==="string"?f.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let B=j*2**J;await new Promise((G)=>setTimeout(G,B)),J++;continue}}if(f?.code&&["ENOSPC","EDQUOT"].includes(f.code))throw Error(`Disk quota exceeded or no space left on device: ${f.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",f),f}finally{if(X!==void 0)try{DW(X)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(J===U-1){let f=W,z=typeof f.message==="string"?f.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),W}J++;let Q=j*2**(J-1);await new Promise((f)=>setTimeout(f,Q))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 _1(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 _1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return _1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=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 X=Array.from(this.encryptionKeys.entries()).sort(([,j],[,W])=>W.createdAt.getTime()-j.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[j]of X.slice(U))this.encryptionKeys.delete(j),this.keys.delete(j)}generateKeyId(){return _W(16).toString("hex")}generateKey(){return _W(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=_W(16),A=Jq("aes-256-gcm",$,Y),X=aw.isBuffer(w)?w:aw.from(w,"utf8"),J=A.update(X),U=A.final(),j=J.length+U.length,W=A.getAuthTag(),Q=aw.allocUnsafe(16+j+16);return Y.copy(Q,0),J.copy(Q,16),U.copy(Q,16+J.length),W.copy(Q,16+j),{encrypted:Q,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=_9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(aw.from(aw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let w=await O1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await gX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,Q)=>{let f=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0")-f}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,j=`${Y}.${U}`;if(await O1(Y).catch(()=>null))try{if(await O9(Y,j),$.compress)try{let W=`${j}.gz`;await this.compressLogFile(j,W),await dX(j)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await xW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await O1(Y).catch(()=>null))await O9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await gX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,j)=>j.localeCompare(U));for(let U of J.slice($.maxFiles))await dX(_1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=V9(w),A=Wq($),X=_9();await Gq(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!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($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),mX(this.currentLogFile))try{let w=S9(this.currentLogFile,"r+");L9(w),DW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await gX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await dX(_1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?g.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let w=typeof P.env.NO_COLOR<"u",$=P.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof P.stderr<"u"&&P.stderr.isTTY||typeof P.stdout<"u"&&P.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,j=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=P.stdout.columns||120,Q="";if(J==="warning"||J==="error")Q=`${Y} ${X}`;else if(J==="info"||J==="success")Q=`${Y} ${A} ${X}`;else Q=`${Y} ${A} ${g.cyan(X)}`;if(!U)return Q.trim();let f=j(Q).trim().length,z=j($).length,B=Math.max(1,W-2-f-z);return`${Q.trim()}${" ".repeat(B)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let j=Number.parseInt(U,10);return j<$[0].length?String($[0][j]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let j=$[A++];switch(U){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 J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let j=`file://${encodeURI(U)}`,W="\x1B]8;;",Q="\x1B\\";return`\x1B]8;;${j}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),$}supportsHyperlinks(){if(M0())return!1;let w=P.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=P.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(zq($)||$.startsWith("./")||$.startsWith("../"))$=Bq($);else return null;return mX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,j;if($ instanceof Error)U=$.message,j=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:Q}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":qq[w],B=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:g.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:g.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:z,tag:B,message:W,level:w}),console.error(G),j){let T=j.split(`
171
171
  `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:g.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),j)console.error(j)}let f=`${J} ${this.environment}.${w.toUpperCase()}: ${Q}
172
172
  `;if(j)f+=`${j}
173
173
  `;if(f=f.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(f)}progress(w,$=""){let Y={update:(j,W)=>{},finish:(j)=>{},interrupt:(j,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(j,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,j),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(j)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,j)},interrupt:(j,W="info")=>{if(!M0()&&P.stdout.isTTY)P.stdout.write(`
174
174
  `);if(this[W==="warning"?"warn":W](j),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":g.blue("◐"),tag:Y,message:`${g.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,j=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
175
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":g.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new FY($,{...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(!vX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return I9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=ow.isBuffer(w)?w:ow.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=Xq("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=ow.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
175
+ `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:j,icon:this.options.showIcons===!1?"":g.green("✓"),tag:f,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new KY($,{...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(!mX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return V9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.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=aw.isBuffer(w)?w:aw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),j=Uq("aes-256-gcm",Y,X);j.setAuthTag(J);let W=j.update(U),Q=j.final(),f=W.length+Q.length,z=aw.allocUnsafe(f);return W.copy(z,0),Q.copy(z,W.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=w,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(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let j=X.split(`
176
176
  `),W=Math.max(...j.map((B)=>B.length))+2,Q=`┌${"─".repeat(W)}┐`,f=`└${"─".repeat(W)}┘`,z=j.map((B)=>{return this.formatConsoleMessage({timestamp:Y,message:g.cyan(B),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(Q),showTimestamp:!1})),z.forEach((B)=>console.error(B)),console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(f),showTimestamp:!1}))}else if(!M0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
177
177
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(M0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${g.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();P.stdin.removeListener("data",Y);try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!1)}catch{}P.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!0)}catch{}P.stdin.resume(),P.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,Q=0;if(Y=w.replace(W,(f,z)=>{if(z==="%")return"%";if(Q>=$.length)return f;let B=$[Q++];switch(z){case"s":return String(B);case"d":case"i":return Number(B).toString();case"j":case"o":return JSON.stringify(B,null,2);default:return f}}),Q<$.length)Y+=` ${$.slice(Q).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${g.blue("◐")} `;console.error(`${Q}${W} ${g.cyan(A)}`)}let j=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
178
178
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(j)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!P.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=g.green("━".repeat(A)),U=g.gray("━".repeat(X)),j=`[${J}${U}]`,W=`${Y}%`.padStart(4),Q=w.message?` ${w.message}`:"",f=this.options.showIcons===!1?"":$||Y===100?g.green("✓"):g.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",B=`\r${f}${z} ${j} ${W}${Q}`,G=P.stdout.columns||80,T=" ".repeat(Math.max(0,G-B.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${B}${T}`,P.stdout.write(w.lastRenderedLine),$)P.stdout.write(`
179
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await mX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=x1(this.config.logDirectory,A);if(w.before)try{if((await D1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 gX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}var R7,M7=(w)=>w,I7=(w,$)=>{for(var Y in $)R7(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:y7.bind($,Y)})},C7=(w,$)=>()=>(w&&($=w(w=0)),$),D9,g9,Z1,KY,d9,CN,VN,G9,nX,iW,k0,e,LN,E9,SN,K9,hN,ON,VW,_N,F9,T9,LW,DN,xN,kN,ZN,lX,n9,PN,Z0,iN,bN,N9,pX,bW,R0,c,uN,q9,cN,H9,vN,mN,SW,gN,R9,M9,dN,hW,nN,lN,pN,rN,tN,rX,l9,aN,sN="0.15.6",ww,Y8,GY,uW,cW,A8,vW,mW,EY,gW,dW,F$,p9,r9,Mw,Y$,t9,a9,oN,Yq,s9,J8,z3,C0,g,M3,Gq,y3,Eq,I3,C3,O9,V3,Kq,Fq,L3,_9,S3,h3,O3,_3,D3,xW,Tq,x3;var e9=a(()=>{R7=Object.defineProperty;D9={};I7(D9,{withErrorRecovery:()=>i9,tryLoadConfig:()=>RN,loadConfigWithResult:()=>qN,loadConfig:()=>m9,isRetryableError:()=>GN,isConfigNotFoundError:()=>BN,isBunfigError:()=>b9,globalPerformanceMonitor:()=>KY,globalCache:()=>Z1,getEnvOrDefault:()=>EN,generateConfigTypes:()=>MN,defaultGeneratedDir:()=>a9,defaultConfigDir:()=>t9,deepMergeWithArrayStrategy:()=>tW,deepMerge:()=>u9,createLibraryConfig:()=>yN,config:()=>HN,bunfigPlugin:()=>IN,applyEnvVarsToConfig:()=>zY,TypeGenerationError:()=>mW,SchemaValidationError:()=>EY,PluginError:()=>dW,PerformanceMonitor:()=>lW,FileSystemError:()=>vW,ErrorFactory:()=>F$,EnvVarError:()=>A8,EnvProcessor:()=>U8,ConfigValidator:()=>aW,ConfigValidationError:()=>uW,ConfigNotFoundError:()=>Y8,ConfigMergeError:()=>cW,ConfigLoader:()=>sW,ConfigLoadError:()=>GY,ConfigFileLoader:()=>W8,ConfigCache:()=>nW,CacheUtils:()=>d9,BunfigError:()=>ww,BrowserConfigError:()=>gW,ArrayMergeStrategies:()=>p9});oN=C7(async()=>{g9=import.meta.require,Z1=new nW,KY=new lW,d9={createKey:e7,isEquivalent:wN,estimateMemoryUsage:$N},CN=sX(ZW.cwd(),"config"),VN=sX(ZW.cwd(),"src/generated"),G9=aX.env.CLARITY_LOG_DIR||_7(XN(),"logs"),nX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:G9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},iW=await JN(),k0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},e=k0,LN=k0.red,E9=k0.green,SN=k0.yellow,K9=k0.blue,hN=k0.magenta,ON=k0.cyan,VW=k0.white,_N=k0.gray,F9=k0.bgRed,T9=k0.bgYellow,LW=k0.bold,DN=k0.dim,xN=k0.italic,kN=k0.underline,ZN=k0.reset,lX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},n9={debug:"\uD83D\uDD0D",info:K9("ℹ"),success:E9("✓"),warning:T9(VW(LW(" WARN "))),error:F9(VW(LW(" ERROR ")))},PN=new eX("stacks"),Z0=new eX("bunfig",{showTags:!0}),iN=n0(BY.cwd(),"config"),bN=n0(BY.cwd(),"src/generated"),N9=tX.env.CLARITY_LOG_DIR||h7(QN(),"logs"),pX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:N9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},bW=await fN(),R0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},c=R0,uN=R0.red,q9=R0.green,cN=R0.yellow,H9=R0.blue,vN=R0.magenta,mN=R0.cyan,SW=R0.white,gN=R0.gray,R9=R0.bgRed,M9=R0.bgYellow,dN=R0.bgGray,hW=R0.bold,nN=R0.dim,lN=R0.italic,pN=R0.underline,rN=R0.strikethrough,tN=R0.reset,rX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},l9={debug:"\uD83D\uDD0D",info:H9("ℹ"),success:q9("✓"),warning:M9(SW(hW(" WARN "))),error:R9(SW(hW(" ERROR ")))},aN=new $8("stacks"),ww=class extends Error{timestamp;context;constructor($,Y={}){super($);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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},Y8=class extends ww{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},GY=class extends ww{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},uW=class extends ww{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},cW=class extends ww{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},A8=class extends ww{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},vW=class extends ww{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},mW=class extends ww{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},EY=class extends ww{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},gW=class extends ww{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},dW=class extends ww{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},F$={configNotFound(w,$,Y){return new Y8(w,$,Y)},configLoad(w,$,Y){return new GY(w,$,Y)},configValidation(w,$,Y){return new uW(w,$,Y)},configMerge(w,$,Y,A){return new cW(w,$,Y,A)},envVar(w,$,Y,A){return new A8(w,$,Y,A)},fileSystem(w,$,Y){return new vW(w,$,Y)},typeGeneration(w,$,Y){return new mW(w,$,Y)},schemaValidation(w,$,Y){return new EY(w,$,Y)},browserConfig(w,$,Y,A){return new gW(w,$,Y,A)},plugin(w,$,Y){return new dW(w,$,Y)}},p9={replace:"replace",concat:"concat",smart:"smart"},r9=/^https?:\/\//,Mw=new $8("bunfig",{showTags:!0}),Y$=new sW,t9=l0(i$.cwd(),"config"),a9=l0(i$.cwd(),"src/generated")});Yq=X8.env.CLARITY_LOG_DIR||eN($q(),"logs"),s9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Yq,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},J8={...s9},z3=(async()=>{try{let{loadConfig:w}=await oN().then(()=>D9),$=await w({name:"clarity",alias:"logging",defaultConfig:s9,cwd:X8.cwd()});if($)Object.assign(J8,$)}catch{}return J8})();C0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},g=C0,M3=C0.red,Gq=C0.green,y3=C0.yellow,Eq=C0.blue,I3=C0.magenta,C3=C0.cyan,O9=C0.white,V3=C0.gray,Kq=C0.bgRed,Fq=C0.bgYellow,L3=C0.bgGray,_9=C0.bold,S3=C0.dim,h3=C0.italic,O3=C0.underline,_3=C0.strikethrough,D3=C0.reset,xW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Tq={debug:"\uD83D\uDD0D",info:Eq("ℹ"),success:Gq("✓"),warning:Fq(O9(_9(" WARN "))),error:Kq(O9(_9(" ERROR ")))};x3=new FY("stacks")});var P1={};tj(P1,{shouldReusePort:()=>NY,safeStringify:()=>A$,safeDeleteFile:()=>wj,resolvePathRewrite:()=>eW,redactSensitive:()=>Q8,isValidRootCA:()=>oW,isSingleProxyOptions:()=>qY,isSingleProxyConfig:()=>Iq,isProcessElevated:()=>TY,isMultiProxyOptions:()=>b$,isMultiProxyConfig:()=>z8,getSudoPassword:()=>T$,getPrimaryDomain:()=>f8,extractHostname:()=>yq,execSudoSync:()=>N$,debugLog:()=>E,authorizeSystemAccess:()=>qq});import{execSync as j8}from"node:child_process";import*as $2 from"node:fs/promises";function T$(){return process.env.SUDO_PASSWORD}function TY(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function qq(w={}){if(process.platform==="win32")return!0;if(TY()||!!T$())return!0;let $=w.exec??j8;try{return $("sudo -n true",{stdio:"ignore"}),!0}catch{if(!w.interactive)return!1}try{return $("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function N$(w){if(TY())return j8(w,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let $=T$(),Y=w.replace(/'/g,"'\\''");if($)return j8(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return j8(`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)Nq.debug(`[rpx:${w}] ${$}`)}function NY(){let w=process.env.RPX_REUSE_PORT;return w==="1"||w==="true"}function Mq(w){let $=w.toLowerCase();return Hq.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function Q8(w){if(Array.isArray(w))return w.map((Y)=>Q8(Y));if(typeof w==="string")return Rq.test(w)?w2:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(Mq(Y)){$[Y]=w2;continue}$[Y]=Q8(A)}return $}function A$(w,$){return JSON.stringify(Q8(w),null,$)}function yq(w){if(b$(w))return w.proxies.map(($)=>{let Y=$.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(qY(w)){let $=w.to||"stacks.localhost";return[$.startsWith("http")?new URL($).hostname:$]}return["stacks.localhost"]}function oW(w){return typeof w==="object"&&w!==null&&"certificate"in w&&"privateKey"in w&&typeof w.certificate==="string"&&typeof w.privateKey==="string"}function f8(w){if(!w)return"stacks.localhost";if(b$(w)&&w.proxies.length>0)return w.proxies[0].to||"stacks.localhost";if(qY(w))return w.to||"stacks.localhost";return"stacks.localhost"}function z8(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}function b$(w){return"proxies"in w&&Array.isArray(w.proxies)}function qY(w){return"to"in w&&typeof w.to==="string"}function Iq(w){return!!(w&&("to"in w)&&!("proxies"in w))}function eW(w,$){if(!$||$.length===0)return null;for(let Y of $)if(w===Y.from||w.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?w.slice(Y.from.length)||"/":w;return{targetHost:A,targetPath:X}}return null}async function wj(w,$){try{await $2.unlink(w),E("certificates",`Successfully deleted: ${w}`,$)}catch(Y){if(Y.code!=="ENOENT")E("certificates",`Warning: Could not delete ${w}: ${Y}`,$)}}var Nq,w2="[redacted]",Hq,Rq;var z0=a(()=>{e9();Nq=new FY("rpx",{showTags:!1});Hq=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Rq=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as B8}from"node:child_process";import{homedir as Cq}from"node:os";import{join as Vq}from"node:path";function G8(){return Vq(Cq(),"Library/Keychains/login.keychain-db")}function Yj(){return[H$,G8()]}function Y2(w,$=$j){let Y=B8(`security find-certificate -a -c "${$}" -Z "${w}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
180
- `)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function Aj(w){if(process.platform!=="darwin")return;let $=P$(w.caPath);if(!$)return;let Y=w.commonName??$j,A=w.keychains??Yj();for(let X of A)for(let J of Y2(X,Y)){if(J===$)continue;try{if(X.startsWith("/Library"))N$(`security delete-certificate -Z ${J} "${X}"`);else B8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});E("ssl",`Removed stale Root CA ${J} from ${X}`,w.verbose)}catch{}}}function Xj(w,$,Y){if(process.platform!=="darwin")return E8(w,Y);try{let X=B8(`security verify-cert -c "${w}" -s "${$}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return E("ssl",`verify-cert ${$}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function E8(w,$){let Y=P$(w);if(!Y)return!1;for(let A of Yj())try{let X=B8(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let J of X.split(`
181
- `))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return E("ssl",`Root CA fingerprint found in ${A}`,$?.verbose),!0}}catch{}return!1}var q$="-d -r trustRoot -p ssl -p basic",H$="/Library/Keychains/System.keychain",$j="rpx.localhost";var Jj=a(()=>{DX();z0()});import{execSync as Uj}from"node:child_process";import B0 from"node:fs/promises";import*as Wj from"node:os";import{homedir as i1}from"node:os";import*as J2 from"node:path";import{join as G0}from"node:path";import*as R$ from"node:process";function U2(w,$){return[...new Set(w.filter(Boolean))].map((Y)=>({serverName:Y,cert:$.cert,key:$.key}))}function W2(w,$,Y){let A=G0(i1(),".stacks","ssl"),X=[...new Set([$,...w,"rpx.localhost"])];return{https:{certPath:jj,keyPath:G0(A,"rpx.localhost.key"),caCertPath:G0(A,"rpx.localhost.ca.crt"),commonName:$},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function j2(w){return{caCertPath:G0(w,Sq),caKeyPath:G0(w,hq)}}async function Oq(w,$){try{let[Y,A]=await Promise.all([B0.readFile(w.caCertPath,"utf8"),B0.readFile(w.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return E("ssl",`Root CA files at ${w.caCertPath} look malformed, will regenerate`,$),null;return{certificate:Y,privateKey:A}}catch(Y){return E("ssl",`No existing Root CA at ${w.caCertPath} (${Y.code||Y}), will create one`,$),null}}function A2(w){let $=new Set;$.add(w);let Y=w.split(".");if(Y.length>=3){let A=Y[Y.length-1],X=Y[Y.length-2],J=new Set(["co","com","org","net","ac","gov","edu"]);if(!(Y.length===3&&A.length===2&&J.has(X)))$.add(`*.${Y.slice(1).join(".")}`)}return Array.from($)}function Q2(w){let Y=f8(w).replace(/\*/g,"wildcard"),A=G0(i1(),".stacks","ssl"),X=A;if(typeof w?.https==="object")return X=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:A,{caCertPath:w.https.caCertPath||G0(X,`${Y}.ca.crt`),certPath:w.https.certPath||G0(X,`${Y}.crt`),keyPath:w.https.keyPath||G0(X,`${Y}.key`)};return{caCertPath:G0(X,`${Y}.ca.crt`),certPath:G0(X,`${Y}.crt`),keyPath:G0(X,`${Y}.key`)}}function X2(w){let $=new Set;if(b$(w))w.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";A2(A).forEach((X)=>$.add(X))});else if(qY(w)){let Y=w.to||"rpx.localhost";A2(Y).forEach((A)=>$.add(A))}else $.add("rpx.localhost");return $.add("localhost"),$.add("*.localhost"),$}async function HY(w){if(M$&&!w.forceRegenerate){E("ssl","Using cached SSL configuration",w.verbose);return}Qj();let $=b$(w)?w.proxies.map((f)=>f.to):[w.to];E("ssl",`Generating certificate for domains: ${$.join(", ")}`,w.verbose);let Y=RY(w,w.verbose),A=Y.basePath||G0(i1(),".stacks","ssl");await B0.mkdir(A,{recursive:!0});let X=j2(A),J=await Oq(X,w.verbose),U=!1;if(!J){if(w.verbose)H.info("Generating Root CA certificate (one-time)...");J=await QW(Y);try{await Promise.all([B0.writeFile(X.caCertPath,J.certificate),B0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,E("ssl",`Persisted Root CA at ${X.caCertPath}`,w.verbose)}catch(f){throw E("ssl",`Error saving Root CA files: ${f}`,w.verbose),Error(`Failed to save Root CA files: ${f}`)}}else E("ssl",`Reusing existing Root CA from ${X.caCertPath}`,w.verbose);if(w.verbose)H.info(`Generating host certificate for: ${$.join(", ")}`);let j=await fW({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([B0.writeFile(Y.certPath,j.certificate),B0.writeFile(Y.keyPath,j.privateKey),B0.writeFile(Y.caCertPath,J.certificate)]),E("ssl","Certificate files saved successfully",w.verbose)}catch(f){throw E("ssl",`Error saving certificate files: ${f}`,w.verbose),Error(`Failed to save certificate files: ${f}`)}if(U?!1:await z2(X.caCertPath,{verbose:w.verbose,regenerateUntrustedCerts:!0})){if(E("ssl","Root CA already trusted, skipping trust store update",w.verbose),w.verbose)H.success("Root CA is already trusted in system trust store");if(M$={key:j.privateKey,cert:j.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);return}if(w.verbose)H.info("Adding certificate to system trust store (may require sudo permission)...");let Q=!1;if(R$.platform==="darwin")try{Aj({caPath:X.caCertPath,verbose:w.verbose});let f=G8();try{Uj(`security add-trusted-cert ${q$} -k "${f}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(N$(`security add-trusted-cert ${q$} -k ${H$} "${X.caCertPath}"`),w.verbose)H.success("Successfully added Root CA to system trust store");Q=!0;let z=G0(A,"trust-rpx-cert.sh"),B=`#!/bin/bash
179
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await gX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=_1(this.config.logDirectory,A);if(w.before)try{if((await O1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}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 dX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}var y7,I7=(w)=>w,V7=(w,$)=>{for(var Y in $)y7(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:C7.bind($,Y)})},L7=(w,$)=>()=>(w&&($=w(w=0)),$),k9,n9,x1,EY,l9,LN,SN,K9,lX,bW,k0,w0,hN,F9,ON,T9,_N,DN,LW,xN,N9,q9,SW,kN,ZN,PN,iN,pX,p9,bN,Z0,uN,cN,H9,rX,uW,R0,c,vN,R9,mN,M9,gN,dN,hW,nN,y9,I9,lN,OW,pN,rN,tN,aN,sN,tX,r9,oN,eN="0.15.6",Yw,A8,BY,cW,vW,X8,mW,gW,GY,dW,nW,K$,t9,a9,yw,w$,s9,o9,wq,Xq,e9,U8,G3,C0,g,I3,Kq,C3,Fq,V3,L3,D9,S3,Tq,Nq,h3,x9,O3,_3,D3,x3,k3,kW,qq,Z3;var $2=s(()=>{y7=Object.defineProperty;k9={};V7(k9,{withErrorRecovery:()=>u9,tryLoadConfig:()=>yN,loadConfigWithResult:()=>RN,loadConfig:()=>d9,isRetryableError:()=>KN,isConfigNotFoundError:()=>EN,isBunfigError:()=>c9,globalPerformanceMonitor:()=>EY,globalCache:()=>x1,getEnvOrDefault:()=>FN,generateConfigTypes:()=>IN,defaultGeneratedDir:()=>o9,defaultConfigDir:()=>s9,deepMergeWithArrayStrategy:()=>aW,deepMerge:()=>v9,createLibraryConfig:()=>CN,config:()=>MN,bunfigPlugin:()=>VN,applyEnvVarsToConfig:()=>fY,TypeGenerationError:()=>gW,SchemaValidationError:()=>GY,PluginError:()=>nW,PerformanceMonitor:()=>pW,FileSystemError:()=>mW,ErrorFactory:()=>K$,EnvVarError:()=>X8,EnvProcessor:()=>W8,ConfigValidator:()=>sW,ConfigValidationError:()=>cW,ConfigNotFoundError:()=>A8,ConfigMergeError:()=>vW,ConfigLoader:()=>oW,ConfigLoadError:()=>BY,ConfigFileLoader:()=>j8,ConfigCache:()=>lW,CacheUtils:()=>l9,BunfigError:()=>Yw,BrowserConfigError:()=>dW,ArrayMergeStrategies:()=>t9});wq=L7(async()=>{n9=import.meta.require,x1=new lW,EY=new pW,l9={createKey:$N,isEquivalent:YN,estimateMemoryUsage:AN},LN=oX(PW.cwd(),"config"),SN=oX(PW.cwd(),"src/generated"),K9=sX.env.CLARITY_LOG_DIR||x7(UN(),"logs"),lX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:K9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},bW=await WN(),k0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},w0=k0,hN=k0.red,F9=k0.green,ON=k0.yellow,T9=k0.blue,_N=k0.magenta,DN=k0.cyan,LW=k0.white,xN=k0.gray,N9=k0.bgRed,q9=k0.bgYellow,SW=k0.bold,kN=k0.dim,ZN=k0.italic,PN=k0.underline,iN=k0.reset,pX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},p9={debug:"\uD83D\uDD0D",info:T9("ℹ"),success:F9("✓"),warning:q9(LW(SW(" WARN "))),error:N9(LW(SW(" ERROR ")))},bN=new w8("stacks"),Z0=new w8("bunfig",{showTags:!0}),uN=n0(zY.cwd(),"config"),cN=n0(zY.cwd(),"src/generated"),H9=aX.env.CLARITY_LOG_DIR||_7(zN(),"logs"),rX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:H9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},uW=await BN(),R0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},c=R0,vN=R0.red,R9=R0.green,mN=R0.yellow,M9=R0.blue,gN=R0.magenta,dN=R0.cyan,hW=R0.white,nN=R0.gray,y9=R0.bgRed,I9=R0.bgYellow,lN=R0.bgGray,OW=R0.bold,pN=R0.dim,rN=R0.italic,tN=R0.underline,aN=R0.strikethrough,sN=R0.reset,tX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},r9={debug:"\uD83D\uDD0D",info:M9("ℹ"),success:R9("✓"),warning:I9(hW(OW(" WARN "))),error:y9(hW(OW(" ERROR ")))},oN=new Y8("stacks"),Yw=class extends Error{timestamp;context;constructor($,Y={}){super($);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 $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},A8=class extends Yw{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},BY=class extends Yw{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},cW=class extends Yw{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},vW=class extends Yw{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},X8=class extends Yw{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},mW=class extends Yw{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},gW=class extends Yw{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},GY=class extends Yw{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},dW=class extends Yw{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},nW=class extends Yw{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},K$={configNotFound(w,$,Y){return new A8(w,$,Y)},configLoad(w,$,Y){return new BY(w,$,Y)},configValidation(w,$,Y){return new cW(w,$,Y)},configMerge(w,$,Y,A){return new vW(w,$,Y,A)},envVar(w,$,Y,A){return new X8(w,$,Y,A)},fileSystem(w,$,Y){return new mW(w,$,Y)},typeGeneration(w,$,Y){return new gW(w,$,Y)},schemaValidation(w,$,Y){return new GY(w,$,Y)},browserConfig(w,$,Y,A){return new dW(w,$,Y,A)},plugin(w,$,Y){return new nW(w,$,Y)}},t9={replace:"replace",concat:"concat",smart:"smart"},a9=/^https?:\/\//,yw=new Y8("bunfig",{showTags:!0}),w$=new oW,s9=l0(Z$.cwd(),"config"),o9=l0(Z$.cwd(),"src/generated")});Xq=J8.env.CLARITY_LOG_DIR||$q(Aq(),"logs"),e9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Xq,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},U8={...e9},G3=(async()=>{try{let{loadConfig:w}=await wq().then(()=>k9),$=await w({name:"clarity",alias:"logging",defaultConfig:e9,cwd:J8.cwd()});if($)Object.assign(U8,$)}catch{}return U8})();C0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},g=C0,I3=C0.red,Kq=C0.green,C3=C0.yellow,Fq=C0.blue,V3=C0.magenta,L3=C0.cyan,D9=C0.white,S3=C0.gray,Tq=C0.bgRed,Nq=C0.bgYellow,h3=C0.bgGray,x9=C0.bold,O3=C0.dim,_3=C0.italic,D3=C0.underline,x3=C0.strikethrough,k3=C0.reset,kW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},qq={debug:"\uD83D\uDD0D",info:Fq("ℹ"),success:Kq("✓"),warning:Nq(D9(x9(" WARN "))),error:Tq(D9(x9(" ERROR ")))};Z3=new KY("stacks")});var k1={};sj(k1,{shouldReusePort:()=>TY,safeStringify:()=>$$,safeDeleteFile:()=>$j,resolvePathRewrite:()=>wj,redactSensitive:()=>f8,isValidRootCA:()=>eW,isSingleProxyOptions:()=>NY,isSingleProxyConfig:()=>Vq,isProcessElevated:()=>FY,isMultiProxyOptions:()=>P$,isMultiProxyConfig:()=>B8,getSudoPassword:()=>F$,getPrimaryDomain:()=>z8,extractHostname:()=>Cq,execSudoSync:()=>T$,debugLog:()=>E,authorizeSystemAccess:()=>Rq});import{execSync as Q8}from"node:child_process";import*as A2 from"node:fs/promises";function F$(){return process.env.SUDO_PASSWORD}function FY(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function Rq(w={}){if(process.platform==="win32")return!0;if(FY()||!!F$())return!0;let $=w.exec??Q8;try{return $("sudo -n true",{stdio:"ignore"}),!0}catch{if(!w.interactive)return!1}try{return $("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function T$(w){if(FY())return Q8(w,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let $=F$(),Y=w.replace(/'/g,"'\\''");if($)return Q8(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return Q8(`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)Hq.debug(`[rpx:${w}] ${$}`)}function TY(){let w=process.env.RPX_REUSE_PORT;return w==="1"||w==="true"}function Iq(w){let $=w.toLowerCase();return Mq.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function f8(w){if(Array.isArray(w))return w.map((Y)=>f8(Y));if(typeof w==="string")return yq.test(w)?Y2:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(Iq(Y)){$[Y]=Y2;continue}$[Y]=f8(A)}return $}function $$(w,$){return JSON.stringify(f8(w),null,$)}function Cq(w){if(P$(w))return w.proxies.map(($)=>{let Y=$.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(NY(w)){let $=w.to||"stacks.localhost";return[$.startsWith("http")?new URL($).hostname:$]}return["stacks.localhost"]}function eW(w){return typeof w==="object"&&w!==null&&"certificate"in w&&"privateKey"in w&&typeof w.certificate==="string"&&typeof w.privateKey==="string"}function z8(w){if(!w)return"stacks.localhost";if(P$(w)&&w.proxies.length>0)return w.proxies[0].to||"stacks.localhost";if(NY(w))return w.to||"stacks.localhost";return"stacks.localhost"}function B8(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}function P$(w){return"proxies"in w&&Array.isArray(w.proxies)}function NY(w){return"to"in w&&typeof w.to==="string"}function Vq(w){return!!(w&&("to"in w)&&!("proxies"in w))}function wj(w,$){if(!$||$.length===0)return null;for(let Y of $)if(w===Y.from||w.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?w.slice(Y.from.length)||"/":w;return{targetHost:A,targetPath:X}}return null}async function $j(w,$){try{await A2.unlink(w),E("certificates",`Successfully deleted: ${w}`,$)}catch(Y){if(Y.code!=="ENOENT")E("certificates",`Warning: Could not delete ${w}: ${Y}`,$)}}var Hq,Y2="[redacted]",Mq,yq;var z0=s(()=>{$2();Hq=new KY("rpx",{showTags:!1});Mq=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),yq=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as G8}from"node:child_process";import{homedir as Lq}from"node:os";import{join as Sq}from"node:path";function E8(){return Sq(Lq(),"Library/Keychains/login.keychain-db")}function Aj(){return[q$,E8()]}function X2(w,$=Yj){let Y=G8(`security find-certificate -a -c "${$}" -Z "${w}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
180
+ `)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function Xj(w){if(process.platform!=="darwin")return;let $=k$(w.caPath);if(!$)return;let Y=w.commonName??Yj,A=w.keychains??Aj();for(let X of A)for(let J of X2(X,Y)){if(J===$)continue;try{if(X.startsWith("/Library"))T$(`security delete-certificate -Z ${J} "${X}"`);else G8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});E("ssl",`Removed stale Root CA ${J} from ${X}`,w.verbose)}catch{}}}function Jj(w,$,Y){if(process.platform!=="darwin")return K8(w,Y);try{let X=G8(`security verify-cert -c "${w}" -s "${$}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return E("ssl",`verify-cert ${$}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function K8(w,$){let Y=k$(w);if(!Y)return!1;for(let A of Aj())try{let X=G8(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let J of X.split(`
181
+ `))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return E("ssl",`Root CA fingerprint found in ${A}`,$?.verbose),!0}}catch{}return!1}var N$="-d -r trustRoot -p ssl -p basic",q$="/Library/Keychains/System.keychain",Yj="rpx.localhost";var Uj=s(()=>{xX();z0()});import{execSync as Wj}from"node:child_process";import B0 from"node:fs/promises";import*as jj from"node:os";import{homedir as Z1}from"node:os";import*as W2 from"node:path";import{join as G0}from"node:path";import*as H$ from"node:process";function j2(w,$){return[...new Set(w.filter(Boolean))].map((Y)=>({serverName:Y,cert:$.cert,key:$.key}))}function Q2(w,$,Y){let A=G0(Z1(),".stacks","ssl"),X=[...new Set([$,...w,"rpx.localhost"])];return{https:{certPath:Qj,keyPath:G0(A,"rpx.localhost.key"),caCertPath:G0(A,"rpx.localhost.ca.crt"),commonName:$},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function f2(w){return{caCertPath:G0(w,Oq),caKeyPath:G0(w,_q)}}async function Dq(w,$){try{let[Y,A]=await Promise.all([B0.readFile(w.caCertPath,"utf8"),B0.readFile(w.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return E("ssl",`Root CA files at ${w.caCertPath} look malformed, will regenerate`,$),null;return{certificate:Y,privateKey:A}}catch(Y){return E("ssl",`No existing Root CA at ${w.caCertPath} (${Y.code||Y}), will create one`,$),null}}function J2(w){let $=new Set;$.add(w);let Y=w.split(".");if(Y.length>=3){let A=Y[Y.length-1],X=Y[Y.length-2],J=new Set(["co","com","org","net","ac","gov","edu"]);if(!(Y.length===3&&A.length===2&&J.has(X)))$.add(`*.${Y.slice(1).join(".")}`)}return Array.from($)}function z2(w){let Y=z8(w).replace(/\*/g,"wildcard"),A=G0(Z1(),".stacks","ssl"),X=A;if(typeof w?.https==="object")return X=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:A,{caCertPath:w.https.caCertPath||G0(X,`${Y}.ca.crt`),certPath:w.https.certPath||G0(X,`${Y}.crt`),keyPath:w.https.keyPath||G0(X,`${Y}.key`)};return{caCertPath:G0(X,`${Y}.ca.crt`),certPath:G0(X,`${Y}.crt`),keyPath:G0(X,`${Y}.key`)}}function U2(w){let $=new Set;if(P$(w))w.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";J2(A).forEach((X)=>$.add(X))});else if(NY(w)){let Y=w.to||"rpx.localhost";J2(Y).forEach((A)=>$.add(A))}else $.add("rpx.localhost");return $.add("localhost"),$.add("*.localhost"),$}async function qY(w){if(R$&&!w.forceRegenerate){E("ssl","Using cached SSL configuration",w.verbose);return}fj();let $=P$(w)?w.proxies.map((f)=>f.to):[w.to];E("ssl",`Generating certificate for domains: ${$.join(", ")}`,w.verbose);let Y=HY(w,w.verbose),A=Y.basePath||G0(Z1(),".stacks","ssl");await B0.mkdir(A,{recursive:!0});let X=f2(A),J=await Dq(X,w.verbose),U=!1;if(!J){if(w.verbose)H.info("Generating Root CA certificate (one-time)...");J=await fW(Y);try{await Promise.all([B0.writeFile(X.caCertPath,J.certificate),B0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,E("ssl",`Persisted Root CA at ${X.caCertPath}`,w.verbose)}catch(f){throw E("ssl",`Error saving Root CA files: ${f}`,w.verbose),Error(`Failed to save Root CA files: ${f}`)}}else E("ssl",`Reusing existing Root CA from ${X.caCertPath}`,w.verbose);if(w.verbose)H.info(`Generating host certificate for: ${$.join(", ")}`);let j=await zW({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([B0.writeFile(Y.certPath,j.certificate),B0.writeFile(Y.keyPath,j.privateKey),B0.writeFile(Y.caCertPath,J.certificate)]),E("ssl","Certificate files saved successfully",w.verbose)}catch(f){throw E("ssl",`Error saving certificate files: ${f}`,w.verbose),Error(`Failed to save certificate files: ${f}`)}if(U?!1:await G2(X.caCertPath,{verbose:w.verbose,regenerateUntrustedCerts:!0})){if(E("ssl","Root CA already trusted, skipping trust store update",w.verbose),w.verbose)H.success("Root CA is already trusted in system trust store");if(R$={key:j.privateKey,cert:j.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);return}if(w.verbose)H.info("Adding certificate to system trust store (may require sudo permission)...");let Q=!1;if(H$.platform==="darwin")try{Xj({caPath:X.caCertPath,verbose:w.verbose});let f=E8();try{Wj(`security add-trusted-cert ${N$} -k "${f}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(T$(`security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"`),w.verbose)H.success("Successfully added Root CA to system trust store");Q=!0;let z=G0(A,"trust-rpx-cert.sh"),B=`#!/bin/bash
182
182
  echo "Trusting RPX Root CA"
183
183
  # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
184
184
  # non-interactive. Without it, fall back to a normal sudo prompt.
185
185
  if [ -n "$SUDO_PASSWORD" ]
186
186
  then
187
187
  printf '%s
188
- ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${q$} -k ${H$} "${X.caCertPath}"
188
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"
189
189
  else
190
- sudo security add-trusted-cert ${q$} -k ${H$} "${X.caCertPath}"
190
+ sudo security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"
191
191
  fi
192
192
  echo "Root CA trusted! Please restart your browser."
193
193
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
@@ -198,59 +198,59 @@ echo "Trusting RPX Root CA"
198
198
  if [ -n "$SUDO_PASSWORD" ]
199
199
  then
200
200
  printf '%s
201
- ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${q$} -k ${H$} "${X.caCertPath}"
201
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"
202
202
  else
203
- sudo security add-trusted-cert ${q$} -k ${H$} "${X.caCertPath}"
203
+ sudo security add-trusted-cert ${N$} -k ${q$} "${X.caCertPath}"
204
204
  fi
205
205
  echo "Root CA trusted! Please restart your browser."
206
206
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
207
- `;if(await B0.writeFile(z,B,{mode:493}),w.verbose)H.info(`Created a trust helper script at: ${z}`),H.info(`If you're still having certificate issues, run: sh ${z}`)}else if(R$.platform==="linux")try{let{exec:f}=await import("node:child_process"),z="/usr/local/share/ca-certificates/rpx",B=`
207
+ `;if(await B0.writeFile(z,B,{mode:493}),w.verbose)H.info(`Created a trust helper script at: ${z}`),H.info(`If you're still having certificate issues, run: sh ${z}`)}else if(H$.platform==="linux")try{let{exec:f}=await import("node:child_process"),z="/usr/local/share/ca-certificates/rpx",B=`
208
208
  mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
209
209
  cp "${X.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
210
210
  update-ca-certificates
211
211
  echo "RPX Root CA installed. Please restart your browser."
212
- `,G=G0(Wj.tmpdir(),`rpx-trust-${Date.now()}.sh`);await B0.writeFile(G,B,{mode:493}),await new Promise((T)=>{f(`sudo bash "${G}"`,(K)=>{if(K){if(w.verbose)H.warn(`Could not trust certificates: ${K}`);T(!1)}else{if(w.verbose)H.success("Successfully added certificates to system trust store");T(!0)}})}),await B0.unlink(G).catch(()=>{}),Q=!0}catch(f){if(w.verbose)H.warn(`Failed to trust certificates: ${f}`)}else if(R$.platform==="win32")try{let f=`
212
+ `,G=G0(jj.tmpdir(),`rpx-trust-${Date.now()}.sh`);await B0.writeFile(G,B,{mode:493}),await new Promise((T)=>{f(`sudo bash "${G}"`,(K)=>{if(K){if(w.verbose)H.warn(`Could not trust certificates: ${K}`);T(!1)}else{if(w.verbose)H.success("Successfully added certificates to system trust store");T(!0)}})}),await B0.unlink(G).catch(()=>{}),Q=!0}catch(f){if(w.verbose)H.warn(`Failed to trust certificates: ${f}`)}else if(H$.platform==="win32")try{let f=`
213
213
  $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${X.caCertPath.replace(/\//g,"\\")}")
214
214
  $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
215
215
  $store.Open("ReadWrite")
216
216
  $store.Add($cert)
217
217
  $store.Close()
218
218
  Write-Host "Root CA trusted successfully!"
219
- `,z=G0(Wj.tmpdir(),"rpx-trust.ps1");if(await B0.writeFile(z,f),Uj(`powershell -ExecutionPolicy Bypass -File "${z}"`),w.verbose)H.success("Successfully added certificate to Windows trust store");Q=!0}catch(f){if(w.verbose)H.warn(`Could not trust certificate: ${f}`)}else try{await GW(j,J.certificate,Y),Q=!0}catch(f){if(w.verbose)H.warn(`Could not add certificate to trust store: ${f}`)}if(M$={key:j.privateKey,cert:j.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);if(!Q&&w.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function Qj(){M$=null}async function y$(w){if(!w)return null;if(M$)return M$;let $=RY(w);try{let[Y,A,X]=await Promise.all([B0.access($.keyPath).then(()=>!0).catch(()=>!1),B0.access($.certPath).then(()=>!0).catch(()=>!1),$.caCertPath?B0.access($.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return E("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${$.keyPath}, ${$.certPath}`,w.verbose),null;let J="regenerateUntrustedCerts"in w,U=w.regenerateUntrustedCerts,j=J?U!==!1:!0;E("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${j}`,w.verbose);let W=$.basePath||G0(i1(),".stacks","ssl"),Q=j2(W);if(!(j?await z2(Q.caCertPath,w):!0))return E("ssl","Root CA exists but is not trusted, will regenerate",w.verbose),null;let[z,B,G]=await Promise.all([B0.readFile($.keyPath,"utf8"),B0.readFile($.certPath,"utf8"),X&&$.caCertPath?B0.readFile($.caCertPath,"utf8"):Promise.resolve(void 0)]);if(G&&!G.includes("-----BEGIN CERTIFICATE-----"))return E("ssl","Invalid root CA certificate content, will regenerate",w.verbose),null;if(b$(w))try{let{X509Certificate:T}=await import("node:crypto"),F=new T(B).subjectAltName||"",R=w.proxies.map((L)=>L.to).filter((L)=>!F.includes(`DNS:${L}`));if(R.length>0)return E("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,w.verbose),null}catch(T){E("ssl",`Could not verify cert SANs: ${T}`,w.verbose)}return E("ssl","Successfully loaded existing certificates",w.verbose),M$={key:z,cert:B,ca:G},M$}catch(Y){return E("ssl",`Error checking existing certificates: ${Y}`,w.verbose),null}}function RY(w,$){let Y=f8(w);E("ssl",`Primary domain: ${Y}`,$);let A=Q2(w),X=G0(i1(),".stacks","ssl");if(typeof w.https==="object"){let J=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:w.https.caCertPath||A.caCertPath,certPath:w.https.certPath||A.certPath,keyPath:w.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:w.https.commonName||Y,organizationName:w.https.organizationName||"Local Development",countryName:w.https.countryName||"US",stateName:w.https.stateName||"California",localityName:w.https.localityName||"Playa Vista",validityDays:w.https.validityDays||825,verbose:$||!1,subjectAltNames:Array.from(X2(w)).map((j)=>({type:2,value:j}))};if(oW(w.https.rootCA))U.rootCA=w.https.rootCA;return U}return{domain:Y,hostCertCN:Y,basePath:X,...A,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:Y,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:$||!1,subjectAltNames:Array.from(X2(w)).map((J)=>({type:2,value:J}))}}async function f2(w,$){let Y=Q2({to:w,verbose:$}),A=[Y.caCertPath,Y.certPath,Y.keyPath];E("certificates","Attempting to clean up relating certificates",$),await Promise.all(A.map((X)=>wj(X,$)))}async function z2(w,$){try{if(E("ssl",`Checking if certificate is trusted: ${w}`,$?.verbose),R$.platform==="darwin"){if($?.serverName)return Xj(w,$.serverName,{verbose:$?.verbose});return E8(w,{verbose:$?.verbose})}else if(R$.platform==="win32")try{let Y=EW(w)||"";if(!Y)return E("ssl","Could not extract certificate subject",$?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(Uj(A).toString().includes(Y))return E("ssl","Certificate found in trusted root store",$?.verbose),!0;return E("ssl","Certificate not found in trusted root store",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Windows: ${Y}`,$?.verbose),!1}else if(R$.platform==="linux")try{let Y=P$(w);if(!Y)return E("ssl","Could not extract certificate fingerprint",$?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await B0.readdir(X)}catch{continue}for(let U of J){let j=P$(J2.join(X,U));if(j&&j===Y)return E("ssl",`Certificate fingerprint found in ${X}`,$?.verbose),!0}}return E("ssl","Certificate not found in system trust stores",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Linux: ${Y}`,$?.verbose),!1}return E("ssl",`Platform ${R$.platform} not supported for certificate trust check`,$?.verbose),!1}catch(Y){return E("ssl",`Error checking if certificate is trusted: ${Y}`,$?.verbose),!1}}var M$=null,jj,Sq="rpx-root-ca.crt",hq="rpx-root-ca.key";var fj=a(()=>{_X();x$();PA();Jj();z0();Jj();DX();DX();jj=G0(i1(),".stacks","ssl","rpx.localhost.crt")});function _q(w){return{enabled:w?.enabled??!1,path:w?.path??"/",interval:w?.interval??1e4,timeout:w?.timeout??2000,healthyThreshold:w?.healthyThreshold??2,unhealthyThreshold:w?.unhealthyThreshold??3}}function Dq(w){return(Array.isArray(w)?w:[w]).map((Y)=>{let A=typeof Y==="string"?{url:Y}:Y;return{url:A.url,weight:A.weight&&A.weight>0?A.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function B2(w){return(Array.isArray(w)?w:[w]).map((Y)=>typeof Y==="string"?Y:Y.url)}function u$(w){if(!w)return"localhost:5173";let $=Array.isArray(w)?w[0]:w;if(!$)return"localhost:5173";return typeof $==="string"?$:$.url}function MY(w,$){return{upstreams:Dq(w),strategy:$?.strategy??"round-robin",healthCheck:_q($?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function xq(w){let $=w.upstreams.filter((Y)=>Y.healthy);if($.length===0&&w.upstreams.length===1)return w.upstreams;return $}function kq(w,$){let Y=w.cursor%$.length;return w.cursor=(w.cursor+1)%$.length,$[Y]}function Zq(w,$){if(w.wrrCurrentWeights.length!==$.length)w.wrrCurrentWeights=$.map(()=>0);let Y=$.reduce((X,J)=>X+J.weight,0),A=0;for(let X=0;X<$.length;X++)if(w.wrrCurrentWeights[X]+=$[X].weight,w.wrrCurrentWeights[X]>w.wrrCurrentWeights[A])A=X;return w.wrrCurrentWeights[A]-=Y,$[A]}function Pq(w){let $=w[0];for(let Y=1;Y<w.length;Y++)if(w[Y].activeConnections<$.activeConnections)$=w[Y];return $}function G2(w){let $=xq(w);if($.length===0)return;if($.length===1)return $[0];switch(w.strategy){case"weighted-round-robin":return Zq(w,$);case"least-connections":return Pq($);case"round-robin":default:return kq(w,$)}}function K8(w,$){if($.consecutiveFailures=0,$.consecutiveSuccesses+=1,!$.healthy&&$.consecutiveSuccesses>=w.healthCheck.healthyThreshold)$.healthy=!0}function yY(w,$){if($.consecutiveSuccesses=0,$.consecutiveFailures+=1,$.healthy&&$.consecutiveFailures>=w.healthCheck.unhealthyThreshold)$.healthy=!1}function iq(w){let $=w.lastIndexOf(":");if($===-1)return{hostname:w,port:80};let Y=Number(w.slice($+1));return{hostname:w.slice(0,$),port:Number.isFinite(Y)?Y:80}}async function bq(w,$){let{hostname:Y,port:A}=iq($.url),X=new AbortController,J=setTimeout(()=>X.abort(),w.healthCheck.timeout);try{(await fetch(`http://${Y}:${A}${w.healthCheck.path}`,{signal:X.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),K8(w,$)}catch{yY(w,$)}finally{clearTimeout(J)}}function IY(w){if(!w.healthCheck.enabled||w.healthCheckTimer||w.upstreams.length<2)return;let $=setInterval(()=>{for(let Y of w.upstreams)bq(w,Y)},w.healthCheck.interval);$.unref?.(),w.healthCheckTimer=$}function b1(w){if(w.healthCheckTimer)clearInterval(w.healthCheckTimer),w.healthCheckTimer=null}import{createHash as K2,timingSafeEqual as E2}from"node:crypto";import{readFileSync as uq}from"node:fs";function CY(w,$){let Y=Buffer.from(w,"utf8"),A=Buffer.from($,"utf8");if(Y.length!==A.length)return E2(Y,Y),!1;return E2(Y,A)}function vq(w,$){let Y=(B)=>K2("md5").update(B).digest(),A=Buffer.from(w,"utf8"),X=Buffer.from($,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let B=A.length;B>0;B-=16)U.push(J.subarray(0,Math.min(B,16)));for(let B=A.length;B>0;B>>=1)U.push(B&1?Buffer.from([0]):A.subarray(0,1));let j=Y(Buffer.concat(U));for(let B=0;B<1000;B++){let G=[];if(G.push(B&1?A:j.subarray(0,16)),B%3)G.push(X);if(B%7)G.push(A);G.push(B&1?j.subarray(0,16):A),j=Y(Buffer.concat(G))}let W="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Q=(B,G)=>{let T="",K=B;for(let F=0;F<G;F++)T+=W[K&63],K>>=6;return T},f=j,z="";return z+=Q(f[0]<<16|f[6]<<8|f[12],4),z+=Q(f[1]<<16|f[7]<<8|f[13],4),z+=Q(f[2]<<16|f[8]<<8|f[14],4),z+=Q(f[3]<<16|f[9]<<8|f[15],4),z+=Q(f[4]<<16|f[10]<<8|f[5],4),z+=Q(f[11],2),`$apr1$${$}$${z}`}function mq(w,$){if(/^\$2[aby]?\$/.test($))try{return Bun.password.verifySync(w,$)}catch{return!1}if($.startsWith("$apr1$")){let A=$.split("$")[2]??"";return CY(vq(w,A),$)}if($.startsWith("{SHA}")){let Y=K2("sha1").update(w,"utf8").digest("base64");return CY(`{SHA}${Y}`,$)}return CY(w,$)}function gq(w){let $=new Map;for(let Y of w.split(`
220
- `)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;$.set(A.slice(0,X),A.slice(X+1))}return $}function VY(w){if(!w)return;let $=(w.realm??"").trim()||"Restricted",Y=[];if(w.username)Y.push({username:w.username,password:w.password??""});for(let J of w.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if(w.htpasswdFile)try{A=gq(uq(w.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:$,verify:(J,U)=>{let j=!1;for(let W of Y)if(CY(J,W.username)&&CY(U,W.password))j=!0;if(A){let W=A.get(J);if(W&&mq(U,W))j=!0}return j}}}function F2(w,$,Y){if($.startsWith(cq))return;let A=w.headers.get("authorization")??"",X=A.indexOf(" "),J=X===-1?A:A.slice(0,X),U=X===-1?"":A.slice(X+1).trim();if(J.toLowerCase()==="basic"&&U){let W="";try{W=Buffer.from(U,"base64").toString("utf8")}catch{W=""}let Q=W.indexOf(":");if(Q>=0&&Y.verify(W.slice(0,Q),W.slice(Q+1)))return}let j=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${j}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var cq="/.well-known/acme-challenge/";var F8=()=>{};function lq(w){return nq.has(w.toUpperCase())}function pq(){let w=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(w)&&w>0?w:30000}function rq(w){let $=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite($)&&$>0?$:w*8}function tq(){let w=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(w)&&w>0?w:0}function aq(){let w=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(w)&&w>0?w:0}function sq(){let w=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(w)&&w>0?w:256}class R2{socket=null;buf=new Uint8Array(oq);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(w){let $=this.socket,Y=$.write(w);while(Y<w.length){if(this.closed)throw T8;await new Promise((A)=>{this.drainWaiter=A}),Y+=$.write(w.subarray(Y))}}wakeDrain(){let w=this.drainWaiter;if(w)this.drainWaiter=null,w()}push(w){if(this.bodyQueue){let $=w.length<=this.bodyRemaining?w.length:this.bodyRemaining;if($>0)this.bodyQueue.push(w.slice(0,$)),this.queuedBytes+=$;if(this.bodyRemaining-=$,$<w.length)this.appendToBuf(w.subarray($));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(w),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()>eq)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=wH)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(w){let $=this.len+w.length;if($>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,$));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set(w,this.len),this.len=$}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let w=this.waiter;if(w)this.waiter=null,w()}waitForData(w){if(this.len>w||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}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 M2{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=pq();maxWaiters;checkoutIdleMs=tq();inUse=new Set;constructor(w,$,Y,A=""){this.host=w;this.port=$;this.maxTotal=Y;this.key=A;this.maxWaiters=rq(Y)}trackCheckout(w){if(w.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(w),this.ensureSweeper()}dial(){let w=new R2;return dq({hostname:this.host,port:this.port,socket:{data:($,Y)=>w.push(Y),drain:()=>w.wakeDrain(),close:()=>w.markClosed(),end:()=>w.markClosed(),error:()=>w.markClosed(),connectError:()=>w.markClosed(),timeout:()=>w.markTimedOut()}}).then(($)=>{let Y=$;Y.setNoDelay?.(!0);let A=aq();if(A>0)Y.timeout?.(A);return w.socket=$,w})}acquireIdleSync(){while(this.idle.length){let w=this.idle.pop();if(!w.closed)return w.socket?.ref(),w.pos=0,w.len=0,this.trackCheckout(w),w;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw c$;let w=await this.waitForSlot();if(w===c$)throw c$;if(w)return w.pos=0,w.len=0,this.trackCheckout(w),w}this.open++;try{let w=await this.dial();return this.trackCheckout(w),w}catch(w){throw this.open--,this.wakeWaiter(),w}}waitForSlot(){return new Promise((w)=>{let $=!1,Y=(J)=>{if($)return;$=!0,clearTimeout(X),w(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(c$)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release(w){if(this.inUse.delete(w),w.closed){this.open--,this.wakeWaiter();return}w.clearStreaming(),w.compact(),w.fresh=!1;let $=this.waiters.shift();if($){w.socket?.ref(),this.trackCheckout(w),$(w);return}w.idleSince=Date.now(),w.socket?.unref(),this.idle.push(w),this.ensureSweeper()}destroy(w){this.inUse.delete(w),w.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let w=this.waiters.shift();if(w)w(null)}ensureSweeper(){if(this.sweeper)return;let w=this.checkoutIdleMs>0?Math.min(zj,this.checkoutIdleMs):zj;this.sweeper=setInterval(()=>this.sweep(),w),this.sweeper.unref?.()}sweep(){let w=Date.now(),$=w-zj;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=$)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=w-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){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&N8.get(this.key)===this)N8.delete(this.key)}}}function JH(w,$){let Y=N8.get(w);if(!Y){let A=w.lastIndexOf(":"),X=A===-1?w:w.slice(0,A),J=A===-1?80:Number(w.slice(A+1));Y=new M2(X,J,$,w),N8.set(w,Y)}return Y}function T2(w,$,Y){for(let A=Y+3;A<$;A++)if(w[A]===10&&w[A-1]===13&&w[A-2]===10&&w[A-3]===13)return A-3;return-1}function UH(w,$,Y){let A=H2.decode(w.subarray($,Y)),X=A.indexOf(`\r
219
+ `,z=G0(jj.tmpdir(),"rpx-trust.ps1");if(await B0.writeFile(z,f),Wj(`powershell -ExecutionPolicy Bypass -File "${z}"`),w.verbose)H.success("Successfully added certificate to Windows trust store");Q=!0}catch(f){if(w.verbose)H.warn(`Could not trust certificate: ${f}`)}else try{await EW(j,J.certificate,Y),Q=!0}catch(f){if(w.verbose)H.warn(`Could not add certificate to trust store: ${f}`)}if(R$={key:j.privateKey,cert:j.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);if(!Q&&w.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function fj(){R$=null}async function M$(w){if(!w)return null;if(R$)return R$;let $=HY(w);try{let[Y,A,X]=await Promise.all([B0.access($.keyPath).then(()=>!0).catch(()=>!1),B0.access($.certPath).then(()=>!0).catch(()=>!1),$.caCertPath?B0.access($.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return E("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${$.keyPath}, ${$.certPath}`,w.verbose),null;let J="regenerateUntrustedCerts"in w,U=w.regenerateUntrustedCerts,j=J?U!==!1:!0;E("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${j}`,w.verbose);let W=$.basePath||G0(Z1(),".stacks","ssl"),Q=f2(W);if(!(j?await G2(Q.caCertPath,w):!0))return E("ssl","Root CA exists but is not trusted, will regenerate",w.verbose),null;let[z,B,G]=await Promise.all([B0.readFile($.keyPath,"utf8"),B0.readFile($.certPath,"utf8"),X&&$.caCertPath?B0.readFile($.caCertPath,"utf8"):Promise.resolve(void 0)]);if(G&&!G.includes("-----BEGIN CERTIFICATE-----"))return E("ssl","Invalid root CA certificate content, will regenerate",w.verbose),null;if(P$(w))try{let{X509Certificate:T}=await import("node:crypto"),F=new T(B).subjectAltName||"",R=w.proxies.map((V)=>V.to).filter((V)=>!F.includes(`DNS:${V}`));if(R.length>0)return E("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,w.verbose),null}catch(T){E("ssl",`Could not verify cert SANs: ${T}`,w.verbose)}return E("ssl","Successfully loaded existing certificates",w.verbose),R$={key:z,cert:B,ca:G},R$}catch(Y){return E("ssl",`Error checking existing certificates: ${Y}`,w.verbose),null}}function HY(w,$){let Y=z8(w);E("ssl",`Primary domain: ${Y}`,$);let A=z2(w),X=G0(Z1(),".stacks","ssl");if(typeof w.https==="object"){let J=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:w.https.caCertPath||A.caCertPath,certPath:w.https.certPath||A.certPath,keyPath:w.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:w.https.commonName||Y,organizationName:w.https.organizationName||"Local Development",countryName:w.https.countryName||"US",stateName:w.https.stateName||"California",localityName:w.https.localityName||"Playa Vista",validityDays:w.https.validityDays||825,verbose:$||!1,subjectAltNames:Array.from(U2(w)).map((j)=>({type:2,value:j}))};if(eW(w.https.rootCA))U.rootCA=w.https.rootCA;return U}return{domain:Y,hostCertCN:Y,basePath:X,...A,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:Y,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:$||!1,subjectAltNames:Array.from(U2(w)).map((J)=>({type:2,value:J}))}}async function B2(w,$){let Y=z2({to:w,verbose:$}),A=[Y.caCertPath,Y.certPath,Y.keyPath];E("certificates","Attempting to clean up relating certificates",$),await Promise.all(A.map((X)=>$j(X,$)))}async function G2(w,$){try{if(E("ssl",`Checking if certificate is trusted: ${w}`,$?.verbose),H$.platform==="darwin"){if($?.serverName)return Jj(w,$.serverName,{verbose:$?.verbose});return K8(w,{verbose:$?.verbose})}else if(H$.platform==="win32")try{let Y=KW(w)||"";if(!Y)return E("ssl","Could not extract certificate subject",$?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(Wj(A).toString().includes(Y))return E("ssl","Certificate found in trusted root store",$?.verbose),!0;return E("ssl","Certificate not found in trusted root store",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Windows: ${Y}`,$?.verbose),!1}else if(H$.platform==="linux")try{let Y=k$(w);if(!Y)return E("ssl","Could not extract certificate fingerprint",$?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await B0.readdir(X)}catch{continue}for(let U of J){let j=k$(W2.join(X,U));if(j&&j===Y)return E("ssl",`Certificate fingerprint found in ${X}`,$?.verbose),!0}}return E("ssl","Certificate not found in system trust stores",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Linux: ${Y}`,$?.verbose),!1}return E("ssl",`Platform ${H$.platform} not supported for certificate trust check`,$?.verbose),!1}catch(Y){return E("ssl",`Error checking if certificate is trusted: ${Y}`,$?.verbose),!1}}var R$=null,Qj,Oq="rpx-root-ca.crt",_q="rpx-root-ca.key";var zj=s(()=>{DX();_$();iA();Uj();z0();Uj();xX();xX();Qj=G0(Z1(),".stacks","ssl","rpx.localhost.crt")});function xq(w){return{enabled:w?.enabled??!1,path:w?.path??"/",interval:w?.interval??1e4,timeout:w?.timeout??2000,healthyThreshold:w?.healthyThreshold??2,unhealthyThreshold:w?.unhealthyThreshold??3}}function kq(w){return(Array.isArray(w)?w:[w]).map((Y)=>{let A=typeof Y==="string"?{url:Y}:Y;return{url:A.url,weight:A.weight&&A.weight>0?A.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function E2(w){return(Array.isArray(w)?w:[w]).map((Y)=>typeof Y==="string"?Y:Y.url)}function i$(w){if(!w)return"localhost:5173";let $=Array.isArray(w)?w[0]:w;if(!$)return"localhost:5173";return typeof $==="string"?$:$.url}function RY(w,$){return{upstreams:kq(w),strategy:$?.strategy??"round-robin",healthCheck:xq($?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function Zq(w){let $=w.upstreams.filter((Y)=>Y.healthy);if($.length===0&&w.upstreams.length===1)return w.upstreams;return $}function Pq(w,$){let Y=w.cursor%$.length;return w.cursor=(w.cursor+1)%$.length,$[Y]}function iq(w,$){if(w.wrrCurrentWeights.length!==$.length)w.wrrCurrentWeights=$.map(()=>0);let Y=$.reduce((X,J)=>X+J.weight,0),A=0;for(let X=0;X<$.length;X++)if(w.wrrCurrentWeights[X]+=$[X].weight,w.wrrCurrentWeights[X]>w.wrrCurrentWeights[A])A=X;return w.wrrCurrentWeights[A]-=Y,$[A]}function bq(w){let $=w[0];for(let Y=1;Y<w.length;Y++)if(w[Y].activeConnections<$.activeConnections)$=w[Y];return $}function K2(w){let $=Zq(w);if($.length===0)return;if($.length===1)return $[0];switch(w.strategy){case"weighted-round-robin":return iq(w,$);case"least-connections":return bq($);case"round-robin":default:return Pq(w,$)}}function F8(w,$){if($.consecutiveFailures=0,$.consecutiveSuccesses+=1,!$.healthy&&$.consecutiveSuccesses>=w.healthCheck.healthyThreshold)$.healthy=!0}function MY(w,$){if($.consecutiveSuccesses=0,$.consecutiveFailures+=1,$.healthy&&$.consecutiveFailures>=w.healthCheck.unhealthyThreshold)$.healthy=!1}function uq(w){let $=w.lastIndexOf(":");if($===-1)return{hostname:w,port:80};let Y=Number(w.slice($+1));return{hostname:w.slice(0,$),port:Number.isFinite(Y)?Y:80}}async function cq(w,$){let{hostname:Y,port:A}=uq($.url),X=new AbortController,J=setTimeout(()=>X.abort(),w.healthCheck.timeout);try{(await fetch(`http://${Y}:${A}${w.healthCheck.path}`,{signal:X.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),F8(w,$)}catch{MY(w,$)}finally{clearTimeout(J)}}function yY(w){if(!w.healthCheck.enabled||w.healthCheckTimer||w.upstreams.length<2)return;let $=setInterval(()=>{for(let Y of w.upstreams)cq(w,Y)},w.healthCheck.interval);$.unref?.(),w.healthCheckTimer=$}function P1(w){if(w.healthCheckTimer)clearInterval(w.healthCheckTimer),w.healthCheckTimer=null}import{createHash as T2,timingSafeEqual as F2}from"node:crypto";import{readFileSync as vq}from"node:fs";function IY(w,$){let Y=Buffer.from(w,"utf8"),A=Buffer.from($,"utf8");if(Y.length!==A.length)return F2(Y,Y),!1;return F2(Y,A)}function gq(w,$){let Y=(B)=>T2("md5").update(B).digest(),A=Buffer.from(w,"utf8"),X=Buffer.from($,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let B=A.length;B>0;B-=16)U.push(J.subarray(0,Math.min(B,16)));for(let B=A.length;B>0;B>>=1)U.push(B&1?Buffer.from([0]):A.subarray(0,1));let j=Y(Buffer.concat(U));for(let B=0;B<1000;B++){let G=[];if(G.push(B&1?A:j.subarray(0,16)),B%3)G.push(X);if(B%7)G.push(A);G.push(B&1?j.subarray(0,16):A),j=Y(Buffer.concat(G))}let W="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Q=(B,G)=>{let T="",K=B;for(let F=0;F<G;F++)T+=W[K&63],K>>=6;return T},f=j,z="";return z+=Q(f[0]<<16|f[6]<<8|f[12],4),z+=Q(f[1]<<16|f[7]<<8|f[13],4),z+=Q(f[2]<<16|f[8]<<8|f[14],4),z+=Q(f[3]<<16|f[9]<<8|f[15],4),z+=Q(f[4]<<16|f[10]<<8|f[5],4),z+=Q(f[11],2),`$apr1$${$}$${z}`}function dq(w,$){if(/^\$2[aby]?\$/.test($))try{return Bun.password.verifySync(w,$)}catch{return!1}if($.startsWith("$apr1$")){let A=$.split("$")[2]??"";return IY(gq(w,A),$)}if($.startsWith("{SHA}")){let Y=T2("sha1").update(w,"utf8").digest("base64");return IY(`{SHA}${Y}`,$)}return IY(w,$)}function nq(w){let $=new Map;for(let Y of w.split(`
220
+ `)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;$.set(A.slice(0,X),A.slice(X+1))}return $}function CY(w){if(!w)return;let $=(w.realm??"").trim()||"Restricted",Y=[];if(w.username)Y.push({username:w.username,password:w.password??""});for(let J of w.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if(w.htpasswdFile)try{A=nq(vq(w.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:$,verify:(J,U)=>{let j=!1;for(let W of Y)if(IY(J,W.username)&&IY(U,W.password))j=!0;if(A){let W=A.get(J);if(W&&dq(U,W))j=!0}return j}}}function N2(w,$,Y){if($.startsWith(mq))return;let A=w.headers.get("authorization")??"",X=A.indexOf(" "),J=X===-1?A:A.slice(0,X),U=X===-1?"":A.slice(X+1).trim();if(J.toLowerCase()==="basic"&&U){let W="";try{W=Buffer.from(U,"base64").toString("utf8")}catch{W=""}let Q=W.indexOf(":");if(Q>=0&&Y.verify(W.slice(0,Q),W.slice(Q+1)))return}let j=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${j}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var mq="/.well-known/acme-challenge/";var T8=()=>{};function rq(w){return pq.has(w.toUpperCase())}function tq(){let w=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(w)&&w>0?w:30000}function aq(w){let $=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite($)&&$>0?$:w*8}function sq(){let w=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(w)&&w>0?w:0}function oq(){let w=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(w)&&w>0?w:0}function eq(){let w=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(w)&&w>0?w:256}class y2{socket=null;buf=new Uint8Array(wH);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(w){let $=this.socket,Y=$.write(w);while(Y<w.length){if(this.closed)throw N8;await new Promise((A)=>{this.drainWaiter=A}),Y+=$.write(w.subarray(Y))}}wakeDrain(){let w=this.drainWaiter;if(w)this.drainWaiter=null,w()}push(w){if(this.bodyQueue){let $=w.length<=this.bodyRemaining?w.length:this.bodyRemaining;if($>0)this.bodyQueue.push(w.slice(0,$)),this.queuedBytes+=$;if(this.bodyRemaining-=$,$<w.length)this.appendToBuf(w.subarray($));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(w),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()>$H)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=YH)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(w){let $=this.len+w.length;if($>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,$));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set(w,this.len),this.len=$}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let w=this.waiter;if(w)this.waiter=null,w()}waitForData(w){if(this.len>w||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}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 I2{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=tq();maxWaiters;checkoutIdleMs=sq();inUse=new Set;constructor(w,$,Y,A=""){this.host=w;this.port=$;this.maxTotal=Y;this.key=A;this.maxWaiters=aq(Y)}trackCheckout(w){if(w.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(w),this.ensureSweeper()}dial(){let w=new y2;return lq({hostname:this.host,port:this.port,socket:{data:($,Y)=>w.push(Y),drain:()=>w.wakeDrain(),close:()=>w.markClosed(),end:()=>w.markClosed(),error:()=>w.markClosed(),connectError:()=>w.markClosed(),timeout:()=>w.markTimedOut()}}).then(($)=>{let Y=$;Y.setNoDelay?.(!0);let A=oq();if(A>0)Y.timeout?.(A);return w.socket=$,w})}acquireIdleSync(){while(this.idle.length){let w=this.idle.pop();if(!w.closed)return w.socket?.ref(),w.pos=0,w.len=0,this.trackCheckout(w),w;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw b$;let w=await this.waitForSlot();if(w===b$)throw b$;if(w)return w.pos=0,w.len=0,this.trackCheckout(w),w}this.open++;try{let w=await this.dial();return this.trackCheckout(w),w}catch(w){throw this.open--,this.wakeWaiter(),w}}waitForSlot(){return new Promise((w)=>{let $=!1,Y=(J)=>{if($)return;$=!0,clearTimeout(X),w(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(b$)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release(w){if(this.inUse.delete(w),w.closed){this.open--,this.wakeWaiter();return}w.clearStreaming(),w.compact(),w.fresh=!1;let $=this.waiters.shift();if($){w.socket?.ref(),this.trackCheckout(w),$(w);return}w.idleSince=Date.now(),w.socket?.unref(),this.idle.push(w),this.ensureSweeper()}destroy(w){this.inUse.delete(w),w.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let w=this.waiters.shift();if(w)w(null)}ensureSweeper(){if(this.sweeper)return;let w=this.checkoutIdleMs>0?Math.min(Bj,this.checkoutIdleMs):Bj;this.sweeper=setInterval(()=>this.sweep(),w),this.sweeper.unref?.()}sweep(){let w=Date.now(),$=w-Bj;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=$)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=w-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){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&q8.get(this.key)===this)q8.delete(this.key)}}}function WH(w,$){let Y=q8.get(w);if(!Y){let A=w.lastIndexOf(":"),X=A===-1?w:w.slice(0,A),J=A===-1?80:Number(w.slice(A+1));Y=new I2(X,J,$,w),q8.set(w,Y)}return Y}function q2(w,$,Y){for(let A=Y+3;A<$;A++)if(w[A]===10&&w[A-1]===13&&w[A-2]===10&&w[A-3]===13)return A-3;return-1}function jH(w,$,Y){let A=M2.decode(w.subarray($,Y)),X=A.indexOf(`\r
221
221
  `),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),j=Number.parseInt(J.slice(U+1,U+5),10),W=J.startsWith("HTTP/1.0"),Q=[],f=-1,z=!1,B=W,G=!1,T=!1,K=X===-1?A.length:X+2;while(K<A.length){let F=A.indexOf(`\r
222
- `,K);if(F===-1)F=A.length;let N=A.slice(K,F);if(K=F+2,N==="")continue;let R=N.indexOf(":");if(R===-1)continue;let L=N.slice(0,R),V=N.slice(R+1).trim(),q=L.charCodeAt(0)|32;if(q===99||q===116||q===107){let M=L.toLowerCase();if(M==="content-length"){let C=/^\d+$/.test(V)?Number(V):Number.NaN;if(!Number.isSafeInteger(C)||f>=0&&f!==C)T=!0;else f=C;continue}if(M==="transfer-encoding"){if(V.toLowerCase().includes("chunked"))z=!0;continue}if(M==="connection"){let C=V.toLowerCase();if(C.includes("close"))B=!0;if(C.includes("keep-alive"))G=!0;continue}if(M==="keep-alive")continue}Q.push([L,V])}if(W&&G)B=!1;if(z&&f>=0)f=-1;return{status:j,headerEnd:Y,headers:Q,contentLength:f,chunked:z,closeConn:B,malformed:T}}function WH(w,$){return $||w===204||w===304}async function y2(w){let{hostPort:$,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:j}=w,W=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw LY;let Q=null;if(j){let G=X.get("content-length"),T=G?Number.parseInt(G,10):Number.NaN;if(Number.isNaN(T)||T>N2)throw LY;if(Q=await EH(j),Q===null)throw LY}let f=GH(Y,A,X,$,J,U,Q),z=f;if(Q&&Q.length)z=new Uint8Array(f.length+Q.length),z.set(f),z.set(Q,f.length);let B=JH($,w.maxPerHost??sq());for(let G=0;;G++){if(G>0)await new Promise((K)=>{setTimeout(K,G)});let T;try{T=B.acquireIdleSync()??await B.acquireOrDial()}catch(K){if(K!==c$&&G<4)continue;throw K}try{let K=T.socket.write(z);if(K<z.length)await T.writeAll(z.subarray(K));return await QH(B,T,W,w.signal)}catch(K){let F=K===T8&&G<4&&(T.fresh||lq(Y));if(B.destroy(T),F)continue;if(K===T8)throw Error("upstream closed connection");throw K}}}async function jH(w){let $=T2(w.buf,w.len,w.pos);while($===-1){if(w.closed){if(w.timedOut)throw Bj;if(w.len===w.pos)throw T8;throw Error("upstream closed mid-header")}if(w.len-w.pos>q2)throw Error("upstream header block too large");await w.waitForData(w.len),$=T2(w.buf,w.len,w.pos)}return $}async function QH(w,$,Y,A){let X;for(;;){let U=await jH($);if(X=UH($.buf,$.pos,U),$.pos=U+4,X.status>=100&&X.status<200)continue;break}if(X.malformed)throw w.destroy($),Error("upstream sent malformed response framing");let J=X.headers;if(WH(X.status,Y))return I2(w,$,X.closeConn),new Response(null,{status:X.status,headers:J});if(X.chunked)return new Response(BH(w,$,X.closeConn,A),{status:X.status,headers:J});if(X.contentLength>=0){if($.len-$.pos>=X.contentLength){let j=$.pos+X.contentLength,W=$.len>j,Q=null;if(X.contentLength>=$H)Q=$.buf.subarray($.pos,j),$.buf=new Uint8Array(YH);else if(X.contentLength>0)Q=$.buf.slice($.pos,j);if($.pos=0,$.len=0,X.closeConn||W)w.destroy($);else w.release($);return new Response(Q,{status:X.status,headers:J})}return new Response(fH(w,$,X.contentLength,X.closeConn),{status:X.status,headers:J})}return new Response(zH($),{status:X.status,headers:J})}function I2(w,$,Y){if(Y||$.pos!==$.len)w.destroy($);else w.release($)}function fH(w,$,Y,A){let X=$.len-$.pos,J=X>0?$.buf.slice($.pos,$.len):null;$.pos=0,$.len=0,$.bodyQueue=[],$.bodyRemaining=Y-X,$.queuedBytes=0,$.streamingBody=!0;let U=(j)=>{if($.bodyQueue=null,A||$.len>0)w.destroy($);else w.release($);j.close()};return new ReadableStream({start(j){if(J)j.enqueue(J);if($.bodyRemaining===0&&$.bodyQueue.length===0)U(j)},async pull(j){for(;;){let W=$.bodyQueue;if(W&&W.length>0){let Q=W.shift();if($.queuedBytes-=Q.length,$.resumeIfDrained(),j.enqueue(Q),$.bodyRemaining===0&&W.length===0)U(j);return}if($.bodyRemaining===0){if($.bodyQueue)U(j);return}if($.closed){$.bodyQueue=null,w.destroy($),j.error(Error("upstream closed mid-body"));return}await $.waitForBody()}},cancel(){$.bodyQueue=null,w.destroy($)}})}function zH(w){return w.streamingBody=!0,new ReadableStream({async pull($){for(;;){if(w.len>w.pos){$.enqueue(w.buf.slice(w.pos,w.len)),w.pos=w.len,w.resumeIfDrained();return}if(w.closed){w.destroy(),$.close();return}await w.waitForData(w.len)}},cancel(){w.destroy()}})}function BH(w,$,Y,A){$.streamingBody=!0;let X=0,J=!1,U=!1,j,W=()=>A?.removeEventListener("abort",Q),Q=()=>{if(U)return;U=!0,w.destroy($);try{j?.close()}catch{}};async function f(z=!1){for(;;){for(let B=$.pos;B+1<$.len;B++)if($.buf[B]===13&&$.buf[B+1]===10){let G=H2.decode($.buf.subarray($.pos,B));return $.pos=B+2,G}if($.closed){if(z&&$.pos===$.len)return null;throw Error("upstream closed mid-chunk-header")}if($.len-$.pos>q2)throw Error("upstream chunk header too large");await $.waitForData($.len)}}return new ReadableStream({start(z){if(j=z,A?.aborted)Q();else A?.addEventListener("abort",Q,{once:!0})},async pull(z){try{for(;;){if(X>0){if($.len===$.pos){if($.closed){w.destroy($),z.error(Error("upstream closed mid-chunk"));return}await $.waitForData($.len);continue}let K=Math.min(X,$.len-$.pos);if(z.enqueue($.buf.slice($.pos,$.pos+K)),$.pos+=K,X-=K,$.resumeIfDrained(),X===0)J=!0;return}if(J)await f(),J=!1;let B=await f(!0);if(B===null){w.destroy($),W(),z.close();return}let G=B.indexOf(";"),T=Number.parseInt(G===-1?B:B.slice(0,G),16);if(!Number.isInteger(T)||T<0){w.destroy($),z.error(Error("upstream sent malformed chunk size"));return}if(T===0){for(;;)if(await f()==="")break;I2(w,$,Y),W(),z.close();return}X=T}}catch(B){if(w.destroy($),W(),!U)z.error(B)}},cancel(){U=!0,W(),w.destroy($)}})}function GH(w,$,Y,A,X,J,U){let j=`${w} ${$} HTTP/1.1\r
222
+ `,K);if(F===-1)F=A.length;let N=A.slice(K,F);if(K=F+2,N==="")continue;let R=N.indexOf(":");if(R===-1)continue;let V=N.slice(0,R),L=N.slice(R+1).trim(),q=V.charCodeAt(0)|32;if(q===99||q===116||q===107){let C=V.toLowerCase();if(C==="content-length"){let M=/^\d+$/.test(L)?Number(L):Number.NaN;if(!Number.isSafeInteger(M)||f>=0&&f!==M)T=!0;else f=M;continue}if(C==="transfer-encoding"){if(L.toLowerCase().includes("chunked"))z=!0;continue}if(C==="connection"){let M=L.toLowerCase();if(M.includes("close"))B=!0;if(M.includes("keep-alive"))G=!0;continue}if(C==="keep-alive")continue}Q.push([V,L])}if(W&&G)B=!1;if(z&&f>=0)f=-1;return{status:j,headerEnd:Y,headers:Q,contentLength:f,chunked:z,closeConn:B,malformed:T}}function QH(w,$){return $||w===204||w===304}async function C2(w){let{hostPort:$,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:j}=w,W=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw VY;let Q=null;if(j){let G=X.get("content-length"),T=G?Number.parseInt(G,10):Number.NaN;if(Number.isNaN(T)||T>H2)throw VY;if(Q=await FH(j),Q===null)throw VY}let f=KH(Y,A,X,$,J,U,Q),z=f;if(Q&&Q.length)z=new Uint8Array(f.length+Q.length),z.set(f),z.set(Q,f.length);let B=WH($,w.maxPerHost??eq());for(let G=0;;G++){if(G>0)await new Promise((K)=>{setTimeout(K,G)});let T;try{T=B.acquireIdleSync()??await B.acquireOrDial()}catch(K){if(K!==b$&&G<4)continue;throw K}try{let K=T.socket.write(z);if(K<z.length)await T.writeAll(z.subarray(K));return await zH(B,T,W,w.signal)}catch(K){let F=K===N8&&G<4&&(T.fresh||rq(Y));if(B.destroy(T),F)continue;if(K===N8)throw Error("upstream closed connection");throw K}}}async function fH(w){let $=q2(w.buf,w.len,w.pos);while($===-1){if(w.closed){if(w.timedOut)throw Gj;if(w.len===w.pos)throw N8;throw Error("upstream closed mid-header")}if(w.len-w.pos>R2)throw Error("upstream header block too large");await w.waitForData(w.len),$=q2(w.buf,w.len,w.pos)}return $}async function zH(w,$,Y,A){let X;for(;;){let U=await fH($);if(X=jH($.buf,$.pos,U),$.pos=U+4,X.status>=100&&X.status<200)continue;break}if(X.malformed)throw w.destroy($),Error("upstream sent malformed response framing");let J=X.headers;if(QH(X.status,Y))return V2(w,$,X.closeConn),new Response(null,{status:X.status,headers:J});if(X.chunked)return new Response(EH(w,$,X.closeConn,A),{status:X.status,headers:J});if(X.contentLength>=0){if($.len-$.pos>=X.contentLength){let j=$.pos+X.contentLength,W=$.len>j,Q=null;if(X.contentLength>=AH)Q=$.buf.subarray($.pos,j),$.buf=new Uint8Array(XH);else if(X.contentLength>0)Q=$.buf.slice($.pos,j);if($.pos=0,$.len=0,X.closeConn||W)w.destroy($);else w.release($);return new Response(Q,{status:X.status,headers:J})}return new Response(BH(w,$,X.contentLength,X.closeConn),{status:X.status,headers:J})}return new Response(GH($),{status:X.status,headers:J})}function V2(w,$,Y){if(Y||$.pos!==$.len)w.destroy($);else w.release($)}function BH(w,$,Y,A){let X=$.len-$.pos,J=X>0?$.buf.slice($.pos,$.len):null;$.pos=0,$.len=0,$.bodyQueue=[],$.bodyRemaining=Y-X,$.queuedBytes=0,$.streamingBody=!0;let U=(j)=>{if($.bodyQueue=null,A||$.len>0)w.destroy($);else w.release($);j.close()};return new ReadableStream({start(j){if(J)j.enqueue(J);if($.bodyRemaining===0&&$.bodyQueue.length===0)U(j)},async pull(j){for(;;){let W=$.bodyQueue;if(W&&W.length>0){let Q=W.shift();if($.queuedBytes-=Q.length,$.resumeIfDrained(),j.enqueue(Q),$.bodyRemaining===0&&W.length===0)U(j);return}if($.bodyRemaining===0){if($.bodyQueue)U(j);return}if($.closed){$.bodyQueue=null,w.destroy($),j.error(Error("upstream closed mid-body"));return}await $.waitForBody()}},cancel(){$.bodyQueue=null,w.destroy($)}})}function GH(w){return w.streamingBody=!0,new ReadableStream({async pull($){for(;;){if(w.len>w.pos){$.enqueue(w.buf.slice(w.pos,w.len)),w.pos=w.len,w.resumeIfDrained();return}if(w.closed){w.destroy(),$.close();return}await w.waitForData(w.len)}},cancel(){w.destroy()}})}function EH(w,$,Y,A){$.streamingBody=!0;let X=0,J=!1,U=!1,j,W=()=>A?.removeEventListener("abort",Q),Q=()=>{if(U)return;U=!0,w.destroy($);try{j?.close()}catch{}};async function f(z=!1){for(;;){for(let B=$.pos;B+1<$.len;B++)if($.buf[B]===13&&$.buf[B+1]===10){let G=M2.decode($.buf.subarray($.pos,B));return $.pos=B+2,G}if($.closed){if(z&&$.pos===$.len)return null;throw Error("upstream closed mid-chunk-header")}if($.len-$.pos>R2)throw Error("upstream chunk header too large");await $.waitForData($.len)}}return new ReadableStream({start(z){if(j=z,A?.aborted)Q();else A?.addEventListener("abort",Q,{once:!0})},async pull(z){try{for(;;){if(X>0){if($.len===$.pos){if($.closed){w.destroy($),z.error(Error("upstream closed mid-chunk"));return}await $.waitForData($.len);continue}let K=Math.min(X,$.len-$.pos);if(z.enqueue($.buf.slice($.pos,$.pos+K)),$.pos+=K,X-=K,$.resumeIfDrained(),X===0)J=!0;return}if(J)await f(),J=!1;let B=await f(!0);if(B===null){w.destroy($),W(),z.close();return}let G=B.indexOf(";"),T=Number.parseInt(G===-1?B:B.slice(0,G),16);if(!Number.isInteger(T)||T<0){w.destroy($),z.error(Error("upstream sent malformed chunk size"));return}if(T===0){for(;;)if(await f()==="")break;V2(w,$,Y),W(),z.close();return}X=T}}catch(B){if(w.destroy($),W(),!U)z.error(B)}},cancel(){U=!0,W(),w.destroy($)}})}function KH(w,$,Y,A,X,J,U){let j=`${w} ${$} HTTP/1.1\r
223
223
  host: ${A}\r
224
224
  x-forwarded-for: 127.0.0.1\r
225
225
  x-forwarded-proto: https\r
226
226
  x-forwarded-host: ${X}\r
227
227
  `;if(J!==void 0)j+=`origin: ${J}\r
228
- `;let W=!1;for(let[Q,f]of Y){let z=Q.toLowerCase();if(XH.has(z))continue;if(J!==void 0&&z==="origin")continue;if(z==="content-length")W=!0;j+=`${Q}: ${f}\r
228
+ `;let W=!1;for(let[Q,f]of Y){let z=Q.toLowerCase();if(UH.has(z))continue;if(J!==void 0&&z==="origin")continue;if(z==="content-length")W=!0;j+=`${Q}: ${f}\r
229
229
  `}if(j+=`connection: keep-alive\r
230
230
  `,U&&!W)j+=`content-length: ${U.length}\r
231
231
  `;return j+=`\r
232
- `,AH.encode(j)}async function EH(w){let $=w.getReader(),Y=[],A=0;for(;;){let{done:U,value:j}=await $.read();if(U)break;if(j){if(A+=j.length,A>N2)return $.cancel().catch(()=>{}),null;Y.push(j)}}if(Y.length===1)return Y[0];let X=new Uint8Array(A),J=0;for(let U of Y)X.set(U,J),J+=U.length;return X}var dq,LY,T8,nq,Bj,c$,N2=1048576,zj=30000,oq=16384,q2=262144,eq=2097152,wH=524288,$H=8192,YH=4096,AH,H2,XH,N8;var C2=a(()=>{({connect:dq}=Bun),LY=Symbol("rpx.pool.fallback"),T8=Symbol("rpx.pool.stale"),nq=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);Bj=Symbol("rpx.pool.timeout"),c$=Symbol("rpx.pool.busy");AH=new TextEncoder,H2=new TextDecoder,XH=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);N8=new Map});function V2(w){let $=typeof w==="string"?{to:w}:w,Y=($.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:$.status??301,preservePath:$.preservePath??!0}}function L2(w,$,Y){if(!w.preservePath)return w.to||"/";let A=`${$}${Y}`;return A==="/"?`${w.to}/`:`${w.to}${A}`}import*as zw from"node:path";function q8(w,$){if(typeof w==="string")return{dir:w,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:$};return{dir:w.dir,spa:w.spa??!1,pathRewriteStyle:w.pathRewriteStyle??"directory",maxAge:w.maxAge??0,cleanUrls:$}}function FH(w){let $=zw.extname(w).toLowerCase();return KH[$]??"application/octet-stream"}function TH(w){let $;try{$=decodeURIComponent(w)}catch{return null}if($.includes("\x00")||$.includes("\\"))return null;let Y=zw.posix.normalize(`/${$}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function NH(w,$){let Y=TH(w);if(Y===null)return null;let A=zw.posix.extname(Y);if($.cleanUrls&&A===".html"){let X=w.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:zw.join($.dir,Y),redirectTo:X||"/"}}if(Y===""||w.endsWith("/"))return{filePath:zw.join($.dir,Y,"index.html")};if(A!=="")return{filePath:zw.join($.dir,Y)};if($.pathRewriteStyle==="flat")return{filePath:zw.join($.dir,`${Y}.html`)};return{filePath:zw.join($.dir,Y,"index.html")}}async function S2(w,$){let Y=NH(w,$);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=$.maxAge>0?`public, max-age=${$.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":FH(Y.filePath),"Cache-Control":A}});if($.spa){let J=zw.join($.dir,"index.html"),U=Bun.file(J);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 KH;var H8=a(()=>{KH={".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 qH(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function RH(w){let $=w.headers.get("host")||"",Y=$.indexOf(":");return Y===-1?$:$.slice(0,Y)}function _2(w,$){if(!$||$==="/")return w;if(w===$)return"/";if(w.startsWith(`${$}/`)){let Y=w.slice($.length);return Y===""?"/":Y}return w}function h2(w){if(w.upstreamPool)return G2(w.upstreamPool);if(w.sourceHost)return{url:w.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function O2(w,$,Y,A){let X=Y?.url??$.sourceHost??"",U=$.stripBasePathPrefix??!1?_2(w,$.basePath):w,j=eW(U,$.pathRewrites);if(j)X=j.targetHost,U=j.targetPath,E("request",`Path rewrite: ${w} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function MH(w){let $=w.indexOf("://"),Y=$===-1?w.indexOf("/"):w.indexOf("/",$+3);if(Y===-1)return{pathname:"/",search:""};let A=w.indexOf("?",Y);if(A===-1)return{pathname:w.slice(Y),search:""};return{pathname:w.slice(Y,A),search:w.slice(A)}}function SY(w,$,Y){let A=async(X,J)=>{let{pathname:U,search:j}=MH(X.url),W=RH(X),Q=w(W,U);if(!Q&&Y){let F=await Y(W,U,X);if(F instanceof Response)return F;if(F&&F.retry)Q=w(W,U)}if(!Q)return E("request",`No route found for host: ${W}`,$),new Response(`No proxy configured for ${W}`,{status:404});if(Q.auth){let F=F2(X,U,Q.auth);if(F)return E("request",`401 challenge for ${W}${U}`,$),F}if(Q.redirect){let F=L2(Q.redirect,U,j);return E("request",`${Q.redirect.status} redirect ${W}${U} → ${F}`,$),new Response(null,{status:Q.redirect.status,headers:{location:F}})}if(Q.static){let N=Q.stripBasePathPrefix??!0?_2(U,Q.basePath):U;return S2(N,Q.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let F=h2(Q);if(!J||!F)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:N,targetPath:R}=O2(U,Q,F,$),L=`ws://${N}${R}${j}`,V={};for(let[C,O]of X.headers)if(!HH.has(C.toLowerCase())&&C.toLowerCase()!=="host")V[C]=O;V.host=N,V["x-forwarded-for"]="127.0.0.1",V["x-forwarded-proto"]="https",V["x-forwarded-host"]=W;let q={targetUrl:L,forwardHeaders:V};if(J.upgrade(X,{data:q})){E("ws",`upgraded ${W}${R} → ${L}`,$);return}return new Response("WebSocket upgrade failed",{status:400})}let f=h2(Q);if(!f)return new Response(`No upstream configured for ${W}`,{status:502});if(Q.cleanUrls&&U.endsWith(".html")){let F=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:F}})}let{targetHost:z,targetPath:B}=O2(U,Q,f,$),G=Q.changeOrigin?`http://${z}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",K=Q.upstreamPool;if(K)f.activeConnections++;try{let F=await y2({hostPort:z,method:X.method,path:`${B}${j}`,reqHeaders:X.headers,forwardedHost:W,originOverride:G,body:X.body,signal:X.signal});if(K)K8(K,f);return F}catch(F){if(F===Bj){if(E("request",`Upstream timeout for ${W}`,$),K)yY(K,f);return new Response("Gateway Timeout",{status:504})}if(F===c$)return E("request",`Upstream pool saturated for ${W}`,$),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(F===LY||!T)try{let N=new Headers(X.headers);if(N.set("host",z),N.set("x-forwarded-for","127.0.0.1"),N.set("x-forwarded-proto","https"),N.set("x-forwarded-host",W),G!==void 0)N.set("origin",G);let R=await fetch(`http://${z}${B}${j}`,{method:X.method,headers:N,body:X.body,redirect:"manual"});if(K)K8(K,f);return R}catch(N){if(E("request",`Proxy error for ${W}: ${N}`,$),K)yY(K,f);return new Response(`Proxy Error: ${N}`,{status:502})}if(E("request",`Proxy error for ${W}: ${F}`,$),K)yY(K,f);return new Response(`Proxy Error: ${F}`,{status:502})}finally{if(K)f.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return E("request",`Unhandled proxy handler error: ${U}`,$),new Response("Bad Gateway",{status:502})}}}function hY(w){let $=new WeakMap,Y=qH();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){E("ws",`failed to open upstream ${X}: ${W}`,w),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let j={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};$.set(A,j),U.addEventListener("open",()=>{j.upstreamOpen=!0;for(let W of j.pending)U.send(W);j.pending=[],j.pendingBytes=0}),U.addEventListener("message",(W)=>{A.send(W.data)}),U.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),U.addEventListener("error",()=>{E("ws",`upstream error for ${X}`,w);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=$.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let j=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+j>Y){E("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,w);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}$.delete(A);return}J.pending.push(U),J.pendingBytes+=j},close(A,X,J){let U=$.get(A);if(!U)return;$.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var HH;var Gj=a(()=>{F8();C2();H8();z0();HH=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});import*as x2 from"node:fs";import*as k2 from"node:path";function R8(w,$){if(!w||!$.startsWith(D2))return null;let Y=$.slice(D2.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return x2.readFileSync(k2.join(w,Y),"utf8")}catch{return null}}var D2="/.well-known/acme-challenge/";var Ej=()=>{};function X$(w){if(!w||w==="/")return"/";let $=w.trim();if(!$.startsWith("/"))$=`/${$}`;return $=$.replace(/\/+$/,""),$===""?"/":$}function yH(w,$){if($==="/")return!0;if(w===$)return!0;return w.startsWith(`${$}/`)}function OY(w){let $=new Map;for(let A of w){let X=X$(A.path),J=$.get(A.host);if(!J)J=new Map,$.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of $){let J=[];for(let[U,j]of X)J.push({path:U,route:j});J.sort((U,j)=>j.path.length-U.path.length),Y.set(A,J)}return Y}function Kj(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!j1(J))continue;if($Y($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}function _Y(w,$,Y){let A=Kj(w,$);if(!A)return;for(let X of A)if(yH(Y,X.path))return X.route;return}var M8=()=>{};import*as DY from"node:fs/promises";import*as Fj from"node:path";function v$(w){if(Array.isArray(w))return w.map(($)=>({...$,lowMemoryMode:!0}));return{...w,lowMemoryMode:!0}}function IH(w){if(!w.endsWith(".crt"))return null;let $=w.slice(0,-4);if($.length===0)return null;if($.startsWith("_wildcard."))return`*.${$.slice(10)}`;return $}async function CH(w,$,Y,A){try{let[X,J]=await Promise.all([DY.readFile($,"utf8"),DY.readFile(Y,"utf8")]);return{serverName:w,cert:X,key:J}}catch(X){return E("sni",`skipping ${w}: ${X.message}`,A),null}}async function xY(w,$){let Y=new Map;if(w.certsDir){let X=[];try{X=await DY.readdir(w.certsDir)}catch(J){E("sni",`certsDir read failed (${w.certsDir}): ${J.message}`,$)}for(let J of X){let U=IH(J);if(!U)continue;let j=J.slice(0,-4);Y.set(U,{certPath:Fj.join(w.certsDir,J),keyPath:Fj.join(w.certsDir,`${j}.key`)})}}if(w.domains)for(let[X,J]of Object.entries(w.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await CH(X,J.certPath,J.keyPath,$);if(U)A.push(U)}return A}var Tj=a(()=>{z0()});import*as yw from"node:fs/promises";import*as y8 from"node:path";function kY(w=process.env){let $=w.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if($==="restart"||$==="rebind")return $;return w.INVOCATION_ID?"restart":"rebind"}function SH(w,$){if(!$||$.length===0)return!1;return $.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return w===A||w.endsWith(`.${A}`)})}function P2(w){if(!w||w.length>253)return!1;if(w.includes("/")||w.includes(":")||w.includes(" "))return!1;if(w.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(w)}class u1{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(w){this.config=w.config,this.certsDir=w.certsDir,this.onCertAdded=w.onCertAdded,this.http01Store=w.http01Store??yX,this.issuer=w.issuer??tU,this.verbose=w.verbose??!1,this.negativeCacheMs=w.negativeCacheMs??LH;for(let $ of w.initial??[])this.certs.set($.serverName,$)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(w){return this.certs.has(w)}async isApproved(w){if(!P2(w))return!1;if(SH(w,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(w)}catch($){return E("on-demand",`ask(${w}) threw: ${$.message}`,this.verbose),!1}return!1}async ensureCert(w){if(!this.config.enabled)return!1;if(this.certs.has(w))return!0;if(!P2(w))return!1;let $=this.inFlight.get(w);if($)return $;let Y=this.negativeCache.get(w);if(Y!==void 0&&Date.now()<Y){if(await this.loadFromDisk(w))return this.negativeCache.delete(w),!0;return E("on-demand",`${w} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1}let A=this.issue(w).finally(()=>{this.inFlight.delete(w)});return this.inFlight.set(w,A),A}async issue(w){if(this.certs.has(w))return!0;if(await this.loadFromDisk(w))return!0;if(!await this.isApproved(w))return E("on-demand",`refused issuance for ${w} (not approved)`,this.verbose),this.cacheNegative(w),!1;try{E("on-demand",`issuing cert for ${w} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let $=await this.issuer({domains:[w],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey($.accountKeyPem),await this.persist(w,$.fullChainPem,$.keyPem);let Y={serverName:w,cert:$.fullChainPem,key:$.keyPem};return this.certs.set(w,Y),this.negativeCache.delete(w),E("on-demand",`issued + installed cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch($){return this.cacheNegative(w),E("on-demand",`issuance for ${w} failed: ${$.message}`,this.verbose),!1}}cacheNegative(w){if(this.negativeCache.size>=Z2){let $=Date.now();for(let[Y,A]of this.negativeCache)if(A<=$)this.negativeCache.delete(Y);if(this.negativeCache.size>=Z2){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set(w,Date.now()+this.negativeCacheMs)}async loadFromDisk(w){let{certPath:$,keyPath:Y}=this.pathsFor(w);try{let[A,X]=await Promise.all([yw.readFile($,"utf8"),yw.readFile(Y,"utf8")]),J={serverName:w,cert:A,key:X};return this.certs.set(w,J),E("on-demand",`adopted existing on-disk cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(w){return{certPath:y8.join(this.certsDir,`${w}.crt`),keyPath:y8.join(this.certsDir,`${w}.key`)}}async persist(w,$,Y){await yw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor(w);await Promise.all([yw.writeFile(A,$,"utf8"),yw.writeFile(X,Y,{encoding:"utf8",mode:384})])}get accountKeyPath(){return y8.join(this.certsDir,VH)}async loadAccountKey(){try{return await yw.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(w){if(!w||this.accountKeyPem===w)return;this.accountKeyPem=w,await yw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await yw.writeFile(this.accountKeyPath,w,{encoding:"utf8",mode:384}).catch(()=>{})}}var VH="acme-account.key",LH=60000,Z2=4096;var Nj=a(()=>{_X();z0()});import*as I8 from"node:net";function I$(w,$,Y){return E("port",`Checking if port ${w} is in use on ${$}`,Y),new Promise((A)=>{let X=I8.createServer(),J=setTimeout(()=>{E("port",`Checking port ${w} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")E("port",`Port ${w} is in use`,Y),A(!0);else E("port",`Error checking port ${w}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),E("port",`Port ${w} is available`,Y),X.close(),A(!1)});try{X.listen(w,$)}catch(U){clearTimeout(J),E("port",`Exception checking port ${w}: ${U}`,Y),A(!0)}})}async function qj(w,$,Y,A=50){E("port",`Finding available port starting from ${w} (max attempts: ${A})`,Y);let X=w,J=0;while(J<A){if(J++,!await I$(X,$,Y))return E("port",`Found available port: ${X} after ${J} attempts`,Y),X;E("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${A})`,Y),X++}throw Error(`Unable to find available port after ${A} attempts starting from ${w}`)}function i2(w,$,Y=5000,A){return E("port",`Testing connection to ${$}:${w}`,A),new Promise((X)=>{let J=I8.connect({host:$,port:w,timeout:Y});J.once("connect",()=>{E("port",`Successfully connected to ${$}:${w}`,A),J.end(),X(!0)}),J.once("timeout",()=>{E("port",`Connection to ${$}:${w} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{E("port",`Failed to connect to ${$}:${w}: ${U.message}`,A),J.destroy(),X(!1)})})}class C8{usedPorts=new Set;hostname;verbose;maxRetries;constructor(w="0.0.0.0",$,Y=50){this.hostname=w,this.verbose=$,this.maxRetries=Y}async getNextAvailablePort(w,$=!1){if(this.usedPorts.has(w))return this.findNextAvailablePort(w+1,$);if(await I$(w,this.hostname,this.verbose))return this.findNextAvailablePort(w+1,$);if($){if(!await i2(w,this.hostname,3000,this.verbose))return E("port",`Port ${w} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(w+1,$)}return this.usedPorts.add(w),w}async findNextAvailablePort(w,$=!1){let Y=await qj(w,this.hostname,this.verbose,this.maxRetries);if($){if(!await i2(Y,this.hostname,3000,this.verbose))if(Y<w+this.maxRetries)return this.findNextAvailablePort(Y+1,$);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort(w){E("port",`Releasing port ${w}`,this.verbose),this.usedPorts.delete(w)}}var SL;var Hj=a(()=>{z0();SL=new C8});import*as V8 from"node:fs";import*as p0 from"node:fs/promises";import{homedir as hH}from"node:os";import*as Rj from"node:path";import*as L8 from"node:process";function $w(){return Rj.join(hH(),".stacks","rpx","registry.d")}function C$(w){return typeof w==="string"&&w.length>0&&w.length<=128&&OH.test(w)}function Mj(w,$){if(!C$($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return Rj.join(w,`${$}.json`)}function Yw(w){if(!Number.isInteger(w)||w<=0)return!1;try{return L8.kill(w,0),!0}catch($){return $.code==="EPERM"}}function b2(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&C$($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function _H(w){await p0.mkdir(w,{recursive:!0})}async function c1(w,$=$w(),Y){if(!b2(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await _H($);let A=Mj($,w.id),X=`${A}.tmp.${L8.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),E("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function m$(w,$=$w(),Y){let A=Mj($,w);try{await p0.unlink(A),E("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function yj(w,$=$w(),Y){let A=Mj($,w);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!b2(J))return E("registry",`entry ${w} failed validation, removing`,Y),await p0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return E("registry",`entry ${w} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function Bw(w=$w(),$){let Y;try{Y=await p0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!C$(J))continue;let U=await yj(J,w,$);if(U)A.push(U)}return A}async function ZY(w=$w(),$){let Y=await Bw(w,$),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!Yw(X.pid))E("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,$),await m$(X.id,w,$).catch(()=>{}),A++}return A}function S8(w,$={}){let Y=$.dir??$w(),A=$.debounceMs??100,X=$.pollMs??Math.max(A*2,250),J=$.verbose;V8.mkdirSync(Y,{recursive:!0});let U=null,j=!1,W=null,Q=!1,f=(F)=>{return JSON.stringify(F.map((N)=>({id:N.id,from:N.from,to:N.to,path:N.path,pid:N.pid,pathRewrites:N.pathRewrites,cleanUrls:N.cleanUrls,changeOrigin:N.changeOrigin,static:N.static,loadBalancer:N.loadBalancer})).sort((N,R)=>N.id.localeCompare(R.id)))},z=()=>{if(U=null,j)return;Bw(Y,J).then((F)=>{return W=f(F),w(F)}).catch((F)=>{E("registry",`watcher onChange failed: ${F}`,J)})},B=()=>{if(j)return;if(U)clearTimeout(U);U=setTimeout(z,A)},T=setInterval(()=>{if(j||Q)return;Q=!0,Bw(Y,J).then((F)=>{if(f(F)!==W)B()}).catch((F)=>{E("registry",`watcher poll failed: ${F}`,J)}).finally(()=>{Q=!1})},X),K=V8.watch(Y,{persistent:!0},(F,N)=>{if(N&&/\.tmp\.\d+\.\d+$/.test(N))return;B()});return K.on("error",(F)=>{E("registry",`watcher error: ${F}`,J)}),B(),{close:()=>{if(j=!0,U)clearTimeout(U);clearInterval(T),K.close()}}}var OH;var g$=a(()=>{z0();OH=/^[a-zA-Z0-9._-]+$/});import{closeSync as u2,openSync as DH,readFileSync as xH}from"node:fs";import*as c2 from"node:fs/promises";import{spawn as kH}from"node:child_process";import{homedir as ZH}from"node:os";import*as PY from"node:path";import*as Iw from"node:process";class Cj{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(w){this.resolver=w.resolver,this.registryDir=w.registryDir??$w(),this.rpxDir=w.rpxDir??PY.join(ZH(),".stacks","rpx"),this.verbose=w.verbose??!1,this.startupTimeoutMs=w.startupTimeoutMs??PH,this.pollIntervalMs=w.pollIntervalMs??iH,this.restartDelayMs=w.restartDelayMs??uH,this.killGraceMs=w.killGraceMs??cH,this.launch=w.launcher??mH(this.verbose),this.probePort=w.probePort??vH,this.pickPort=w.pickPort??((Y)=>qj(Y,"127.0.0.1")),this.isHostRoutable=w.isHostRoutable??(()=>!1),this.onSiteActivating=w.onSiteActivating,this.now=w.now??Date.now,this.writeEntry=w.writeEntry??c1,this.removeEntry=w.removeEntry??m$;let $=w.reapIntervalMs??bH;if(this.reaper=setInterval(()=>{this.reapIdle()},$),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(w){if(this.stopped)return{kind:"unknown"};let $=this.sites.get(w);if($&&$.status==="failed"&&this.now()-$.failedAt>=this.restartDelayMs)this.sites.delete(w),$=void 0;if(!$){let Y=this.resolver.resolve(w);if(!Y)return{kind:"unknown"};$=await this.start(Y)}if($.lastAccess=this.now(),$.status==="ready")return{kind:"ready",host:w};if($.status==="failed")return{kind:"failed",host:w,error:$.error??"failed to start",logTail:this.readLogTail($)};return{kind:"starting",host:w,sinceMs:this.now()-$.startedAt,source:$.site.source,logTail:this.readLogTail($,16)}}async start(w){try{this.onSiteActivating?.(w.host)}catch{}let $=new Map;if(!w.selfRegisters)for(let j of w.routes){if($.has(j.portEnv))continue;let W=await this.pickPort(j.defaultPort??3000);$.set(j.portEnv,W)}let Y=PY.join(this.rpxDir,"sites",`${w.id}.log`);await c2.mkdir(PY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv(w,$),X=null,J;try{X=this.launch({command:w.command,cwd:w.dir,env:A,logPath:Y})}catch(j){J=`failed to spawn: ${j.message}`}let U={site:w,status:J?"failed":"starting",handle:X,ports:$,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:J?this.now():0,error:J,logPath:Y,exited:!1,ready:Promise.resolve()};if(this.sites.set(w.host,U),J)return H.warn(`rpx: site ${w.host} ${J}`),U;return H.info(`rpx: booting ${w.host} → ${w.command} (${w.dir})`),X.exited.then((j)=>this.onProcessExit(U,j)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((j)=>{E("sites",`readiness loop for ${w.host} threw: ${j}`,this.verbose)}),U}async onProcessExit(w,$){if(w.exited=!0,this.stopped||this.sites.get(w.site.host)!==w)return;if(w.status==="ready"){H.warn(`rpx: ${w.site.host} exited${$!==null?` (code ${$})`:""} — will reboot on next request`),this.sites.delete(w.site.host);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if(w.status==="starting")this.fail(w,`process exited${$!==null?` with code ${$}`:""} before becoming ready`)}async driveReadiness(w){let{site:$}=w,Y=this.now()+this.startupTimeoutMs,A=$.selfRegisters?()=>this.isHostRoutable($.host):await this.makeGateProbe($,w.ports);while(this.now()<Y&&!this.stopped){if(w.status!=="starting"||w.exited)return;if(await A()){if(await this.publishRoutes(w),w.status==="starting")w.status="ready",H.success(`rpx: ${$.host} ready`);return}await Ij(this.pollIntervalMs)}if(w.status==="starting")this.fail(w,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(w,$){let Y=w.routes.filter((X)=>X.readyGate??X$(X.path)==="/").map((X)=>$.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...$.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes(w){let{site:$,ports:Y}=w;if($.selfRegisters||$.routes.length===0)return;let A=$.routes.find((W)=>X$(W.path)==="/")??$.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of $.routes){if(W===A)continue;let Q=Y.get(W.portEnv);if(Q===void 0)continue;J.push({from:X$(W.path),to:`localhost:${Q}`,stripPrefix:W.stripPrefix??!1})}let U={id:$.id,from:`localhost:${X}`,to:$.host,cwd:$.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:w.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),w.routeIds=[$.id];let j=this.now()+2000;while(this.now()<j&&!this.isHostRoutable($.host))await Ij(50)}fail(w,$){w.status="failed",w.error=$,w.failedAt=this.now(),H.warn(`rpx: site ${w.site.host} failed — ${$}`),this.killProcess(w)}buildEnv(w,$){let Y={};for(let[A,X]of Object.entries(Iw.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,w.env);for(let[A,X]of $)Y[A]=String(X);return Y.RPX_SITE_HOST=w.host,Y.RPX_SITE_URL=`https://${w.host}`,Y}readLogTail(w,$=40){try{return xH(w.logPath,"utf8").split(`
232
+ `,JH.encode(j)}async function FH(w){let $=w.getReader(),Y=[],A=0;for(;;){let{done:U,value:j}=await $.read();if(U)break;if(j){if(A+=j.length,A>H2)return $.cancel().catch(()=>{}),null;Y.push(j)}}if(Y.length===1)return Y[0];let X=new Uint8Array(A),J=0;for(let U of Y)X.set(U,J),J+=U.length;return X}var lq,VY,N8,pq,Gj,b$,H2=1048576,Bj=30000,wH=16384,R2=262144,$H=2097152,YH=524288,AH=8192,XH=4096,JH,M2,UH,q8;var L2=s(()=>{({connect:lq}=Bun),VY=Symbol("rpx.pool.fallback"),N8=Symbol("rpx.pool.stale"),pq=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);Gj=Symbol("rpx.pool.timeout"),b$=Symbol("rpx.pool.busy");JH=new TextEncoder,M2=new TextDecoder,UH=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);q8=new Map});function S2(w){let $=typeof w==="string"?{to:w}:w,Y=($.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:$.status??301,preservePath:$.preservePath??!0}}function h2(w,$,Y){if(!w.preservePath)return w.to||"/";let A=`${$}${Y}`;return A==="/"?`${w.to}/`:`${w.to}${A}`}import*as Ew from"node:path";function H8(w,$){if(typeof w==="string")return{dir:w,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:$};return{dir:w.dir,spa:w.spa??!1,pathRewriteStyle:w.pathRewriteStyle??"directory",maxAge:w.maxAge??0,cleanUrls:$}}function NH(w){let $=Ew.extname(w).toLowerCase();return TH[$]??"application/octet-stream"}function qH(w){let $;try{$=decodeURIComponent(w)}catch{return null}if($.includes("\x00")||$.includes("\\"))return null;let Y=Ew.posix.normalize(`/${$}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function HH(w,$){let Y=qH(w);if(Y===null)return null;let A=Ew.posix.extname(Y);if($.cleanUrls&&A===".html"){let X=w.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Ew.join($.dir,Y),redirectTo:X||"/"}}if(Y===""||w.endsWith("/"))return{filePath:Ew.join($.dir,Y,"index.html")};if(A!=="")return{filePath:Ew.join($.dir,Y)};if($.pathRewriteStyle==="flat")return{filePath:Ew.join($.dir,`${Y}.html`)};return{filePath:Ew.join($.dir,Y,"index.html")}}async function O2(w,$){let Y=HH(w,$);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=$.maxAge>0?`public, max-age=${$.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":NH(Y.filePath),"Cache-Control":A}});if($.spa){let J=Ew.join($.dir,"index.html"),U=Bun.file(J);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 TH;var R8=s(()=>{TH={".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 RH(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function yH(w){let $=w.headers.get("host")||"",Y=$.indexOf(":");return Y===-1?$:$.slice(0,Y)}function x2(w,$){if(!$||$==="/")return w;if(w===$)return"/";if(w.startsWith(`${$}/`)){let Y=w.slice($.length);return Y===""?"/":Y}return w}function _2(w){if(w.upstreamPool)return K2(w.upstreamPool);if(w.sourceHost)return{url:w.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function D2(w,$,Y,A){let X=Y?.url??$.sourceHost??"",U=$.stripBasePathPrefix??!1?x2(w,$.basePath):w,j=wj(U,$.pathRewrites);if(j)X=j.targetHost,U=j.targetPath,E("request",`Path rewrite: ${w} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function IH(w){let $=w.indexOf("://"),Y=$===-1?w.indexOf("/"):w.indexOf("/",$+3);if(Y===-1)return{pathname:"/",search:""};let A=w.indexOf("?",Y);if(A===-1)return{pathname:w.slice(Y),search:""};return{pathname:w.slice(Y,A),search:w.slice(A)}}function LY(w,$,Y){let A=async(X,J)=>{let{pathname:U,search:j}=IH(X.url),W=yH(X),Q=w(W,U);if(!Q&&Y){let F=await Y(W,U,X);if(F instanceof Response)return F;if(F&&F.retry)Q=w(W,U)}if(!Q)return E("request",`No route found for host: ${W}`,$),new Response(`No proxy configured for ${W}`,{status:404});if(Q.auth){let F=N2(X,U,Q.auth);if(F)return E("request",`401 challenge for ${W}${U}`,$),F}if(Q.redirect){let F=h2(Q.redirect,U,j);return E("request",`${Q.redirect.status} redirect ${W}${U} → ${F}`,$),new Response(null,{status:Q.redirect.status,headers:{location:F}})}if(Q.static){let N=Q.stripBasePathPrefix??!0?x2(U,Q.basePath):U;return O2(N,Q.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let F=_2(Q);if(!J||!F)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:N,targetPath:R}=D2(U,Q,F,$),V=`ws://${N}${R}${j}`,L={};for(let[M,D]of X.headers)if(!MH.has(M.toLowerCase())&&M.toLowerCase()!=="host")L[M]=D;L.host=N,L["x-forwarded-for"]="127.0.0.1",L["x-forwarded-proto"]="https",L["x-forwarded-host"]=W;let q={targetUrl:V,forwardHeaders:L};if(J.upgrade(X,{data:q})){E("ws",`upgraded ${W}${R} → ${V}`,$);return}return new Response("WebSocket upgrade failed",{status:400})}let f=_2(Q);if(!f)return new Response(`No upstream configured for ${W}`,{status:502});if(Q.cleanUrls&&U.endsWith(".html")){let F=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:F}})}let{targetHost:z,targetPath:B}=D2(U,Q,f,$),G=Q.changeOrigin?`http://${z}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",K=Q.upstreamPool;if(K)f.activeConnections++;try{let F=await C2({hostPort:z,method:X.method,path:`${B}${j}`,reqHeaders:X.headers,forwardedHost:W,originOverride:G,body:X.body,signal:X.signal});if(K)F8(K,f);return F}catch(F){if(F===Gj){if(E("request",`Upstream timeout for ${W}`,$),K)MY(K,f);return new Response("Gateway Timeout",{status:504})}if(F===b$)return E("request",`Upstream pool saturated for ${W}`,$),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(F===VY||!T)try{let N=new Headers(X.headers);if(N.set("host",z),N.set("x-forwarded-for","127.0.0.1"),N.set("x-forwarded-proto","https"),N.set("x-forwarded-host",W),G!==void 0)N.set("origin",G);let R=await fetch(`http://${z}${B}${j}`,{method:X.method,headers:N,body:X.body,redirect:"manual"});if(K)F8(K,f);return R}catch(N){if(E("request",`Proxy error for ${W}: ${N}`,$),K)MY(K,f);return new Response(`Proxy Error: ${N}`,{status:502})}if(E("request",`Proxy error for ${W}: ${F}`,$),K)MY(K,f);return new Response(`Proxy Error: ${F}`,{status:502})}finally{if(K)f.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return E("request",`Unhandled proxy handler error: ${U}`,$),new Response("Bad Gateway",{status:502})}}}function SY(w){let $=new WeakMap,Y=RH();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){E("ws",`failed to open upstream ${X}: ${W}`,w),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let j={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};$.set(A,j),U.addEventListener("open",()=>{j.upstreamOpen=!0;for(let W of j.pending)U.send(W);j.pending=[],j.pendingBytes=0}),U.addEventListener("message",(W)=>{A.send(W.data)}),U.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),U.addEventListener("error",()=>{E("ws",`upstream error for ${X}`,w);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=$.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let j=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+j>Y){E("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,w);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}$.delete(A);return}J.pending.push(U),J.pendingBytes+=j},close(A,X,J){let U=$.get(A);if(!U)return;$.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var MH;var Ej=s(()=>{T8();L2();R8();z0();MH=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});import*as Z2 from"node:fs";import*as P2 from"node:path";function M8(w,$){if(!w||!$.startsWith(k2))return null;let Y=$.slice(k2.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return Z2.readFileSync(P2.join(w,Y),"utf8")}catch{return null}}var k2="/.well-known/acme-challenge/";var Kj=()=>{};function Y$(w){if(!w||w==="/")return"/";let $=w.trim();if(!$.startsWith("/"))$=`/${$}`;return $=$.replace(/\/+$/,""),$===""?"/":$}function CH(w,$){if($==="/")return!0;if(w===$)return!0;return w.startsWith(`${$}/`)}function hY(w){let $=new Map;for(let A of w){let X=Y$(A.path),J=$.get(A.host);if(!J)J=new Map,$.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of $){let J=[];for(let[U,j]of X)J.push({path:U,route:j});J.sort((U,j)=>j.path.length-U.path.length),Y.set(A,J)}return Y}function Fj(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!U1(J))continue;if(wY($,J)){let j=J.length-1;if(j>X)X=j,A=U}}return A}function OY(w,$,Y){let A=Fj(w,$);if(!A)return;for(let X of A)if(CH(Y,X.path))return X.route;return}var y8=()=>{};import*as _Y from"node:fs/promises";import*as Tj from"node:path";function u$(w){if(Array.isArray(w))return w.map(($)=>({...$,lowMemoryMode:!0}));return{...w,lowMemoryMode:!0}}function VH(w){if(!w.endsWith(".crt"))return null;let $=w.slice(0,-4);if($.length===0)return null;if($.startsWith("_wildcard."))return`*.${$.slice(10)}`;return $}async function LH(w,$,Y,A){try{let[X,J]=await Promise.all([_Y.readFile($,"utf8"),_Y.readFile(Y,"utf8")]);return{serverName:w,cert:X,key:J}}catch(X){return E("sni",`skipping ${w}: ${X.message}`,A),null}}async function DY(w,$){let Y=new Map;if(w.certsDir){let X=[];try{X=await _Y.readdir(w.certsDir)}catch(J){E("sni",`certsDir read failed (${w.certsDir}): ${J.message}`,$)}for(let J of X){let U=VH(J);if(!U)continue;let j=J.slice(0,-4);Y.set(U,{certPath:Tj.join(w.certsDir,J),keyPath:Tj.join(w.certsDir,`${j}.key`)})}}if(w.domains)for(let[X,J]of Object.entries(w.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await LH(X,J.certPath,J.keyPath,$);if(U)A.push(U)}return A}var Nj=s(()=>{z0()});import*as Iw from"node:fs/promises";import*as I8 from"node:path";function xY(w=process.env){let $=w.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if($==="restart"||$==="rebind")return $;return w.INVOCATION_ID?"restart":"rebind"}function OH(w,$){if(!$||$.length===0)return!1;return $.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return w===A||w.endsWith(`.${A}`)})}function b2(w){if(!w||w.length>253)return!1;if(w.includes("/")||w.includes(":")||w.includes(" "))return!1;if(w.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(w)}class i1{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(w){this.config=w.config,this.certsDir=w.certsDir,this.onCertAdded=w.onCertAdded,this.http01Store=w.http01Store??IX,this.issuer=w.issuer??aU,this.verbose=w.verbose??!1,this.negativeCacheMs=w.negativeCacheMs??hH;for(let $ of w.initial??[])this.certs.set($.serverName,$)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(w){return this.certs.has(w)}async isApproved(w){if(!b2(w))return!1;if(OH(w,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(w)}catch($){return E("on-demand",`ask(${w}) threw: ${$.message}`,this.verbose),!1}return!1}async ensureCert(w){if(!this.config.enabled)return!1;if(this.certs.has(w))return!0;if(!b2(w))return!1;let $=this.inFlight.get(w);if($)return $;let Y=this.negativeCache.get(w);if(Y!==void 0&&Date.now()<Y){if(await this.loadFromDisk(w))return this.negativeCache.delete(w),!0;return E("on-demand",`${w} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1}let A=this.issue(w).finally(()=>{this.inFlight.delete(w)});return this.inFlight.set(w,A),A}async issue(w){if(this.certs.has(w))return!0;if(await this.loadFromDisk(w))return!0;if(!await this.isApproved(w))return E("on-demand",`refused issuance for ${w} (not approved)`,this.verbose),this.cacheNegative(w),!1;try{E("on-demand",`issuing cert for ${w} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let $=await this.issuer({domains:[w],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey($.accountKeyPem),await this.persist(w,$.fullChainPem,$.keyPem);let Y={serverName:w,cert:$.fullChainPem,key:$.keyPem};return this.certs.set(w,Y),this.negativeCache.delete(w),E("on-demand",`issued + installed cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch($){return this.cacheNegative(w),E("on-demand",`issuance for ${w} failed: ${$.message}`,this.verbose),!1}}cacheNegative(w){if(this.negativeCache.size>=i2){let $=Date.now();for(let[Y,A]of this.negativeCache)if(A<=$)this.negativeCache.delete(Y);if(this.negativeCache.size>=i2){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set(w,Date.now()+this.negativeCacheMs)}async loadFromDisk(w){let{certPath:$,keyPath:Y}=this.pathsFor(w);try{let[A,X]=await Promise.all([Iw.readFile($,"utf8"),Iw.readFile(Y,"utf8")]),J={serverName:w,cert:A,key:X};return this.certs.set(w,J),E("on-demand",`adopted existing on-disk cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(w){return{certPath:I8.join(this.certsDir,`${w}.crt`),keyPath:I8.join(this.certsDir,`${w}.key`)}}async persist(w,$,Y){await Iw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor(w);await Promise.all([Iw.writeFile(A,$,"utf8"),Iw.writeFile(X,Y,{encoding:"utf8",mode:384})])}get accountKeyPath(){return I8.join(this.certsDir,SH)}async loadAccountKey(){try{return await Iw.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(w){if(!w||this.accountKeyPem===w)return;this.accountKeyPem=w,await Iw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Iw.writeFile(this.accountKeyPath,w,{encoding:"utf8",mode:384}).catch(()=>{})}}var SH="acme-account.key",hH=60000,i2=4096;var qj=s(()=>{DX();z0()});import*as C8 from"node:net";function y$(w,$,Y){return E("port",`Checking if port ${w} is in use on ${$}`,Y),new Promise((A)=>{let X=C8.createServer(),J=setTimeout(()=>{E("port",`Checking port ${w} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")E("port",`Port ${w} is in use`,Y),A(!0);else E("port",`Error checking port ${w}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),E("port",`Port ${w} is available`,Y),X.close(),A(!1)});try{X.listen(w,$)}catch(U){clearTimeout(J),E("port",`Exception checking port ${w}: ${U}`,Y),A(!0)}})}async function Hj(w,$,Y,A=50){E("port",`Finding available port starting from ${w} (max attempts: ${A})`,Y);let X=w,J=0;while(J<A){if(J++,!await y$(X,$,Y))return E("port",`Found available port: ${X} after ${J} attempts`,Y),X;E("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${A})`,Y),X++}throw Error(`Unable to find available port after ${A} attempts starting from ${w}`)}function u2(w,$,Y=5000,A){return E("port",`Testing connection to ${$}:${w}`,A),new Promise((X)=>{let J=C8.connect({host:$,port:w,timeout:Y});J.once("connect",()=>{E("port",`Successfully connected to ${$}:${w}`,A),J.end(),X(!0)}),J.once("timeout",()=>{E("port",`Connection to ${$}:${w} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{E("port",`Failed to connect to ${$}:${w}: ${U.message}`,A),J.destroy(),X(!1)})})}class V8{usedPorts=new Set;hostname;verbose;maxRetries;constructor(w="0.0.0.0",$,Y=50){this.hostname=w,this.verbose=$,this.maxRetries=Y}async getNextAvailablePort(w,$=!1){if(this.usedPorts.has(w))return this.findNextAvailablePort(w+1,$);if(await y$(w,this.hostname,this.verbose))return this.findNextAvailablePort(w+1,$);if($){if(!await u2(w,this.hostname,3000,this.verbose))return E("port",`Port ${w} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(w+1,$)}return this.usedPorts.add(w),w}async findNextAvailablePort(w,$=!1){let Y=await Hj(w,this.hostname,this.verbose,this.maxRetries);if($){if(!await u2(Y,this.hostname,3000,this.verbose))if(Y<w+this.maxRetries)return this.findNextAvailablePort(Y+1,$);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort(w){E("port",`Releasing port ${w}`,this.verbose),this.usedPorts.delete(w)}}var OL;var Rj=s(()=>{z0();OL=new V8});import*as L8 from"node:fs";import*as p0 from"node:fs/promises";import{homedir as _H}from"node:os";import*as Mj from"node:path";import*as S8 from"node:process";function Aw(){return Mj.join(_H(),".stacks","rpx","registry.d")}function I$(w){return typeof w==="string"&&w.length>0&&w.length<=128&&DH.test(w)}function yj(w,$){if(!I$($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return Mj.join(w,`${$}.json`)}function Xw(w){if(!Number.isInteger(w)||w<=0)return!1;try{return S8.kill(w,0),!0}catch($){return $.code==="EPERM"}}function c2(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&I$($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function xH(w){await p0.mkdir(w,{recursive:!0})}async function b1(w,$=Aw(),Y){if(!c2(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await xH($);let A=yj($,w.id),X=`${A}.tmp.${S8.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),E("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function c$(w,$=Aw(),Y){let A=yj($,w);try{await p0.unlink(A),E("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function Ij(w,$=Aw(),Y){let A=yj($,w);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!c2(J))return E("registry",`entry ${w} failed validation, removing`,Y),await p0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return E("registry",`entry ${w} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function Kw(w=Aw(),$){let Y;try{Y=await p0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!I$(J))continue;let U=await Ij(J,w,$);if(U)A.push(U)}return A}async function kY(w=Aw(),$){let Y=await Kw(w,$),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!Xw(X.pid))E("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,$),await c$(X.id,w,$).catch(()=>{}),A++}return A}function h8(w,$={}){let Y=$.dir??Aw(),A=$.debounceMs??100,X=$.pollMs??Math.max(A*2,250),J=$.verbose;L8.mkdirSync(Y,{recursive:!0});let U=null,j=!1,W=null,Q=!1,f=(F)=>{return JSON.stringify(F.map((N)=>({id:N.id,from:N.from,to:N.to,path:N.path,pid:N.pid,pathRewrites:N.pathRewrites,cleanUrls:N.cleanUrls,changeOrigin:N.changeOrigin,static:N.static,loadBalancer:N.loadBalancer})).sort((N,R)=>N.id.localeCompare(R.id)))},z=()=>{if(U=null,j)return;Kw(Y,J).then((F)=>{return W=f(F),w(F)}).catch((F)=>{E("registry",`watcher onChange failed: ${F}`,J)})},B=()=>{if(j)return;if(U)clearTimeout(U);U=setTimeout(z,A)},T=setInterval(()=>{if(j||Q)return;Q=!0,Kw(Y,J).then((F)=>{if(f(F)!==W)B()}).catch((F)=>{E("registry",`watcher poll failed: ${F}`,J)}).finally(()=>{Q=!1})},X),K=L8.watch(Y,{persistent:!0},(F,N)=>{if(N&&/\.tmp\.\d+\.\d+$/.test(N))return;B()});return K.on("error",(F)=>{E("registry",`watcher error: ${F}`,J)}),B(),{close:()=>{if(j=!0,U)clearTimeout(U);clearInterval(T),K.close()}}}var DH;var v$=s(()=>{z0();DH=/^[a-zA-Z0-9._-]+$/});import{closeSync as v2,openSync as kH,readFileSync as ZH}from"node:fs";import*as m2 from"node:fs/promises";import{spawn as PH}from"node:child_process";import{homedir as iH}from"node:os";import*as ZY from"node:path";import*as Cw from"node:process";class Vj{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(w){this.resolver=w.resolver,this.registryDir=w.registryDir??Aw(),this.rpxDir=w.rpxDir??ZY.join(iH(),".stacks","rpx"),this.verbose=w.verbose??!1,this.startupTimeoutMs=w.startupTimeoutMs??bH,this.pollIntervalMs=w.pollIntervalMs??uH,this.restartDelayMs=w.restartDelayMs??vH,this.killGraceMs=w.killGraceMs??mH,this.launch=w.launcher??dH(this.verbose),this.probePort=w.probePort??gH,this.pickPort=w.pickPort??((Y)=>Hj(Y,"127.0.0.1")),this.isHostRoutable=w.isHostRoutable??(()=>!1),this.onSiteActivating=w.onSiteActivating,this.now=w.now??Date.now,this.writeEntry=w.writeEntry??b1,this.removeEntry=w.removeEntry??c$;let $=w.reapIntervalMs??cH;if(this.reaper=setInterval(()=>{this.reapIdle()},$),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(w){if(this.stopped)return{kind:"unknown"};let $=this.sites.get(w);if($&&$.status==="failed"&&this.now()-$.failedAt>=this.restartDelayMs)this.sites.delete(w),$=void 0;if(!$){let Y=this.resolver.resolve(w);if(!Y)return{kind:"unknown"};$=await this.start(Y)}if($.lastAccess=this.now(),$.status==="ready")return{kind:"ready",host:w};if($.status==="failed")return{kind:"failed",host:w,error:$.error??"failed to start",logTail:this.readLogTail($)};return{kind:"starting",host:w,sinceMs:this.now()-$.startedAt,source:$.site.source,logTail:this.readLogTail($,16)}}async start(w){try{this.onSiteActivating?.(w.host)}catch{}let $=new Map;if(!w.selfRegisters)for(let j of w.routes){if($.has(j.portEnv))continue;let W=await this.pickPort(j.defaultPort??3000);$.set(j.portEnv,W)}let Y=ZY.join(this.rpxDir,"sites",`${w.id}.log`);await m2.mkdir(ZY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv(w,$),X=null,J;try{X=this.launch({command:w.command,cwd:w.dir,env:A,logPath:Y})}catch(j){J=`failed to spawn: ${j.message}`}let U={site:w,status:J?"failed":"starting",handle:X,ports:$,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:J?this.now():0,error:J,logPath:Y,exited:!1,ready:Promise.resolve()};if(this.sites.set(w.host,U),J)return H.warn(`rpx: site ${w.host} ${J}`),U;return H.info(`rpx: booting ${w.host} → ${w.command} (${w.dir})`),X.exited.then((j)=>this.onProcessExit(U,j)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((j)=>{E("sites",`readiness loop for ${w.host} threw: ${j}`,this.verbose)}),U}async onProcessExit(w,$){if(w.exited=!0,this.stopped||this.sites.get(w.site.host)!==w)return;if(w.status==="ready"){H.warn(`rpx: ${w.site.host} exited${$!==null?` (code ${$})`:""} — will reboot on next request`),this.sites.delete(w.site.host);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if(w.status==="starting")this.fail(w,`process exited${$!==null?` with code ${$}`:""} before becoming ready`)}async driveReadiness(w){let{site:$}=w,Y=this.now()+this.startupTimeoutMs,A=$.selfRegisters?()=>this.isHostRoutable($.host):await this.makeGateProbe($,w.ports);while(this.now()<Y&&!this.stopped){if(w.status!=="starting"||w.exited)return;if(await A()){if(await this.publishRoutes(w),w.status==="starting")w.status="ready",H.success(`rpx: ${$.host} ready`);return}await Cj(this.pollIntervalMs)}if(w.status==="starting")this.fail(w,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(w,$){let Y=w.routes.filter((X)=>X.readyGate??Y$(X.path)==="/").map((X)=>$.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...$.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes(w){let{site:$,ports:Y}=w;if($.selfRegisters||$.routes.length===0)return;let A=$.routes.find((W)=>Y$(W.path)==="/")??$.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of $.routes){if(W===A)continue;let Q=Y.get(W.portEnv);if(Q===void 0)continue;J.push({from:Y$(W.path),to:`localhost:${Q}`,stripPrefix:W.stripPrefix??!1})}let U={id:$.id,from:`localhost:${X}`,to:$.host,cwd:$.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:w.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),w.routeIds=[$.id];let j=this.now()+2000;while(this.now()<j&&!this.isHostRoutable($.host))await Cj(50)}fail(w,$){w.status="failed",w.error=$,w.failedAt=this.now(),H.warn(`rpx: site ${w.site.host} failed — ${$}`),this.killProcess(w)}buildEnv(w,$){let Y={};for(let[A,X]of Object.entries(Cw.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,w.env);for(let[A,X]of $)Y[A]=String(X);return Y.RPX_SITE_HOST=w.host,Y.RPX_SITE_URL=`https://${w.host}`,Y}readLogTail(w,$=40){try{return ZH(w.logPath,"utf8").split(`
233
233
  `).slice(-$).join(`
234
- `).trim()}catch{return""}}async stop(w){let $=this.sites.get(w);if(!$)return;this.sites.delete(w);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess($),H.info(`rpx: stopped ${w}`)}async killProcess(w){let $=w.handle;if(!$)return;w.handle=null;try{$.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{$.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([$.exited.catch(()=>{}),Ij(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let w=this.now();for(let[$,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=w-Y.lastAccess;if((Y.status==="ready"||w-Y.startedAt>this.startupTimeoutMs)&&X>A)E("sites",`reaping ${$} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop($)}}list(){let w=this.now();return[...this.sites.values()].map(($)=>({host:$.site.host,dir:$.site.dir,status:$.status,pid:$.handle?.pid??null,ports:Object.fromEntries($.ports),uptimeMs:w-$.startedAt,idleMs:w-$.lastAccess,error:$.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((w)=>this.stop(w)))}}function Ij(w){return new Promise(($)=>setTimeout($,w))}async function vH(w){let $=new AbortController,Y=setTimeout(()=>$.abort(),2000);try{return await fetch(`http://127.0.0.1:${w}/`,{signal:$.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(Y)}}function mH(w){let $=gH();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=DH(J,"a");try{let j=kH("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...$?{uid:$.uid,gid:$.gid}:{}}),W=j.pid;if(W===void 0)throw Error("spawn returned no pid");let Q=new Promise((f)=>{j.once("exit",(z)=>{f(z)}),j.once("error",()=>{f(null)})}).finally(()=>{try{u2(U)}catch{}});return E("sites",`spawned pid ${W}: sh -c ${Y} (cwd ${A})`,w),{pid:W,exited:Q,stop:(f="SIGTERM")=>{try{Iw.kill(-W,f)}catch{try{j.kill(f)}catch{}}}}}catch(j){try{u2(U)}catch{}throw j}}}function gH(){if(Iw.platform==="win32")return null;if(!(typeof Iw.getuid==="function"&&Iw.getuid()===0))return null;let $=Number.parseInt(Iw.env.SUDO_UID??"",10),Y=Number.parseInt(Iw.env.SUDO_GID??"",10);if(!Number.isInteger($)||$<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:$,gid:Y}}var PH=120000,iH=200,bH=30000,uH=3000,cH=4000;var v2=a(()=>{M8();Hj();g$();z0();x$()});function v1(w){return w.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function m2(w,$,Y){return`<!doctype html>
234
+ `).trim()}catch{return""}}async stop(w){let $=this.sites.get(w);if(!$)return;this.sites.delete(w);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess($),H.info(`rpx: stopped ${w}`)}async killProcess(w){let $=w.handle;if(!$)return;w.handle=null;try{$.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{$.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([$.exited.catch(()=>{}),Cj(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let w=this.now();for(let[$,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=w-Y.lastAccess;if((Y.status==="ready"||w-Y.startedAt>this.startupTimeoutMs)&&X>A)E("sites",`reaping ${$} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop($)}}list(){let w=this.now();return[...this.sites.values()].map(($)=>({host:$.site.host,dir:$.site.dir,status:$.status,pid:$.handle?.pid??null,ports:Object.fromEntries($.ports),uptimeMs:w-$.startedAt,idleMs:w-$.lastAccess,error:$.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((w)=>this.stop(w)))}}function Cj(w){return new Promise(($)=>setTimeout($,w))}async function gH(w){let $=new AbortController,Y=setTimeout(()=>$.abort(),2000);try{return await fetch(`http://127.0.0.1:${w}/`,{signal:$.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(Y)}}function dH(w){let $=nH();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=kH(J,"a");try{let j=PH("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...$?{uid:$.uid,gid:$.gid}:{}}),W=j.pid;if(W===void 0)throw Error("spawn returned no pid");let Q=new Promise((f)=>{j.once("exit",(z)=>{f(z)}),j.once("error",()=>{f(null)})}).finally(()=>{try{v2(U)}catch{}});return E("sites",`spawned pid ${W}: sh -c ${Y} (cwd ${A})`,w),{pid:W,exited:Q,stop:(f="SIGTERM")=>{try{Cw.kill(-W,f)}catch{try{j.kill(f)}catch{}}}}}catch(j){try{v2(U)}catch{}throw j}}}function nH(){if(Cw.platform==="win32")return null;if(!(typeof Cw.getuid==="function"&&Cw.getuid()===0))return null;let $=Number.parseInt(Cw.env.SUDO_UID??"",10),Y=Number.parseInt(Cw.env.SUDO_GID??"",10);if(!Number.isInteger($)||$<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:$,gid:Y}}var bH=120000,uH=200,cH=30000,vH=3000,mH=4000;var g2=s(()=>{y8();Rj();v$();z0();_$()});function u1(w){return w.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function d2(w,$,Y){return`<!doctype html>
235
235
  <html lang="en">
236
236
  <head>
237
237
  <meta charset="utf-8">
238
238
  <meta name="viewport" content="width=device-width, initial-scale=1">
239
239
  ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
240
- <title>${v1(w)}</title>
241
- <style>${dH}</style>
240
+ <title>${u1(w)}</title>
241
+ <style>${lH}</style>
242
242
  </head>
243
243
  <body><main class="card">${$}</main></body>
244
- </html>`}function g2(w){let $=Math.max(1,Math.round(w.sinceMs/1000)),Y=w.logTail?`<pre>${v1(w.logTail)}</pre>`:"",A=`
245
- <div class="row"><div class="spinner"></div><h1>Starting ${v1(w.host)}…</h1></div>
244
+ </html>`}function n2(w){let $=Math.max(1,Math.round(w.sinceMs/1000)),Y=w.logTail?`<pre>${u1(w.logTail)}</pre>`:"",A=`
245
+ <div class="row"><div class="spinner"></div><h1>Starting ${u1(w.host)}…</h1></div>
246
246
  <p>rpx is booting this site's dev server on demand. This page reloads itself —
247
247
  it'll switch to the app as soon as it's ready (usually a few seconds).</p>
248
248
  <p>Booting for ${$}s.</p>
249
- ${Y}`;return new Response(m2(`Starting ${w.host}`,A,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function d2(w){let $=w.logTail?`<pre>${v1(w.logTail)}</pre>`:"<p>No output was captured.</p>",Y=`
250
- <div class="row"><div class="dot"></div><h1>${v1(w.host)} failed to start</h1></div>
251
- <p>${v1(w.error)}</p>
249
+ ${Y}`;return new Response(d2(`Starting ${w.host}`,A,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function l2(w){let $=w.logTail?`<pre>${u1(w.logTail)}</pre>`:"<p>No output was captured.</p>",Y=`
250
+ <div class="row"><div class="dot"></div><h1>${u1(w.host)} failed to start</h1></div>
251
+ <p>${u1(w.error)}</p>
252
252
  ${$}
253
- <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(m2(`${w.host} failed`,Y,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var dH=`
253
+ <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(d2(`${w.host} failed`,Y,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var lH=`
254
254
  :root { color-scheme: light dark }
255
255
  * { box-sizing: border-box }
256
256
  body {
@@ -276,63 +276,63 @@ ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
276
276
  }
277
277
  .dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
278
278
  @keyframes spin { to { transform: rotate(360deg) } }
279
- `;import{exec as nH}from"node:child_process";import h8 from"node:fs";import lH from"node:os";import p2 from"node:path";import*as d$ from"node:process";import{promisify as pH}from"node:util";function n2(w){let $=w.trim().toLowerCase();return $==="localhost"||$.endsWith(".localhost")||$.endsWith(".localhost.")}async function r2(w){if(d$.platform==="win32")throw Error("Administrator privileges required on Windows");if(TY()){let{stdout:A}=await iY(w);return A}let $=T$(),Y=w.replace(/'/g,"'\\''");try{if($){let{stdout:A}=await iY(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`);return Vj=!0,A}if(Vj)try{let{stdout:A}=await iY(`sudo -n sh -c '${Y}'`);return A}catch(A){E("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await iY(`sudo -n sh -c '${Y}'`);return Vj=!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}`)}}function _8(w){let $=w.indexOf("#"),Y=($===-1?w:w.slice(0,$)).trim();if(!Y)return null;let A=$===-1?"":w.slice($+1).trim(),[X,...J]=Y.split(/\s+/);if(!X||J.length===0)return null;let U=/^rpx(?::pid=(\d+))?$/.exec(A);return{address:X,names:J,comment:A,rpxPid:U?.[1]?Number.parseInt(U[1],10):null,rpxManaged:U!==null}}function t2(w,$){let Y=_8(w);return Y!==null&&O8.has(Y.address)&&Y.names.includes($)}function tH(w,$){let Y=new Set($),A=new Set,X=w.split(`
280
- `),J=[],U=0;while(U<X.length){let j=X[U];if(j.trim()===rH){let Q=[],f=U+1;while(f<X.length){let B=X[f];if(B.trim()===""||B.trim().startsWith("#"))break;Q.push(B),f++}let z=Q.filter((B)=>{let G=_8(B),T=G!==null&&O8.has(G.address)&&G.names.some((K)=>Y.has(K));if(T){for(let K of G.names)if(Y.has(K))A.add(K)}return!T});if(z.length>0||Q.length===0)J.push(j,...z);U=f;continue}let W=_8(j);if(W?.rpxManaged&&O8.has(W.address)&&W.names.some((Q)=>Y.has(Q))){for(let Q of W.names)if(Y.has(Q))A.add(Q);U++;continue}J.push(j),U++}while(J.length>0&&J[J.length-1].trim()==="")J.pop();return{content:`${J.join(`
279
+ `;import{exec as pH}from"node:child_process";import O8 from"node:fs";import rH from"node:os";import t2 from"node:path";import*as m$ from"node:process";import{promisify as tH}from"node:util";function p2(w){let $=w.trim().toLowerCase();return $==="localhost"||$.endsWith(".localhost")||$.endsWith(".localhost.")}async function a2(w){if(m$.platform==="win32")throw Error("Administrator privileges required on Windows");if(FY()){let{stdout:A}=await PY(w);return A}let $=F$(),Y=w.replace(/'/g,"'\\''");try{if($){let{stdout:A}=await PY(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`);return Lj=!0,A}if(Lj)try{let{stdout:A}=await PY(`sudo -n sh -c '${Y}'`);return A}catch(A){E("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await PY(`sudo -n sh -c '${Y}'`);return Lj=!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}`)}}function D8(w){let $=w.indexOf("#"),Y=($===-1?w:w.slice(0,$)).trim();if(!Y)return null;let A=$===-1?"":w.slice($+1).trim(),[X,...J]=Y.split(/\s+/);if(!X||J.length===0)return null;let U=/^rpx(?::pid=(\d+))?$/.exec(A);return{address:X,names:J,comment:A,rpxPid:U?.[1]?Number.parseInt(U[1],10):null,rpxManaged:U!==null}}function s2(w,$){let Y=D8(w);return Y!==null&&_8.has(Y.address)&&Y.names.includes($)}function sH(w,$){let Y=new Set($),A=new Set,X=w.split(`
280
+ `),J=[],U=0;while(U<X.length){let j=X[U];if(j.trim()===aH){let Q=[],f=U+1;while(f<X.length){let B=X[f];if(B.trim()===""||B.trim().startsWith("#"))break;Q.push(B),f++}let z=Q.filter((B)=>{let G=D8(B),T=G!==null&&_8.has(G.address)&&G.names.some((K)=>Y.has(K));if(T){for(let K of G.names)if(Y.has(K))A.add(K)}return!T});if(z.length>0||Q.length===0)J.push(j,...z);U=f;continue}let W=D8(j);if(W?.rpxManaged&&_8.has(W.address)&&W.names.some((Q)=>Y.has(Q))){for(let Q of W.names)if(Y.has(Q))A.add(Q);U++;continue}J.push(j),U++}while(J.length>0&&J[J.length-1].trim()==="")J.pop();return{content:`${J.join(`
281
281
  `)}
282
- `,removed:[...A]}}function aH(w,$){let Y=[],A=new Set,X=[];for(let J of w.split(`
283
- `)){let U=_8(J);if(U?.rpxManaged&&U.rpxPid!==null&&O8.has(U.address)&&!$(U.rpxPid)){Y.push(...U.names),A.add(U.rpxPid);continue}X.push(J)}while(X.length>0&&X[X.length-1].trim()==="")X.pop();return{content:`${X.join(`
282
+ `,removed:[...A]}}function oH(w,$){let Y=[],A=new Set,X=[];for(let J of w.split(`
283
+ `)){let U=D8(J);if(U?.rpxManaged&&U.rpxPid!==null&&_8.has(U.address)&&!$(U.rpxPid)){Y.push(...U.names),A.add(U.rpxPid);continue}X.push(J)}while(X.length>0&&X[X.length-1].trim()==="")X.pop();return{content:`${X.join(`
284
284
  `)}
285
- `,removed:Y,stalePids:[...A]}}async function Lj(w){try{return await h8.promises.readFile(J$,"utf-8")}catch{return E("hosts","Reading hosts file requires elevated permissions, using sudo",w),r2(`cat "${J$}"`)}}async function Sj(w,$){let Y=p2.join(lH.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await h8.promises.writeFile(Y,w,"utf8"),await r2(`cat "${Y}" | tee "${J$}" > /dev/null`)}finally{await h8.promises.unlink(Y).catch((A)=>{E("hosts",`Failed to remove temporary file: ${A}`,$)})}}async function bY(w,$){let Y=w.filter((X)=>!n2(X)),A=w.filter((X)=>n2(X));if(A.length>0)E("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,$);if(Y.length===0)return;E("hosts",`Adding hosts: ${Y.join(", ")}`,$),E("hosts",`Using hosts file at: ${J$}`,$);try{let X;try{X=await Lj($)}catch(Q){throw console.log(" Could not read hosts file — skipping hosts setup"),E("hosts",`sudo read also failed: ${Q}`,$),Error(`Cannot read hosts file: ${Q}`)}let J=X.split(`
286
- `),U=Y.filter((Q)=>!J.some((f)=>t2(f,Q)));if(U.length===0){E("hosts","All hosts already exist in hosts file",$);return}let j=d$.pid,W=U.map((Q)=>`
287
- 127.0.0.1 ${Q} ${l2}:pid=${j}
288
- ::1 ${Q} ${l2}:pid=${j}`).join(`
289
- `);try{await Sj(X+W,$),console.log(` Hosts updated: ${U.join(", ")}`)}catch(Q){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),U.forEach((f)=>{console.log(` 127.0.0.1 ${f}`),console.log(` ::1 ${f}`)}),console.log(` Or run: sudo nano ${J$}`)}}catch(X){E("hosts",`Failed to manage hosts file: ${X.message}`,$)}}async function a2(w,$){E("hosts",`Removing hosts: ${w.join(", ")}`,$);try{let Y;try{Y=await Lj($)}catch(J){throw E("hosts",`sudo read also failed: ${J}`,$),Error(`Cannot read hosts file: ${J}`)}let{content:A,removed:X}=tH(Y,w);if(X.length===0){E("hosts","No matching rpx-managed hosts found to remove",$);return}try{await Sj(A,$),E("hosts",`Hosts removed successfully: ${X.join(", ")}`,$)}catch(J){E("hosts","Could not clean up hosts file automatically",$)}}catch(Y){E("hosts",`Failed to clean up hosts file: ${Y.message}`,$)}}async function uY(w,$){E("hosts",`Checking hosts: ${w}`,$);let Y;try{Y=await h8.promises.readFile(J$,"utf-8")}catch(X){E("hosts",`Error reading hosts file: ${X}`,$);try{let J=T$(),U;if(J)U=`echo '${J}' | sudo -S cat "${J$}" 2>/dev/null`;else U=`sudo -n cat "${J$}" 2>/dev/null || cat "${J$}" 2>/dev/null || echo ""`;let{stdout:j}=await iY(U);Y=j}catch(J){return E("hosts",`Cannot read hosts file, assuming entries don't exist: ${J}`,$),w.map(()=>!1)}}let A=Y.split(`
290
- `);return w.map((X)=>A.some((J)=>t2(J,X)))}async function cY(w={}){let $=w.isAlive??Yw,Y;try{Y=await Lj(w.verbose)}catch(U){return E("hosts",`stale hosts GC: cannot read hosts file: ${U}`,w.verbose),[]}let{content:A,removed:X,stalePids:J}=aH(Y,$);if(X.length===0)return[];try{return await Sj(A,w.verbose),E("hosts",`stale hosts GC: removed ${X.join(", ")} (dead pid(s): ${J.join(", ")})`,w.verbose),[...new Set(X)]}catch(U){return E("hosts",`stale hosts GC: write failed: ${U}`,w.verbose),[]}}var iY,J$,l2="# rpx",rH="# Added by rpx",O8,Vj=!1;var hj=a(()=>{g$();z0();iY=pH(nH);J$=d$.platform==="win32"?p2.join(d$.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",O8=new Set(["127.0.0.1","::1"])});import*as V$ from"node:fs/promises";import{homedir as sH}from"node:os";import*as Oj from"node:path";function o2(){return Oj.join(sH(),".stacks","rpx")}function _j(w=o2()){return Oj.join(w,oH)}async function x8(w=o2()){try{let $=await V$.readFile(_j(w),"utf8"),Y=JSON.parse($);if(Y.version!==D8||!Array.isArray(Y.resolvers))return null;return{version:D8,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($){if($.code==="ENOENT")return null;throw $}}async function e2(w,$){await V$.mkdir(w,{recursive:!0}),await V$.writeFile(_j(w),`${JSON.stringify($,null,2)}
291
- `,"utf8")}async function Dj(w){await V$.rm(_j(w),{force:!0})}function w6(w){let $=w.trim().toLowerCase().replace(/\.$/,"");if(!$||$.includes("127.0.0.1"))return null;if($==="localhost"||$.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test($))return null;if(!/^[a-z0-9.-]+$/.test($))return null;return $}function eH(w){let $=w6(w);if(!$)return null;let Y=$.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function xj(w){let $=new Set;for(let Y of w){let A=eH(Y);if(A)$.add(A)}return Array.from($).sort()}function kj(w){let $=new Set;for(let Y of w){let A=w6(Y);if(A)$.add(A)}return Array.from($).sort()}var D8=1,oH="dns-state.json",s2;var $6=a(()=>{s2=["com","test","dev","app","page","local","localhost","example","invalid"]});var Z8={};tj(Z8,{tearDownDevelopmentDns:()=>n$,syncDevelopmentDnsFromRegistry:()=>g1,stopDnsServer:()=>Zj,startDnsServer:()=>Q6,setupResolver:()=>QR,setupDevelopmentDns:()=>uj,resolverFilePath:()=>m1,removeResolver:()=>zR,removeLegacyTldResolvers:()=>bj,reconcileStaleDevelopmentDns:()=>l$,isRpxDevelopmentDnsAnswering:()=>f6,isDnsServerRunning:()=>AR,contentLooksLikeRpxResolver:()=>z6,RPX_RESOLVER_MARKER:()=>J6,DNS_PORT:()=>mY});import Y6 from"node:dgram";import*as A6 from"node:fs/promises";import*as X6 from"node:path";import*as U$ from"node:process";function W6(w){return{id:w.readUInt16BE(0),flags:w.readUInt16BE(2),qdcount:w.readUInt16BE(4),ancount:w.readUInt16BE(6),nscount:w.readUInt16BE(8),arcount:w.readUInt16BE(10)}}function j6(w,$,Y=0){let A=[],X=$,J=0;while(!0){if(X>=w.length||++J>128)break;let U=w[X];if(U===0){X++;break}if((U&192)===192){if(X+1>=w.length||Y>=10)break;let j=w.readUInt16BE(X)&16383,{name:W}=j6(w,j,Y+1);if(W)A.push(W);X+=2;break}if(X++,X+U>w.length)break;A.push(w.subarray(X,X+U).toString("ascii")),X+=U}return{name:A.join("."),newOffset:X}}function wR(w,$){let{name:Y,newOffset:A}=j6(w,$),X=w.readUInt16BE(A),J=w.readUInt16BE(A+2);return{question:{name:Y,type:X,class:J},newOffset:A+4}}function vY(w){let $=w.split("."),Y=[];for(let A of $)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function $R(w,$,Y){let A=[],X=Buffer.alloc(12);X.writeUInt16BE(w,0),X.writeUInt16BE(33152,2),X.writeUInt16BE(1,4),X.writeUInt16BE(1,6),X.writeUInt16BE(0,8),X.writeUInt16BE(0,10),A.push(X),A.push(vY($.name));let J=Buffer.alloc(4);J.writeUInt16BE($.type,0),J.writeUInt16BE($.class,2),A.push(J),A.push(vY($.name));let U=Buffer.alloc(10);if(U.writeUInt16BE($.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),$.type===1){U.writeUInt16BE(4,8),A.push(U);let j=Y.split(".").map((W)=>Number.parseInt(W,10));A.push(Buffer.from(j))}else if($.type===28)U.writeUInt16BE(16,8),A.push(U),A.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return X.writeUInt16BE(33155,2),X.writeUInt16BE(0,6),Buffer.concat([X,vY($.name),J]);return Buffer.concat(A)}function YR(w,$){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE(w,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(vY($.name));let X=Buffer.alloc(4);return X.writeUInt16BE($.type,0),X.writeUInt16BE($.class,2),Y.push(X),Buffer.concat(Y)}async function Q6(w,$){if(U$.platform!=="darwin")return!1;let Y=kj(w);if(Y.length===0)return!1;if(r0){for(let A of Y)k8.add(A);return E("dns","DNS server already running — merged domains",$),!0}return k8=new Set(Y),new Promise((A)=>{r0=Y6.createSocket("udp4"),r0.on("error",(X)=>{E("dns",`DNS server error: ${X.message}`,$),r0?.close(),r0=null,A(!1)}),r0.on("message",(X,J)=>{try{let U=W6(X),{question:j}=wR(X,12);E("dns",`Query for ${j.name} type ${j.type} from ${J.address}`,$);let W=j.name.toLowerCase(),Q=!1;for(let z of k8)if(W===z||W.endsWith(`.${z}`)){Q=!0;break}let f;if(Q&&(j.type===1||j.type===28))f=$R(U.id,j,"127.0.0.1"),E("dns",`Responding with localhost for ${j.name}`,$);else f=YR(U.id,j),E("dns",`NXDOMAIN for ${j.name}`,$);r0?.send(f,J.port,J.address)}catch(U){E("dns",`Error processing DNS query: ${U}`,$)}}),r0.on("listening",()=>{let X=r0?.address();E("dns",`DNS server listening on ${X?.address}:${X?.port}`,$),A(!0)});try{r0.bind(mY,"127.0.0.1")}catch(X){E("dns",`Failed to bind DNS server: ${X}`,$),A(!1)}})}function Zj(w){if(r0)E("dns","Stopping DNS server",w),r0.close(),r0=null,k8=new Set}function AR(){return r0!==null}async function f6(w,$=500){let Y=w.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let X=Y6.createSocket("udp4"),J=setTimeout(()=>{X.close(),A(!1)},$);X.on("message",(j)=>{clearTimeout(J),X.close();try{let W=W6(j);A(W.ancount>0)}catch{A(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),A(!1)});let U=XR(Y,1);X.send(U,mY,"127.0.0.1",(j)=>{if(j)clearTimeout(J),X.close(),A(!1)})})}function XR(w,$){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([vY(w),Buffer.from([0,$,0,1])]);return Buffer.concat([Y,A])}function JR(){return`${J6}
285
+ `,removed:Y,stalePids:[...A]}}async function Sj(w){try{return await O8.promises.readFile(A$,"utf-8")}catch{return E("hosts","Reading hosts file requires elevated permissions, using sudo",w),a2(`cat "${A$}"`)}}async function hj(w,$){let Y=t2.join(rH.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await O8.promises.writeFile(Y,w,"utf8"),await a2(`cat "${Y}" | tee "${A$}" > /dev/null`)}finally{await O8.promises.unlink(Y).catch((A)=>{E("hosts",`Failed to remove temporary file: ${A}`,$)})}}async function iY(w,$){let Y=w.filter((X)=>!p2(X)),A=w.filter((X)=>p2(X));if(A.length>0)E("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,$);if(Y.length===0)return;E("hosts",`Adding hosts: ${Y.join(", ")}`,$),E("hosts",`Using hosts file at: ${A$}`,$);try{let X;try{X=await Sj($)}catch(Q){throw console.log(" Could not read hosts file — skipping hosts setup"),E("hosts",`sudo read also failed: ${Q}`,$),Error(`Cannot read hosts file: ${Q}`)}let J=X.split(`
286
+ `),U=Y.filter((Q)=>!J.some((f)=>s2(f,Q)));if(U.length===0){E("hosts","All hosts already exist in hosts file",$);return}let j=m$.pid,W=U.map((Q)=>`
287
+ 127.0.0.1 ${Q} ${r2}:pid=${j}
288
+ ::1 ${Q} ${r2}:pid=${j}`).join(`
289
+ `);try{await hj(X+W,$),console.log(` Hosts updated: ${U.join(", ")}`)}catch(Q){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),U.forEach((f)=>{console.log(` 127.0.0.1 ${f}`),console.log(` ::1 ${f}`)}),console.log(` Or run: sudo nano ${A$}`)}}catch(X){E("hosts",`Failed to manage hosts file: ${X.message}`,$)}}async function o2(w,$){E("hosts",`Removing hosts: ${w.join(", ")}`,$);try{let Y;try{Y=await Sj($)}catch(J){throw E("hosts",`sudo read also failed: ${J}`,$),Error(`Cannot read hosts file: ${J}`)}let{content:A,removed:X}=sH(Y,w);if(X.length===0){E("hosts","No matching rpx-managed hosts found to remove",$);return}try{await hj(A,$),E("hosts",`Hosts removed successfully: ${X.join(", ")}`,$)}catch(J){E("hosts","Could not clean up hosts file automatically",$)}}catch(Y){E("hosts",`Failed to clean up hosts file: ${Y.message}`,$)}}async function bY(w,$){E("hosts",`Checking hosts: ${w}`,$);let Y;try{Y=await O8.promises.readFile(A$,"utf-8")}catch(X){E("hosts",`Error reading hosts file: ${X}`,$);try{let J=F$(),U;if(J)U=`echo '${J}' | sudo -S cat "${A$}" 2>/dev/null`;else U=`sudo -n cat "${A$}" 2>/dev/null || cat "${A$}" 2>/dev/null || echo ""`;let{stdout:j}=await PY(U);Y=j}catch(J){return E("hosts",`Cannot read hosts file, assuming entries don't exist: ${J}`,$),w.map(()=>!1)}}let A=Y.split(`
290
+ `);return w.map((X)=>A.some((J)=>s2(J,X)))}async function uY(w={}){let $=w.isAlive??Xw,Y;try{Y=await Sj(w.verbose)}catch(U){return E("hosts",`stale hosts GC: cannot read hosts file: ${U}`,w.verbose),[]}let{content:A,removed:X,stalePids:J}=oH(Y,$);if(X.length===0)return[];try{return await hj(A,w.verbose),E("hosts",`stale hosts GC: removed ${X.join(", ")} (dead pid(s): ${J.join(", ")})`,w.verbose),[...new Set(X)]}catch(U){return E("hosts",`stale hosts GC: write failed: ${U}`,w.verbose),[]}}var PY,A$,r2="# rpx",aH="# Added by rpx",_8,Lj=!1;var Oj=s(()=>{v$();z0();PY=tH(pH);A$=m$.platform==="win32"?t2.join(m$.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",_8=new Set(["127.0.0.1","::1"])});import*as C$ from"node:fs/promises";import{homedir as eH}from"node:os";import*as _j from"node:path";function w6(){return _j.join(eH(),".stacks","rpx")}function Dj(w=w6()){return _j.join(w,wR)}async function k8(w=w6()){try{let $=await C$.readFile(Dj(w),"utf8"),Y=JSON.parse($);if(Y.version!==x8||!Array.isArray(Y.resolvers))return null;return{version:x8,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($){if($.code==="ENOENT")return null;throw $}}async function $6(w,$){await C$.mkdir(w,{recursive:!0}),await C$.writeFile(Dj(w),`${JSON.stringify($,null,2)}
291
+ `,"utf8")}async function xj(w){await C$.rm(Dj(w),{force:!0})}function Y6(w){let $=w.trim().toLowerCase().replace(/\.$/,"");if(!$||$.includes("127.0.0.1"))return null;if($==="localhost"||$.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test($))return null;if(!/^[a-z0-9.-]+$/.test($))return null;return $}function $R(w){let $=Y6(w);if(!$)return null;let Y=$.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function kj(w){let $=new Set;for(let Y of w){let A=$R(Y);if(A)$.add(A)}return Array.from($).sort()}function Zj(w){let $=new Set;for(let Y of w){let A=Y6(Y);if(A)$.add(A)}return Array.from($).sort()}var x8=1,wR="dns-state.json",e2;var A6=s(()=>{e2=["com","test","dev","app","page","local","localhost","example","invalid"]});var P8={};sj(P8,{tearDownDevelopmentDns:()=>g$,syncDevelopmentDnsFromRegistry:()=>v1,stopDnsServer:()=>Pj,startDnsServer:()=>z6,setupResolver:()=>zR,setupDevelopmentDns:()=>cj,resolverFilePath:()=>c1,removeResolver:()=>GR,removeLegacyTldResolvers:()=>uj,reconcileStaleDevelopmentDns:()=>d$,isRpxDevelopmentDnsAnswering:()=>B6,isDnsServerRunning:()=>JR,contentLooksLikeRpxResolver:()=>G6,RPX_RESOLVER_MARKER:()=>W6,DNS_PORT:()=>vY});import X6 from"node:dgram";import*as J6 from"node:fs/promises";import*as U6 from"node:path";import*as X$ from"node:process";function Q6(w){return{id:w.readUInt16BE(0),flags:w.readUInt16BE(2),qdcount:w.readUInt16BE(4),ancount:w.readUInt16BE(6),nscount:w.readUInt16BE(8),arcount:w.readUInt16BE(10)}}function f6(w,$,Y=0){let A=[],X=$,J=0;while(!0){if(X>=w.length||++J>128)break;let U=w[X];if(U===0){X++;break}if((U&192)===192){if(X+1>=w.length||Y>=10)break;let j=w.readUInt16BE(X)&16383,{name:W}=f6(w,j,Y+1);if(W)A.push(W);X+=2;break}if(X++,X+U>w.length)break;A.push(w.subarray(X,X+U).toString("ascii")),X+=U}return{name:A.join("."),newOffset:X}}function YR(w,$){let{name:Y,newOffset:A}=f6(w,$),X=w.readUInt16BE(A),J=w.readUInt16BE(A+2);return{question:{name:Y,type:X,class:J},newOffset:A+4}}function cY(w){let $=w.split("."),Y=[];for(let A of $)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function AR(w,$,Y){let A=[],X=Buffer.alloc(12);X.writeUInt16BE(w,0),X.writeUInt16BE(33152,2),X.writeUInt16BE(1,4),X.writeUInt16BE(1,6),X.writeUInt16BE(0,8),X.writeUInt16BE(0,10),A.push(X),A.push(cY($.name));let J=Buffer.alloc(4);J.writeUInt16BE($.type,0),J.writeUInt16BE($.class,2),A.push(J),A.push(cY($.name));let U=Buffer.alloc(10);if(U.writeUInt16BE($.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),$.type===1){U.writeUInt16BE(4,8),A.push(U);let j=Y.split(".").map((W)=>Number.parseInt(W,10));A.push(Buffer.from(j))}else if($.type===28)U.writeUInt16BE(16,8),A.push(U),A.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return X.writeUInt16BE(33155,2),X.writeUInt16BE(0,6),Buffer.concat([X,cY($.name),J]);return Buffer.concat(A)}function XR(w,$){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE(w,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(cY($.name));let X=Buffer.alloc(4);return X.writeUInt16BE($.type,0),X.writeUInt16BE($.class,2),Y.push(X),Buffer.concat(Y)}async function z6(w,$){if(X$.platform!=="darwin")return!1;let Y=Zj(w);if(Y.length===0)return!1;if(t0){for(let A of Y)Z8.add(A);return E("dns","DNS server already running — merged domains",$),!0}return Z8=new Set(Y),new Promise((A)=>{t0=X6.createSocket("udp4"),t0.on("error",(X)=>{E("dns",`DNS server error: ${X.message}`,$),t0?.close(),t0=null,A(!1)}),t0.on("message",(X,J)=>{try{let U=Q6(X),{question:j}=YR(X,12);E("dns",`Query for ${j.name} type ${j.type} from ${J.address}`,$);let W=j.name.toLowerCase(),Q=!1;for(let z of Z8)if(W===z||W.endsWith(`.${z}`)){Q=!0;break}let f;if(Q&&(j.type===1||j.type===28))f=AR(U.id,j,"127.0.0.1"),E("dns",`Responding with localhost for ${j.name}`,$);else f=XR(U.id,j),E("dns",`NXDOMAIN for ${j.name}`,$);t0?.send(f,J.port,J.address)}catch(U){E("dns",`Error processing DNS query: ${U}`,$)}}),t0.on("listening",()=>{let X=t0?.address();E("dns",`DNS server listening on ${X?.address}:${X?.port}`,$),A(!0)});try{t0.bind(vY,"127.0.0.1")}catch(X){E("dns",`Failed to bind DNS server: ${X}`,$),A(!1)}})}function Pj(w){if(t0)E("dns","Stopping DNS server",w),t0.close(),t0=null,Z8=new Set}function JR(){return t0!==null}async function B6(w,$=500){let Y=w.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let X=X6.createSocket("udp4"),J=setTimeout(()=>{X.close(),A(!1)},$);X.on("message",(j)=>{clearTimeout(J),X.close();try{let W=Q6(j);A(W.ancount>0)}catch{A(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),A(!1)});let U=UR(Y,1);X.send(U,vY,"127.0.0.1",(j)=>{if(j)clearTimeout(J),X.close(),A(!1)})})}function UR(w,$){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([cY(w),Buffer.from([0,$,0,1])]);return Buffer.concat([Y,A])}function WR(){return`${W6}
292
292
  nameserver 127.0.0.1
293
- port ${mY}
294
- `}function m1(w){return X6.join(U6,w)}function z6(w){return w.includes("127.0.0.1")&&w.includes(String(mY))}async function UR(w){try{return await A6.readFile(m1(w),"utf8")}catch($){if($.code==="ENOENT")return null;throw $}}async function Pj(w){if(U$.platform!=="darwin")return;let{execSudoSync:$,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (z0(),P1));if(!A()&&!Y()){E("dns","Cannot flush DNS cache without SUDO_PASSWORD",w);return}try{$("dscacheutil -flushcache"),$("killall -HUP mDNSResponder 2>/dev/null || true"),E("dns","DNS cache flushed",w)}catch(X){E("dns",`Could not flush DNS cache: ${X}`,w)}}function B6(w){if(!/^[a-z0-9.-]+$/.test(w))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(w)}`)}async function WR(w,$){B6(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (z0(),P1)),A=JR().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${U6} && printf "%b" "${A}" > ${m1(w)}'`;Y(X),E("dns",`Created ${m1(w)}`,$)}async function jR(w,$){B6(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (z0(),P1));Y(`rm -f ${m1(w)}`),E("dns",`Removed ${m1(w)}`,$)}async function QR(w,$){return uj({domains:$??[],verbose:w})}async function fR(w,$){if(U$.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (z0(),P1));if(!A()&&!Y())return E("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;try{for(let X of w)await WR(X,$);return await Pj($),!0}catch(X){return E("dns",`Failed to create resolver file: ${X}`,$),!1}}async function ij(w,$){if(U$.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (z0(),P1));if(!A()&&!Y())return;try{for(let X of w)await jR(X,$);await Pj($)}catch(X){E("dns",`Failed to remove resolver files: ${X}`,$)}}async function bj(w){if(U$.platform!=="darwin")return[];let $=[];for(let Y of s2){let A=await UR(Y);if(A&&z6(A))await ij([Y],w),$.push(Y)}return $}async function uj(w){let $=w.rpxDir??V0(),Y=kj(w.domains);if(Y.length===0)return!1;let A=xj(Y),X=await Q6(Y,w.verbose);if(!X){let j=Y[0];if(j&&await f6(j))X=!0;else E("dns","Dev DNS server not available on 127.0.0.1:15353",w.verbose)}if(!X)return!1;if(!await fR(A,w.verbose))return!1;let U={version:D8,resolvers:A,domains:Y,ownerPid:w.ownerPid??U$.pid,updatedAt:new Date().toISOString()};return await e2($,U),!0}async function g1(w,$={}){let Y=w.map((W)=>W.to).filter(Boolean),A=$.rpxDir??V0(),X=xj(Y),j=((await x8(A))?.resolvers??[]).filter((W)=>!X.includes(W));if(j.length>0)await ij(j,$.verbose);if(X.length===0){Zj($.verbose),await Dj(A);return}await uj({domains:Y,rpxDir:A,verbose:$.verbose,ownerPid:$.ownerPid??U$.pid})}async function n$(w={}){let $=w.rpxDir??V0();Zj(w.verbose);let A=(await x8($))?.resolvers??[];await ij(A,w.verbose),await bj(w.verbose),await Dj($)}async function zR(w){await n$({verbose:w})}async function l$(w={}){let $=w.rpxDir??V0(),Y=await x8($),A=Y?.ownerPid!=null&&Yw(Y.ownerPid);if(Y&&!A){E("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,w.verbose),await n$(w);return}let X=await bj(w.verbose);if(X.length>0)E("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,w.verbose);await Pj(w.verbose)}var mY=15353,J6="# managed-by: rpx",U6="/etc/resolver",r0=null,k8;var gY=a(()=>{P8();$6();g$();z0();k8=new Set});import{spawn as F6}from"node:child_process";import*as i0 from"node:fs/promises";import{homedir as T6}from"node:os";import*as hw from"node:path";import*as y from"node:process";function V0(){return hw.join(T6(),".stacks","rpx")}function S$(w=V0()){return hw.join(w,"daemon.pid")}async function L$(w=V0()){try{let $=await i0.readFile(S$(w),"utf8"),Y=Number.parseInt($.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch($){if($.code==="ENOENT")return null;throw $}}async function c8(w=V0()){let $=await L$(w);return $!==null&&Yw($)}async function N6(w=V0()){await i0.mkdir(w,{recursive:!0});let $=S$(w);while(!0){try{let A=await i0.open($,"wx");try{await A.write(`${y.pid}
295
- `)}finally{await A.close()}return $}catch(A){if(A.code!=="EEXIST")throw A}let Y=await L$(w);if(Y!==null&&Yw(Y))throw Error(`rpx daemon already running (pid=${Y})`);await i0.unlink($).catch(()=>{})}}async function d1(w=V0()){await i0.unlink(S$(w)).catch(()=>{})}function u8(w){for(let[$,Y]of b8)if(!w.has($))b1(Y),b8.delete($)}function GR(w,$){let Y=B2($??"localhost:1");if(w.upstreams.length!==Y.length)return!1;return w.upstreams.every((A,X)=>A.url===Y[X])}function q6(w){let $=w.cleanUrls??!1,Y=X$(w.path),A=VY(w.auth);if(w.static)return{static:q8(w.static,$),cleanUrls:$,basePath:Y,auth:A};let X=w.from??"localhost:1",J=u$(X),U=new URL(J.startsWith("http")?J:`http://${J}`),j=b8.get(w.id);if(j&&!GR(j,X))b1(j),j=void 0;if(!j)j=MY(X,w.loadBalancer),IY(j),b8.set(w.id,j);return{sourceHost:U.host,upstreamPool:j,cleanUrls:$,changeOrigin:w.changeOrigin??!1,pathRewrites:w.pathRewrites,basePath:Y,auth:A}}function ER(w){return w.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??w[0]??"rpx.localhost"}async function i8(w,$,Y=[],A=!1){let X=await Bw($,w.verbose),J=[...new Set([...X.map((f)=>f.to).filter(Boolean),...Y])],U=ER(J),j=[...new Set([U,...J,"rpx.localhost"])],W=W2(J,U,w.verbose);if(typeof w.https==="object"&&typeof W.https==="object")W.https={...W.https,...w.https};let Q=await y$(W);if(Q&&(A||!KW(jj,j)))E("daemon",`regenerating shared cert for host(s): ${j.join(", ")}`,w.verbose),Qj(),Q=null;if(!Q)E("daemon","no usable cert on disk, generating one via tlsx",w.verbose),await HY({...W,forceRegenerate:!0}),Q=await y$(W);if(!Q)throw Error("failed to bootstrap TLS for rpx daemon");return Q}async function KR(w,$,Y,A){let X=y.env.SUDO_PASSWORD,J=y.env.HOME??T6(),U=[y.execPath,...y.argv.slice(1)],j=[`HOME=${J}`,`PATH=${y.env.PATH??""}`];if(A)j.push("RPX_VERBOSE=1");for(let[T,K]of Object.entries(y.env))if(K!==void 0&&T!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(T))j.push(`${T}=${K}`);let W=X?["-S","-p","","env",...j,...U]:["-n","env",...j,...U];E("daemon",`elevating daemon via sudo for privileged ports ${$}/${Y}`,A);let Q=F6("sudo",W,{detached:!0,stdio:["pipe","ignore","ignore"]}),f=null,z=null;if(Q.once("error",(T)=>{f=T}),Q.once("exit",(T)=>{z=T??0}),X&&Q.stdin)Q.stdin.write(`${X}
296
- `),Q.stdin.end();Q.unref();let B=S$(w),G=Date.now()+15000;while(Date.now()<G){if(f)throw f;let T=await L$(w);if(T!==null&&Yw(T)){if(A)H.success(`rpx daemon elevated to root (pid=${T}, https on :${$})`);return{httpsPort:$,httpPort:Y,pidPath:B,done:Promise.resolve(),stop:async()=>{try{y.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(z!==null&&z!==0)throw Error(`rpx daemon could not elevate to bind :${$} (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=${w})`)}function cj(){if(G6)return;G6=!0,y.on("uncaughtException",(w)=>{H.error(`rpx daemon: uncaught exception (continuing): ${w?.stack??w}`)}),y.on("unhandledRejection",(w)=>{H.error(`rpx daemon: unhandled rejection (continuing): ${w}`)})}function H6(w,$,Y){let A;try{A=new URL(w.url)}catch{return new Response("Bad Request",{status:400})}let X=(w.headers.get("host")??A.hostname).split(":")[0];if(A.pathname.startsWith("/.well-known/acme-challenge/")){if($){let J=$.challengeStore.handlePath(A.pathname);if(J!==void 0)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(Y){let J=R8(Y,A.pathname);if(J!=null)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if($)return new Response("challenge not found",{status:404})}if($&&!$.hasCert(X))$.ensureCert(X).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${X}${A.pathname}${A.search}`}})}async function R6(w={}){cj();let $=w.verbose??!1,Y=w.rpxDir??V0(),A=w.registryDir??hw.join(Y,"registry.d"),X=w.httpsPort??443,J=w.httpPort??80,U=w.hostname??"0.0.0.0",j=w.gcIntervalMs??BR;if(y.env.RPX_DAEMON_WORKER==="1")return NR({rpxDir:y.env.RPX_WORKER_RPXDIR??Y,registryDir:y.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(y.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:y.env.RPX_WORKER_HOSTNAME??U,verbose:y.env.RPX_WORKER_VERBOSE==="1"||$});let W=X>0&&X<1024||J>0&&J<1024,Q=typeof y.getuid==="function"&&y.getuid()===0;if(y.platform!=="win32"&&W&&!Q)return KR(Y,X,J,$);let f=Math.max(1,w.workers??(Number.parseInt(y.env.RPX_WORKERS??"",10)||1));if(f>1){if(w.onDemandSites?.enabled)H.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return qR(w,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:$,gcIntervalMs:j,workers:f})}let z=await N6(Y),B=new Map,G=(I,D)=>_Y(B,I,D);function T(I){B=OY(I.map((Lw)=>({host:Lw.to,path:Lw.path,route:q6(Lw)}))),u8(new Set(I.map((Lw)=>Lw.id)));let D=Array.from(B.keys());E("daemon",`routing table now covers ${D.length} host(s): ${D.join(", ")||"<empty>"}`,$)}await ZY(A,$).catch((I)=>{E("daemon",`initial gc failed: ${I}`,$)}),await cY({verbose:$}).catch((I)=>{E("daemon",`stale hosts GC on start failed: ${I}`,$)});let K=await Bw(A,$);T(K),await l$({rpxDir:Y,verbose:$}).catch((I)=>{E("daemon",`DNS reconcile on start failed: ${I}`,$)}),await g1(K,{rpxDir:Y,verbose:$,ownerPid:y.pid}).catch((I)=>{E("daemon",`DNS setup on start failed: ${I}`,$)});let F=[];if(w.productionCerts){if(F=await xY(w.productionCerts,$),$&&F.length>0)H.info(`SNI: serving ${F.length} real cert(s): ${F.map((I)=>I.serverName).join(", ")}`)}let N=new Set,R=null,L;if(w.onDemandSites?.enabled){if(R=new Cj({resolver:JU(w.onDemandSites),registryDir:A,rpxDir:Y,verbose:$,startupTimeoutMs:w.onDemandSites.startupTimeoutMs,isHostRoutable:(I)=>Kj(B,I)!==void 0,onSiteActivating:(I)=>{Cw(I)}}),L=async(I)=>{let D=await R.onRequest(I);switch(D.kind){case"ready":return{retry:!0};case"starting":return g2({host:D.host,sinceMs:D.sinceMs,logTail:D.logTail});case"failed":return d2({host:D.host,error:D.error,logTail:D.logTail});case"unknown":default:return}},$)H.info("rpx: on-demand sites enabled")}let V=SY(G,$,L),q=hY($),M=null;if(F.length===0)M=await i8(w,A);let C=w.onDemandTls,O=C?.enabled?new u1({config:C,certsDir:C.certsDir??w.productionCerts?.certsDir??hw.join(Y,"on-demand-certs"),initial:F,verbose:$,onCertAdded:(I)=>{if(kY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",$),setTimeout(()=>y.kill(y.pid,"SIGTERM"),10).unref();else kw(I)}}):null;function J0(I){if(I.length>0)return v$(I.map((D)=>({serverName:D.serverName,cert:D.cert,key:D.key})));return v$({key:M.key,cert:M.cert,ca:M.ca,requestCert:!1,rejectUnauthorized:!1})}function u0(I){return Bun.serve({port:X,hostname:U,reusePort:NY(),tls:J0(I),fetch(D,Lw){return V(D,Lw)},websocket:q,error(D){return E("daemon",`https server error: ${D}`,$),new Response(`Server Error: ${D.message}`,{status:500})}})}let Gw=(I)=>[...new Set(I.map((D)=>D.to).filter(Boolean))],h$=(I)=>{if(!M)return F;return U2([...Gw(I),...N,"rpx.localhost"],M)},Dw=u0(O?O.sniEntries():F.length>0?F:h$(K)),xw=null,Ew=!1;async function kw(I){if(Vw)return;if(xw=I,Ew)return;Ew=!0;try{while(!Vw&&xw){let D=xw;xw=null,E("daemon",`rebuilding :443 with ${D.length} SNI cert(s)`,$),Dw.stop(!1);let Lw,wJ=!1,rj=60,b6=500;for(let $J=0;!Vw&&!wJ;$J++)try{Dw=u0(D),wJ=!0;break}catch(u6){if(Lw=u6,$J>=rj)break;await new Promise((c6)=>setTimeout(c6,Math.min(25*2**Math.min($J,4),b6)))}if(!wJ)H.error(`rpx: CRITICAL — could not rebind :443 after ${rj} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Lw?.message}`)}}finally{Ew=!1}}let t0=null;if(J>0)t0=Bun.serve({port:J,hostname:U,fetch(I){return H6(I,O,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if($)H.success(`rpx daemon listening on https://${U}:${X}${t0?` (http→https on :${J})`:""}`),H.info(`pid file: ${z}`),H.info(`registry: ${A}`);async function _(I){if(Vw||F.length>0||O||!M)return;try{M=await i8(w,A,[...N]),await kw(h$(I))}catch(D){E("daemon",`TLS sync on registry change failed: ${D}`,$)}}async function Cw(I){if(Vw||F.length>0||O||!M||!I)return;if(N.has(I))return;N.add(I);try{M=await i8(w,A,[...N],!0);let D=await Bw(A,$);await kw(h$(D))}catch(D){E("daemon",`dev cert refresh for ${I} failed: ${D}`,$)}}let n1=S8((I)=>{T(I),_(I),g1(I,{rpxDir:Y,verbose:$,ownerPid:y.pid}).catch((D)=>{E("daemon",`DNS sync on registry change failed: ${D}`,$)})},{dir:A,verbose:$}),p$=setInterval(()=>{ZY(A,$).then((I)=>{if(I>0)E("daemon",`gc reaped ${I} stale entries`,$)}).catch((I)=>{E("daemon",`periodic gc failed: ${I}`,$)}),cY({verbose:$}).then((I)=>{if(I.length>0)E("daemon",`gc reaped stale hosts entries: ${I.join(", ")}`,$)}).catch((I)=>{E("daemon",`periodic hosts gc failed: ${I}`,$)})},j);if(typeof p$.unref==="function")p$.unref();let Vw=!1,l1,r$=new Promise((I)=>{l1=I});async function e8(){if(Vw)return r$;if(Vw=!0,clearInterval(p$),n1.close(),await R?.stopAll().catch((I)=>{E("daemon",`site supervisor stopAll failed: ${I}`,$)}),Dw.stop(!1),t0?.stop(!1),await n$({rpxDir:Y,verbose:$}).catch((I)=>{E("daemon",`DNS teardown failed: ${I}`,$)}),u8(new Set),await d1(Y),$)H.info("rpx daemon stopped");return l1(),r$}let pj=(I)=>{E("daemon",`received ${I}, shutting down`,$),e8().catch(()=>{})};return y.once("SIGINT",pj),y.once("SIGTERM",pj),{stop:e8,done:r$,httpsPort:typeof Dw.port==="number"?Dw.port:X,httpPort:t0&&typeof t0.port==="number"?t0.port:J,pidPath:z,ensureCert:(I)=>O?O.ensureCert(I):Promise.resolve(!1),listSites:()=>R?.list()??[]}}function vj(w){return hw.join(w,"cluster-sni.json")}async function E6(w,$,Y){let A=vj(w),X=`${A}.${y.pid}.tmp`;await i0.writeFile(X,JSON.stringify({sni:$,dev:Y}),"utf8"),await i0.rename(X,A)}async function K6(w){try{return JSON.parse(await i0.readFile(vj(w),"utf8"))}catch{return{sni:[],dev:null}}}function FR(w){if(w.sni.length>0)return v$(w.sni.map(($)=>({serverName:$.serverName,cert:$.cert,key:$.key})));if(w.dev)return v$({key:w.dev.key,cert:w.dev.cert,ca:w.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function TR(){let w=y.execPath,$=y.env.RPX_WORKER_BIN;if($)return[w,$,"daemon:start"];let Y=hw.basename(w).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&y.argv[1])return[w,y.argv[1],"daemon:start"];return[w,"daemon:start"]}async function NR(w){cj();let{rpxDir:$,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=w,U=new Map,j=(M,C)=>_Y(U,M,C),W=(M)=>{U=OY(M.map((C)=>({host:C.to,path:C.path,route:q6(C)}))),u8(new Set(M.map((C)=>C.id)))};W(await Bw(Y,J));let Q=SY(j,J),f=hY(J),z=!1,B=(M)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:FR(M),fetch(C,O){return Q(C,O)},websocket:f,error(C){return E("daemon",`worker https error: ${C}`,J),new Response(`Server Error: ${C.message}`,{status:500})}}),G=B(await K6($));async function T(){if(z)return;let M=await K6($),C=null;for(let J0=0;J0<20&&!z;J0++)try{C=B(M);break}catch{await new Promise((u0)=>setTimeout(u0,25))}if(!C){E("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let O=G;G=C,O.stop(!1)}let K=S8((M)=>W(M),{dir:Y,verbose:J}),F=()=>{T().catch(()=>{})};y.on("SIGHUP",F);let N=()=>{let M=y.removeListener??y.off;if(typeof M==="function")M.call(y,"SIGHUP",F)},R,L=new Promise((M)=>{R=M});async function V(){if(z)return L;return z=!0,N(),K.close(),G.stop(!1),u8(new Set),R(),L}let q=()=>{V().then(()=>y.exit(0)).catch(()=>y.exit(0))};if(y.once("SIGTERM",q),y.once("SIGINT",q),J)H.success(`rpx worker (pid ${y.pid}) serving :${A}`);return{stop:V,done:L,httpsPort:typeof G.port==="number"?G.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function qR(w,$){cj();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:j,gcIntervalMs:W,workers:Q}=$,f=await N6(Y),z=[];if(w.productionCerts)z=await xY(w.productionCerts,j);let B=null;if(z.length===0)B=await i8(w,A);let G=B?{key:B.key,cert:B.cert,ca:Array.isArray(B.ca)?B.ca.join(`
297
- `):B.ca}:null,T=!1,K=[];function F(_){for(let Cw of K)try{Cw.kill(_)}catch{}}async function N(_){await E6(Y,_,G),F("SIGHUP")}let R=w.onDemandTls,L=R?.enabled?new u1({config:R,certsDir:R.certsDir??w.productionCerts?.certsDir??hw.join(Y,"on-demand-certs"),initial:z,verbose:j,onCertAdded:(_)=>{if(kY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",j),setTimeout(()=>y.kill(y.pid,"SIGTERM"),10).unref();else N(_)}}):null;await E6(Y,L?L.sniEntries():z,G);let V=await Bw(A,j);await l$({rpxDir:Y,verbose:j}).catch((_)=>{E("daemon",`DNS reconcile on start failed: ${_}`,j)}),await g1(V,{rpxDir:Y,verbose:j,ownerPid:y.pid}).catch((_)=>{E("daemon",`DNS setup on start failed: ${_}`,j)}),await ZY(A,j).catch(()=>{}),await cY({verbose:j}).catch(()=>{});let q=S8((_)=>{g1(_,{rpxDir:Y,verbose:j,ownerPid:y.pid}).catch((Cw)=>{E("daemon",`DNS sync on registry change failed: ${Cw}`,j)})},{dir:A,verbose:j}),M=setInterval(()=>{ZY(A,j).catch(()=>{}),cY({verbose:j}).catch(()=>{})},W);M.unref?.();let C=null;if(J>0)C=Bun.serve({port:J,hostname:U,fetch(_){return H6(_,L,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let O=10,J0=60000,u0=30000,Gw=0,h$=Date.now();function Dw(){if(T)return;let _={...y.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:j?"1":"0"},Cw=Bun.spawn(TR(),{env:_,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(n1,p$){if(T)return;let Vw=K.indexOf(n1);if(Vw!==-1)K.splice(Vw,1);let l1=Date.now();if(l1-h$>J0)h$=l1,Gw=0;if(Gw++,Gw>O){H.error(`rpx: worker keeps exiting (code ${p$}); giving up after ${O} restarts in ${Math.round(J0/1000)}s`);return}let r$=Math.min(u0,100*2**Math.min(Gw,8));E("daemon",`worker exited (code ${p$}); respawning in ${r$}ms (restart ${Gw}/${O})`,j),setTimeout(Dw,r$).unref?.()}});K.push(Cw)}for(let _=0;_<Q;_++)Dw();if(j)H.success(`rpx coordinator listening on https://${U}:${X} via ${Q} worker(s)${C?` (http→https on :${J})`:""}`),H.info(`pid file: ${f}`);let xw,Ew=new Promise((_)=>{xw=_});async function kw(){if(T)return Ew;if(T=!0,clearInterval(M),q.close(),C?.stop(!1),F("SIGTERM"),await Promise.race([Promise.all(K.map((_)=>_.exited)),new Promise((_)=>setTimeout(_,3000))]),F("SIGKILL"),await n$({rpxDir:Y,verbose:j}).catch((_)=>{E("daemon",`DNS teardown failed: ${_}`,j)}),await d1(Y),await i0.unlink(vj(Y)).catch(()=>{}),j)H.info("rpx coordinator stopped");return xw(),Ew}let t0=(_)=>{E("daemon",`coordinator received ${_}, shutting down`,j),kw().catch(()=>{})};return y.once("SIGINT",t0),y.once("SIGTERM",t0),{stop:kw,done:Ew,httpsPort:X,httpPort:J,pidPath:f,ensureCert:(_)=>L?L.ensureCert(_):Promise.resolve(!1),listSites:()=>[]}}function HR(){let w=y.execPath,$=hw.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&y.argv[1])return[w,y.argv[1],"daemon:start"];return[w,"daemon:start"]}async function v8(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1;await l$({rpxDir:$,verbose:Y}).catch((f)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${f}`,Y)});let A=await L$($);if(A!==null&&Yw(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 d1($);await i0.mkdir($,{recursive:!0});let X=w.spawnCommand??HR();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=F6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??y.cwd(),env:w.spawnEnv?{...y.env,...w.spawnEnv}:y.env});J.unref();let U=null;J.once("error",(f)=>{U=f});let j=w.startupTimeoutMs??5000,W=w.pollIntervalMs??50,Q=Date.now()+j;while(Date.now()<Q){if(U)throw U;let f=await L$($);if(f!==null&&Yw(f))return E("daemon",`daemon registered with pid=${f}`,Y),{pid:f,spawned:!0};await new Promise((z)=>setTimeout(z,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${j}ms (rpxDir=${$})`)}async function M6(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1,A=w.timeoutMs??5000,X=w.pollIntervalMs??50,J=w.forceAfterTimeout??!0,U=await L$($);if(U===null||!Yw(U)){if(U!==null)await d1($);return await l$({rpxDir:$,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{y.kill(U,"SIGTERM")}catch(W){let Q=W.code;if(Q==="ESRCH")return await d1($),{stopped:!1,pid:U,forced:!1};if(Q==="EPERM")N$(`kill -TERM ${U}`);else throw W}let j=Date.now()+A;while(Date.now()<j){if(!Yw(U))return E("daemon",`daemon pid=${U} stopped cleanly`,Y),{stopped:!0,pid:U,forced:!1};await new Promise((W)=>setTimeout(W,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${A}ms`);E("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{y.kill(U,"SIGKILL")}catch(W){let Q=W.code;if(Q==="EPERM")N$(`kill -KILL ${U}`);else if(Q!=="ESRCH")throw W}return await d1($),await n$({rpxDir:$,verbose:Y}).catch((W)=>{E("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function y6(w={}){let $=w.rpxDir??V0();if(await c8($))return;await l$({rpxDir:$,verbose:w.verbose})}var BR=5000,b8,G6=!1;var P8=a(()=>{x$();fj();Gj();Ej();M8();Tj();Nj();UU();v2();H8();F8();g$();hj();gY();z0();b8=new Map});import{dirname as kR,join as ZR}from"node:path";import*as P0 from"node:process";import{fileURLToPath as PR}from"node:url";import{existsSync as n6}from"node:fs";import YJ from"node:fs/promises";import aj from"node:os";import AJ from"node:path";import O$ from"node:process";import{EventEmitter as l6}from"node:events";import W$ from"node:process";import sj from"node:process";import WJ from"node:process";import tY from"node:process";import t1 from"node:process";import wQ from"node:tty";import xG,{stdin as YM,stdout as AM}from"node:process";import YQ,{stdin as PG,stdout as iG}from"node:process";import bG from"node:readline";class XQ{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let w=aj.homedir(),$=AJ.join(w,".config","clapp");this.configPath=AJ.join($,"telemetry.json")}async isEnabled(){if(O$.env.DO_NOT_TRACK==="1"||O$.env.DO_NOT_TRACK==="true")return!1;if(O$.env.NO_TELEMETRY==="1"||O$.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let w=await this.loadConfig();if(w.enabled=!0,!w.userId)w.userId=this.generateUserId();await this.saveConfig(w)}async disable(){let w=await this.loadConfig();w.enabled=!1,await this.saveConfig(w)}async track(w,$){if(!await this.isEnabled())return;let A={event:w,...$,timestamp:Date.now(),platform:aj.platform(),nodeVersion:O$.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand(w,$){await this.track("command",{command:w,duration:$})}async trackError(w,$){await this.track("error",{error:w,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(w){return new Promise(($)=>setTimeout($,w))}async status(){let w=await this.loadConfig();return{enabled:w.enabled,doNotTrack:O$.env.DO_NOT_TRACK==="1"||O$.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:w.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(n6(this.configPath)){let w=await YJ.readFile(this.configPath,"utf-8");return this.config=JSON.parse(w),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(w){this.config=w;try{let $=AJ.dirname(this.configPath);await YJ.mkdir($,{recursive:!0}),await YJ.writeFile(this.configPath,JSON.stringify(w,null,2),"utf-8")}catch{}}generateUserId(){let w=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${w}-${$}`}}var dR=new XQ;function p6(w,$={}){let Y={_:[]},A=$.alias||{},X=new Set($.boolean||[]),J={};for(let j of Object.keys(A))for(let W of A[j])J[W]=j;for(let j of X)if(A[j])for(let W of A[j])X.add(W);function U(j,W){let Q=J[j]||j;if(Y[Q]=W,A[Q])for(let f of A[Q])Y[f]=W;if(J[j]&&A[J[j]])for(let f of A[J[j]])Y[f]=W;Y[j]=W}for(let j=0;j<w.length;j++){let W=w[j];if(W==="--"){Y._.push(...w.slice(j+1));break}if(W.startsWith("--")){let Q=W.indexOf("=");if(Q!==-1){let f=W.slice(2,Q),z=W.slice(Q+1);U(f,z)}else{let f=W.slice(2);if(f.startsWith("no-")){let B=f.slice(3);U(B,!1);continue}let z=J[f]||f;if(X.has(z)||X.has(f))U(f,!0);else{let B=w[j+1];if(B!==void 0&&!B.startsWith("-"))U(f,B),j++;else U(f,!0)}}}else if(W.startsWith("-")&&W.length>1){let Q=W.slice(1);for(let f=0;f<Q.length;f++){let z=Q[f],B=J[z]||z;if(f===Q.length-1&&!X.has(B)&&!X.has(z)){let G=w[j+1];if(G!==void 0&&!G.startsWith("-"))U(z,G),j++;else U(z,!0)}else U(z,!0)}}else Y._.push(W)}return Y}function UJ(w){return w.replace(/[<[].+/,"").trim()}function r6(w){let $=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(j)=>{let W=!1,Q=j[1];if(Q.startsWith("..."))Q=Q.slice(3),W=!0;return{required:j[0].startsWith("<"),value:Q,variadic:W}},J;while(J=$.exec(w))A.push(X(J));let U;while(U=Y.exec(w))A.push(X(U));return A}function t6(w){let $={alias:{},boolean:[]};for(let[Y,A]of w.entries()){if(A.names.length>1)$.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!w.some((J,U)=>{return U!==Y&&J.names.some((j)=>A.names.includes(j))&&typeof J.required==="boolean"}))$.boolean.push(A.names[0])}else $.boolean.push(A.names[0])}return $}function oj(w){return w.reduce(($,Y)=>$.length>=Y.length?$:Y,"")}function XJ(w,$){return w.length>=$?w:`${w}${" ".repeat($-w.length)}`}function a6(w){return w.replace(/([a-z])-([a-z])/g,($,Y,A)=>{return Y+A.toUpperCase()})}function s6(w,$,Y){let A=0,X=$.length,J=w,U;for(;A<X;++A)U=J[$[A]],J=J[$[A]]=A===X-1?Y:U!=null?U:!!~$[A+1].indexOf(".")||!(+$[A+1]>-1)?{}:[]}function o6(w,$){for(let Y of Object.keys($)){let A=$[Y];if(A.shouldTransform){if(w[Y]=Array.prototype.concat.call([],w[Y]),typeof A.transformFunction==="function")w[Y]=w[Y].map(A.transformFunction)}}}function e6(w){let $=/([^\\/]+)$/.exec(w);return $?$[1]:""}function JQ(w){return w.split(".").map(($,Y)=>{return Y===0?a6($):$}).join(".")}class rY extends Error{exitCode=2;isUsageError=!0;constructor(w){super(w);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(w).stack}format(w=!1){if(w&&this.stack)return`${this.message}
293
+ port ${vY}
294
+ `}function c1(w){return U6.join(j6,w)}function G6(w){return w.includes("127.0.0.1")&&w.includes(String(vY))}async function jR(w){try{return await J6.readFile(c1(w),"utf8")}catch($){if($.code==="ENOENT")return null;throw $}}async function ij(w){if(X$.platform!=="darwin")return;let{execSudoSync:$,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (z0(),k1));if(!A()&&!Y()){E("dns","Cannot flush DNS cache without SUDO_PASSWORD",w);return}try{$("dscacheutil -flushcache"),$("killall -HUP mDNSResponder 2>/dev/null || true"),E("dns","DNS cache flushed",w)}catch(X){E("dns",`Could not flush DNS cache: ${X}`,w)}}function E6(w){if(!/^[a-z0-9.-]+$/.test(w))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(w)}`)}async function QR(w,$){E6(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (z0(),k1)),A=WR().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${j6} && printf "%b" "${A}" > ${c1(w)}'`;Y(X),E("dns",`Created ${c1(w)}`,$)}async function fR(w,$){E6(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (z0(),k1));Y(`rm -f ${c1(w)}`),E("dns",`Removed ${c1(w)}`,$)}async function zR(w,$){return cj({domains:$??[],verbose:w})}async function BR(w,$){if(X$.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (z0(),k1));if(!A()&&!Y())return E("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;try{for(let X of w)await QR(X,$);return await ij($),!0}catch(X){return E("dns",`Failed to create resolver file: ${X}`,$),!1}}async function bj(w,$){if(X$.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (z0(),k1));if(!A()&&!Y())return;try{for(let X of w)await fR(X,$);await ij($)}catch(X){E("dns",`Failed to remove resolver files: ${X}`,$)}}async function uj(w){if(X$.platform!=="darwin")return[];let $=[];for(let Y of e2){let A=await jR(Y);if(A&&G6(A))await bj([Y],w),$.push(Y)}return $}async function cj(w){let $=w.rpxDir??V0(),Y=Zj(w.domains);if(Y.length===0)return!1;let A=kj(Y),X=await z6(Y,w.verbose);if(!X){let j=Y[0];if(j&&await B6(j))X=!0;else E("dns","Dev DNS server not available on 127.0.0.1:15353",w.verbose)}if(!X)return!1;if(!await BR(A,w.verbose))return!1;let U={version:x8,resolvers:A,domains:Y,ownerPid:w.ownerPid??X$.pid,updatedAt:new Date().toISOString()};return await $6($,U),!0}async function v1(w,$={}){let Y=w.map((W)=>W.to).filter(Boolean),A=$.rpxDir??V0(),X=kj(Y),j=((await k8(A))?.resolvers??[]).filter((W)=>!X.includes(W));if(j.length>0)await bj(j,$.verbose);if(X.length===0){Pj($.verbose),await xj(A);return}await cj({domains:Y,rpxDir:A,verbose:$.verbose,ownerPid:$.ownerPid??X$.pid})}async function g$(w={}){let $=w.rpxDir??V0();Pj(w.verbose);let A=(await k8($))?.resolvers??[];await bj(A,w.verbose),await uj(w.verbose),await xj($)}async function GR(w){await g$({verbose:w})}async function d$(w={}){let $=w.rpxDir??V0(),Y=await k8($),A=Y?.ownerPid!=null&&Xw(Y.ownerPid);if(Y&&!A){E("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,w.verbose),await g$(w);return}let X=await uj(w.verbose);if(X.length>0)E("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,w.verbose);await ij(w.verbose)}var vY=15353,W6="# managed-by: rpx",j6="/etc/resolver",t0=null,Z8;var mY=s(()=>{i8();A6();v$();z0();Z8=new Set});import{spawn as N6}from"node:child_process";import*as i0 from"node:fs/promises";import{homedir as q6}from"node:os";import*as Ow from"node:path";import*as I from"node:process";function V0(){return Ow.join(q6(),".stacks","rpx")}function L$(w=V0()){return Ow.join(w,"daemon.pid")}async function V$(w=V0()){try{let $=await i0.readFile(L$(w),"utf8"),Y=Number.parseInt($.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch($){if($.code==="ENOENT")return null;throw $}}async function v8(w=V0()){let $=await V$(w);return $!==null&&Xw($)}async function H6(w=V0()){await i0.mkdir(w,{recursive:!0});let $=L$(w);while(!0){try{let A=await i0.open($,"wx");try{await A.write(`${I.pid}
295
+ `)}finally{await A.close()}return $}catch(A){if(A.code!=="EEXIST")throw A}let Y=await V$(w);if(Y!==null&&Xw(Y))throw Error(`rpx daemon already running (pid=${Y})`);await i0.unlink($).catch(()=>{})}}async function m1(w=V0()){await i0.unlink(L$(w)).catch(()=>{})}function c8(w){for(let[$,Y]of u8)if(!w.has($))P1(Y),u8.delete($)}function KR(w,$){let Y=E2($??"localhost:1");if(w.upstreams.length!==Y.length)return!1;return w.upstreams.every((A,X)=>A.url===Y[X])}function R6(w){let $=w.cleanUrls??!1,Y=Y$(w.path),A=CY(w.auth);if(w.static)return{static:H8(w.static,$),cleanUrls:$,basePath:Y,auth:A};let X=w.from??"localhost:1",J=i$(X),U=new URL(J.startsWith("http")?J:`http://${J}`),j=u8.get(w.id);if(j&&!KR(j,X))P1(j),j=void 0;if(!j)j=RY(X,w.loadBalancer),yY(j),u8.set(w.id,j);return{sourceHost:U.host,upstreamPool:j,cleanUrls:$,changeOrigin:w.changeOrigin??!1,pathRewrites:w.pathRewrites,basePath:Y,auth:A}}function FR(w){return w.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??w[0]??"rpx.localhost"}async function b8(w,$,Y=[],A=!1){let X=await Kw($,w.verbose),J=[...new Set([...X.map((f)=>f.to).filter(Boolean),...Y])],U=FR(J),j=[...new Set([U,...J,"rpx.localhost"])],W=Q2(J,U,w.verbose);if(typeof w.https==="object"&&typeof W.https==="object")W.https={...W.https,...w.https};let Q=await M$(W);if(Q&&(A||!FW(Qj,j)))E("daemon",`regenerating shared cert for host(s): ${j.join(", ")}`,w.verbose),fj(),Q=null;if(!Q)E("daemon","no usable cert on disk, generating one via tlsx",w.verbose),await qY({...W,forceRegenerate:!0}),Q=await M$(W);if(!Q)throw Error("failed to bootstrap TLS for rpx daemon");return Q}async function TR(w,$,Y,A){let X=I.env.SUDO_PASSWORD,J=I.env.HOME??q6(),U=[I.execPath,...I.argv.slice(1)],j=[`HOME=${J}`,`PATH=${I.env.PATH??""}`];if(A)j.push("RPX_VERBOSE=1");for(let[T,K]of Object.entries(I.env))if(K!==void 0&&T!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(T))j.push(`${T}=${K}`);let W=X?["-S","-p","","env",...j,...U]:["-n","env",...j,...U];E("daemon",`elevating daemon via sudo for privileged ports ${$}/${Y}`,A);let Q=N6("sudo",W,{detached:!0,stdio:["pipe","ignore","ignore"]}),f=null,z=null;if(Q.once("error",(T)=>{f=T}),Q.once("exit",(T)=>{z=T??0}),X&&Q.stdin)Q.stdin.write(`${X}
296
+ `),Q.stdin.end();Q.unref();let B=L$(w),G=Date.now()+15000;while(Date.now()<G){if(f)throw f;let T=await V$(w);if(T!==null&&Xw(T)){if(A)H.success(`rpx daemon elevated to root (pid=${T}, https on :${$})`);return{httpsPort:$,httpPort:Y,pidPath:B,done:Promise.resolve(),stop:async()=>{try{I.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(z!==null&&z!==0)throw Error(`rpx daemon could not elevate to bind :${$} (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=${w})`)}function vj(){if(K6)return;K6=!0,I.on("uncaughtException",(w)=>{H.error(`rpx daemon: uncaught exception (continuing): ${w?.stack??w}`)}),I.on("unhandledRejection",(w)=>{H.error(`rpx daemon: unhandled rejection (continuing): ${w}`)})}function M6(w,$,Y){let A;try{A=new URL(w.url)}catch{return new Response("Bad Request",{status:400})}let X=(w.headers.get("host")??A.hostname).split(":")[0];if(A.pathname.startsWith("/.well-known/acme-challenge/")){if($){let J=$.challengeStore.handlePath(A.pathname);if(J!==void 0)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(Y){let J=M8(Y,A.pathname);if(J!=null)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if($)return new Response("challenge not found",{status:404})}if($&&!$.hasCert(X))$.ensureCert(X).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${X}${A.pathname}${A.search}`}})}async function y6(w={}){vj();let $=w.verbose??!1,Y=w.rpxDir??V0(),A=w.registryDir??Ow.join(Y,"registry.d"),X=w.httpsPort??443,J=w.httpPort??80,U=w.hostname??"::",j=w.hostname==null,W=w.gcIntervalMs??ER;if(I.env.RPX_DAEMON_WORKER==="1")return HR({rpxDir:I.env.RPX_WORKER_RPXDIR??Y,registryDir:I.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(I.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:I.env.RPX_WORKER_HOSTNAME??U,verbose:I.env.RPX_WORKER_VERBOSE==="1"||$});let Q=X>0&&X<1024||J>0&&J<1024,f=typeof I.getuid==="function"&&I.getuid()===0;if(I.platform!=="win32"&&Q&&!f)return TR(Y,X,J,$);let z=Math.max(1,w.workers??(Number.parseInt(I.env.RPX_WORKERS??"",10)||1));if(z>1){if(w.onDemandSites?.enabled)H.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return RR(w,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:$,gcIntervalMs:W,workers:z})}let B=await H6(Y),G=new Map,T=(y,O)=>OY(G,y,O);function K(y){G=hY(y.map((s0)=>({host:s0.to,path:s0.path,route:R6(s0)}))),c8(new Set(y.map((s0)=>s0.id)));let O=Array.from(G.keys());E("daemon",`routing table now covers ${O.length} host(s): ${O.join(", ")||"<empty>"}`,$)}await kY(A,$).catch((y)=>{E("daemon",`initial gc failed: ${y}`,$)}),await uY({verbose:$}).catch((y)=>{E("daemon",`stale hosts GC on start failed: ${y}`,$)});let F=await Kw(A,$);K(F),await d$({rpxDir:Y,verbose:$}).catch((y)=>{E("daemon",`DNS reconcile on start failed: ${y}`,$)}),await v1(F,{rpxDir:Y,verbose:$,ownerPid:I.pid}).catch((y)=>{E("daemon",`DNS setup on start failed: ${y}`,$)});let N=[];if(w.productionCerts){if(N=await DY(w.productionCerts,$),$&&N.length>0)H.info(`SNI: serving ${N.length} real cert(s): ${N.map((y)=>y.serverName).join(", ")}`)}let R=new Set,V=null,L;if(w.onDemandSites?.enabled){if(V=new Vj({resolver:UU(w.onDemandSites),registryDir:A,rpxDir:Y,verbose:$,startupTimeoutMs:w.onDemandSites.startupTimeoutMs,isHostRoutable:(y)=>Fj(G,y)!==void 0,onSiteActivating:(y)=>{lY(y)}}),L=async(y)=>{let O=await V.onRequest(y);switch(O.kind){case"ready":return{retry:!0};case"starting":return n2({host:O.host,sinceMs:O.sinceMs,logTail:O.logTail});case"failed":return l2({host:O.host,error:O.error,logTail:O.logTail});case"unknown":default:return}},$)H.info("rpx: on-demand sites enabled")}let q=LY(T,$,L),C=SY($),M=null;if(N.length===0)M=await b8(w,A);let D=w.onDemandTls,d=D?.enabled?new i1({config:D,certsDir:D.certsDir??w.productionCerts?.certsDir??Ow.join(Y,"on-demand-certs"),initial:N,verbose:$,onCertAdded:(y)=>{if(xY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",$),setTimeout(()=>I.kill(I.pid,"SIGTERM"),10).unref();else _(y)}}):null;function r0(y){if(y.length>0)return u$(y.map((O)=>({serverName:O.serverName,cert:O.cert,key:O.key})));return u$({key:M.key,cert:M.cert,ca:M.ca,requestCert:!1,rejectUnauthorized:!1})}function Jw(y){try{return Bun.serve(y)}catch(O){let s0=O instanceof Error?O.message:String(O),n1=/EAFNOSUPPORT|EADDRNOTAVAIL|address family/i.test(s0);if(!j||y.hostname!=="::"||!n1)throw O;return E("daemon",`no IPv6 on this host (${s0}); binding 0.0.0.0`,w.verbose),Bun.serve({...y,hostname:"0.0.0.0"})}}function n$(y){return Jw({port:X,hostname:U,reusePort:TY(),tls:r0(y),fetch(O,s0){return q(O,s0)},websocket:C,error(O){return E("daemon",`https server error: ${O}`,$),new Response(`Server Error: ${O.message}`,{status:500})}})}let g1=(y)=>[...new Set(y.map((O)=>O.to).filter(Boolean))],J$=(y)=>{if(!M)return N;return j2([...g1(y),...R,"rpx.localhost"],M)},a0=n$(d?d.sniEntries():N.length>0?N:J$(F)),Vw=null,Lw=!1;async function _(y){if(Sw)return;if(Vw=y,Lw)return;Lw=!0;try{while(!Sw&&Vw){let O=Vw;Vw=null,E("daemon",`rebuilding :443 with ${O.length} SNI cert(s)`,$),a0.stop(!1);let s0,n1=!1,aj=60,c6=500;for(let YJ=0;!Sw&&!n1;YJ++)try{a0=n$(O),n1=!0;break}catch(v6){if(s0=v6,YJ>=aj)break;await new Promise((m6)=>setTimeout(m6,Math.min(25*2**Math.min(YJ,4),c6)))}if(!n1)H.error(`rpx: CRITICAL — could not rebind :443 after ${aj} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${s0?.message}`)}}finally{Lw=!1}}let u0=null;if(J>0)u0=Jw({port:J,hostname:U,fetch(y){return M6(y,d,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if($)H.success(`rpx daemon listening on https://${U}:${X}${u0?` (http→https on :${J})`:""}`),H.info(`pid file: ${B}`),H.info(`registry: ${A}`);async function d1(y){if(Sw||N.length>0||d||!M)return;try{M=await b8(w,A,[...R]),await _(J$(y))}catch(O){E("daemon",`TLS sync on registry change failed: ${O}`,$)}}async function lY(y){if(Sw||N.length>0||d||!M||!y)return;if(R.has(y))return;R.add(y);try{M=await b8(w,A,[...R],!0);let O=await Kw(A,$);await _(J$(O))}catch(O){E("daemon",`dev cert refresh for ${y} failed: ${O}`,$)}}let pY=h8((y)=>{K(y),d1(y),v1(y,{rpxDir:Y,verbose:$,ownerPid:I.pid}).catch((O)=>{E("daemon",`DNS sync on registry change failed: ${O}`,$)})},{dir:A,verbose:$}),l$=setInterval(()=>{kY(A,$).then((y)=>{if(y>0)E("daemon",`gc reaped ${y} stale entries`,$)}).catch((y)=>{E("daemon",`periodic gc failed: ${y}`,$)}),uY({verbose:$}).then((y)=>{if(y.length>0)E("daemon",`gc reaped stale hosts entries: ${y.join(", ")}`,$)}).catch((y)=>{E("daemon",`periodic hosts gc failed: ${y}`,$)})},W);if(typeof l$.unref==="function")l$.unref();let Sw=!1,wJ,$J=new Promise((y)=>{wJ=y});async function rj(){if(Sw)return $J;if(Sw=!0,clearInterval(l$),pY.close(),await V?.stopAll().catch((y)=>{E("daemon",`site supervisor stopAll failed: ${y}`,$)}),a0.stop(!1),u0?.stop(!1),await g$({rpxDir:Y,verbose:$}).catch((y)=>{E("daemon",`DNS teardown failed: ${y}`,$)}),c8(new Set),await m1(Y),$)H.info("rpx daemon stopped");return wJ(),$J}let tj=(y)=>{E("daemon",`received ${y}, shutting down`,$),rj().catch(()=>{})};return I.once("SIGINT",tj),I.once("SIGTERM",tj),{stop:rj,done:$J,httpsPort:typeof a0.port==="number"?a0.port:X,httpPort:u0&&typeof u0.port==="number"?u0.port:J,pidPath:B,ensureCert:(y)=>d?d.ensureCert(y):Promise.resolve(!1),listSites:()=>V?.list()??[]}}function mj(w){return Ow.join(w,"cluster-sni.json")}async function F6(w,$,Y){let A=mj(w),X=`${A}.${I.pid}.tmp`;await i0.writeFile(X,JSON.stringify({sni:$,dev:Y}),"utf8"),await i0.rename(X,A)}async function T6(w){try{return JSON.parse(await i0.readFile(mj(w),"utf8"))}catch{return{sni:[],dev:null}}}function NR(w){if(w.sni.length>0)return u$(w.sni.map(($)=>({serverName:$.serverName,cert:$.cert,key:$.key})));if(w.dev)return u$({key:w.dev.key,cert:w.dev.cert,ca:w.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function qR(){let w=I.execPath,$=I.env.RPX_WORKER_BIN;if($)return[w,$,"daemon:start"];let Y=Ow.basename(w).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&I.argv[1])return[w,I.argv[1],"daemon:start"];return[w,"daemon:start"]}async function HR(w){vj();let{rpxDir:$,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=w,U=new Map,j=(C,M)=>OY(U,C,M),W=(C)=>{U=hY(C.map((M)=>({host:M.to,path:M.path,route:R6(M)}))),c8(new Set(C.map((M)=>M.id)))};W(await Kw(Y,J));let Q=LY(j,J),f=SY(J),z=!1,B=(C)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:NR(C),fetch(M,D){return Q(M,D)},websocket:f,error(M){return E("daemon",`worker https error: ${M}`,J),new Response(`Server Error: ${M.message}`,{status:500})}}),G=B(await T6($));async function T(){if(z)return;let C=await T6($),M=null;for(let d=0;d<20&&!z;d++)try{M=B(C);break}catch{await new Promise((r0)=>setTimeout(r0,25))}if(!M){E("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let D=G;G=M,D.stop(!1)}let K=h8((C)=>W(C),{dir:Y,verbose:J}),F=()=>{T().catch(()=>{})};I.on("SIGHUP",F);let N=()=>{let C=I.removeListener??I.off;if(typeof C==="function")C.call(I,"SIGHUP",F)},R,V=new Promise((C)=>{R=C});async function L(){if(z)return V;return z=!0,N(),K.close(),G.stop(!1),c8(new Set),R(),V}let q=()=>{L().then(()=>I.exit(0)).catch(()=>I.exit(0))};if(I.once("SIGTERM",q),I.once("SIGINT",q),J)H.success(`rpx worker (pid ${I.pid}) serving :${A}`);return{stop:L,done:V,httpsPort:typeof G.port==="number"?G.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function RR(w,$){vj();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:j,gcIntervalMs:W,workers:Q}=$,f=await H6(Y),z=[];if(w.productionCerts)z=await DY(w.productionCerts,j);let B=null;if(z.length===0)B=await b8(w,A);let G=B?{key:B.key,cert:B.cert,ca:Array.isArray(B.ca)?B.ca.join(`
297
+ `):B.ca}:null,T=!1,K=[];function F(_){for(let u0 of K)try{u0.kill(_)}catch{}}async function N(_){await F6(Y,_,G),F("SIGHUP")}let R=w.onDemandTls,V=R?.enabled?new i1({config:R,certsDir:R.certsDir??w.productionCerts?.certsDir??Ow.join(Y,"on-demand-certs"),initial:z,verbose:j,onCertAdded:(_)=>{if(xY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",j),setTimeout(()=>I.kill(I.pid,"SIGTERM"),10).unref();else N(_)}}):null;await F6(Y,V?V.sniEntries():z,G);let L=await Kw(A,j);await d$({rpxDir:Y,verbose:j}).catch((_)=>{E("daemon",`DNS reconcile on start failed: ${_}`,j)}),await v1(L,{rpxDir:Y,verbose:j,ownerPid:I.pid}).catch((_)=>{E("daemon",`DNS setup on start failed: ${_}`,j)}),await kY(A,j).catch(()=>{}),await uY({verbose:j}).catch(()=>{});let q=h8((_)=>{v1(_,{rpxDir:Y,verbose:j,ownerPid:I.pid}).catch((u0)=>{E("daemon",`DNS sync on registry change failed: ${u0}`,j)})},{dir:A,verbose:j}),C=setInterval(()=>{kY(A,j).catch(()=>{}),uY({verbose:j}).catch(()=>{})},W);C.unref?.();let M=null;if(J>0)M=Bun.serve({port:J,hostname:U,fetch(_){return M6(_,V,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let D=10,d=60000,r0=30000,Jw=0,n$=Date.now();function g1(){if(T)return;let _={...I.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:j?"1":"0"},u0=Bun.spawn(qR(),{env:_,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(d1,lY){if(T)return;let pY=K.indexOf(d1);if(pY!==-1)K.splice(pY,1);let l$=Date.now();if(l$-n$>d)n$=l$,Jw=0;if(Jw++,Jw>D){H.error(`rpx: worker keeps exiting (code ${lY}); giving up after ${D} restarts in ${Math.round(d/1000)}s`);return}let Sw=Math.min(r0,100*2**Math.min(Jw,8));E("daemon",`worker exited (code ${lY}); respawning in ${Sw}ms (restart ${Jw}/${D})`,j),setTimeout(g1,Sw).unref?.()}});K.push(u0)}for(let _=0;_<Q;_++)g1();if(j)H.success(`rpx coordinator listening on https://${U}:${X} via ${Q} worker(s)${M?` (http→https on :${J})`:""}`),H.info(`pid file: ${f}`);let J$,a0=new Promise((_)=>{J$=_});async function Vw(){if(T)return a0;if(T=!0,clearInterval(C),q.close(),M?.stop(!1),F("SIGTERM"),await Promise.race([Promise.all(K.map((_)=>_.exited)),new Promise((_)=>setTimeout(_,3000))]),F("SIGKILL"),await g$({rpxDir:Y,verbose:j}).catch((_)=>{E("daemon",`DNS teardown failed: ${_}`,j)}),await m1(Y),await i0.unlink(mj(Y)).catch(()=>{}),j)H.info("rpx coordinator stopped");return J$(),a0}let Lw=(_)=>{E("daemon",`coordinator received ${_}, shutting down`,j),Vw().catch(()=>{})};return I.once("SIGINT",Lw),I.once("SIGTERM",Lw),{stop:Vw,done:a0,httpsPort:X,httpPort:J,pidPath:f,ensureCert:(_)=>V?V.ensureCert(_):Promise.resolve(!1),listSites:()=>[]}}function MR(){let w=I.execPath,$=Ow.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&I.argv[1])return[w,I.argv[1],"daemon:start"];return[w,"daemon:start"]}async function m8(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1;await d$({rpxDir:$,verbose:Y}).catch((f)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${f}`,Y)});let A=await V$($);if(A!==null&&Xw(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 m1($);await i0.mkdir($,{recursive:!0});let X=w.spawnCommand??MR();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=N6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??I.cwd(),env:w.spawnEnv?{...I.env,...w.spawnEnv}:I.env});J.unref();let U=null;J.once("error",(f)=>{U=f});let j=w.startupTimeoutMs??5000,W=w.pollIntervalMs??50,Q=Date.now()+j;while(Date.now()<Q){if(U)throw U;let f=await V$($);if(f!==null&&Xw(f))return E("daemon",`daemon registered with pid=${f}`,Y),{pid:f,spawned:!0};await new Promise((z)=>setTimeout(z,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${j}ms (rpxDir=${$})`)}async function I6(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1,A=w.timeoutMs??5000,X=w.pollIntervalMs??50,J=w.forceAfterTimeout??!0,U=await V$($);if(U===null||!Xw(U)){if(U!==null)await m1($);return await d$({rpxDir:$,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{I.kill(U,"SIGTERM")}catch(W){let Q=W.code;if(Q==="ESRCH")return await m1($),{stopped:!1,pid:U,forced:!1};if(Q==="EPERM")T$(`kill -TERM ${U}`);else throw W}let j=Date.now()+A;while(Date.now()<j){if(!Xw(U))return E("daemon",`daemon pid=${U} stopped cleanly`,Y),{stopped:!0,pid:U,forced:!1};await new Promise((W)=>setTimeout(W,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${A}ms`);E("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{I.kill(U,"SIGKILL")}catch(W){let Q=W.code;if(Q==="EPERM")T$(`kill -KILL ${U}`);else if(Q!=="ESRCH")throw W}return await m1($),await g$({rpxDir:$,verbose:Y}).catch((W)=>{E("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function C6(w={}){let $=w.rpxDir??V0();if(await v8($))return;await d$({rpxDir:$,verbose:w.verbose})}var ER=5000,u8,K6=!1;var i8=s(()=>{_$();zj();Ej();Kj();y8();Nj();qj();WU();g2();R8();T8();v$();Oj();mY();z0();u8=new Map});import{dirname as PR,join as iR}from"node:path";import*as P0 from"node:process";import{fileURLToPath as bR}from"node:url";import{existsSync as p6}from"node:fs";import AJ from"node:fs/promises";import oj from"node:os";import XJ from"node:path";import S$ from"node:process";import{EventEmitter as r6}from"node:events";import U$ from"node:process";import ej from"node:process";import jJ from"node:process";import aY from"node:process";import r1 from"node:process";import YQ from"node:tty";import ZG,{stdin as XM,stdout as JM}from"node:process";import XQ,{stdin as bG,stdout as uG}from"node:process";import cG from"node:readline";class UQ{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let w=oj.homedir(),$=XJ.join(w,".config","clapp");this.configPath=XJ.join($,"telemetry.json")}async isEnabled(){if(S$.env.DO_NOT_TRACK==="1"||S$.env.DO_NOT_TRACK==="true")return!1;if(S$.env.NO_TELEMETRY==="1"||S$.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let w=await this.loadConfig();if(w.enabled=!0,!w.userId)w.userId=this.generateUserId();await this.saveConfig(w)}async disable(){let w=await this.loadConfig();w.enabled=!1,await this.saveConfig(w)}async track(w,$){if(!await this.isEnabled())return;let A={event:w,...$,timestamp:Date.now(),platform:oj.platform(),nodeVersion:S$.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand(w,$){await this.track("command",{command:w,duration:$})}async trackError(w,$){await this.track("error",{error:w,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(w){return new Promise(($)=>setTimeout($,w))}async status(){let w=await this.loadConfig();return{enabled:w.enabled,doNotTrack:S$.env.DO_NOT_TRACK==="1"||S$.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:w.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(p6(this.configPath)){let w=await AJ.readFile(this.configPath,"utf-8");return this.config=JSON.parse(w),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(w){this.config=w;try{let $=XJ.dirname(this.configPath);await AJ.mkdir($,{recursive:!0}),await AJ.writeFile(this.configPath,JSON.stringify(w,null,2),"utf-8")}catch{}}generateUserId(){let w=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${w}-${$}`}}var lR=new UQ;function t6(w,$={}){let Y={_:[]},A=$.alias||{},X=new Set($.boolean||[]),J={};for(let j of Object.keys(A))for(let W of A[j])J[W]=j;for(let j of X)if(A[j])for(let W of A[j])X.add(W);function U(j,W){let Q=J[j]||j;if(Y[Q]=W,A[Q])for(let f of A[Q])Y[f]=W;if(J[j]&&A[J[j]])for(let f of A[J[j]])Y[f]=W;Y[j]=W}for(let j=0;j<w.length;j++){let W=w[j];if(W==="--"){Y._.push(...w.slice(j+1));break}if(W.startsWith("--")){let Q=W.indexOf("=");if(Q!==-1){let f=W.slice(2,Q),z=W.slice(Q+1);U(f,z)}else{let f=W.slice(2);if(f.startsWith("no-")){let B=f.slice(3);U(B,!1);continue}let z=J[f]||f;if(X.has(z)||X.has(f))U(f,!0);else{let B=w[j+1];if(B!==void 0&&!B.startsWith("-"))U(f,B),j++;else U(f,!0)}}}else if(W.startsWith("-")&&W.length>1){let Q=W.slice(1);for(let f=0;f<Q.length;f++){let z=Q[f],B=J[z]||z;if(f===Q.length-1&&!X.has(B)&&!X.has(z)){let G=w[j+1];if(G!==void 0&&!G.startsWith("-"))U(z,G),j++;else U(z,!0)}else U(z,!0)}}else Y._.push(W)}return Y}function WJ(w){return w.replace(/[<[].+/,"").trim()}function a6(w){let $=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(j)=>{let W=!1,Q=j[1];if(Q.startsWith("..."))Q=Q.slice(3),W=!0;return{required:j[0].startsWith("<"),value:Q,variadic:W}},J;while(J=$.exec(w))A.push(X(J));let U;while(U=Y.exec(w))A.push(X(U));return A}function s6(w){let $={alias:{},boolean:[]};for(let[Y,A]of w.entries()){if(A.names.length>1)$.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!w.some((J,U)=>{return U!==Y&&J.names.some((j)=>A.names.includes(j))&&typeof J.required==="boolean"}))$.boolean.push(A.names[0])}else $.boolean.push(A.names[0])}return $}function wQ(w){return w.reduce(($,Y)=>$.length>=Y.length?$:Y,"")}function JJ(w,$){return w.length>=$?w:`${w}${" ".repeat($-w.length)}`}function o6(w){return w.replace(/([a-z])-([a-z])/g,($,Y,A)=>{return Y+A.toUpperCase()})}function e6(w,$,Y){let A=0,X=$.length,J=w,U;for(;A<X;++A)U=J[$[A]],J=J[$[A]]=A===X-1?Y:U!=null?U:!!~$[A+1].indexOf(".")||!(+$[A+1]>-1)?{}:[]}function wG(w,$){for(let Y of Object.keys($)){let A=$[Y];if(A.shouldTransform){if(w[Y]=Array.prototype.concat.call([],w[Y]),typeof A.transformFunction==="function")w[Y]=w[Y].map(A.transformFunction)}}}function $G(w){let $=/([^\\/]+)$/.exec(w);return $?$[1]:""}function WQ(w){return w.split(".").map(($,Y)=>{return Y===0?o6($):$}).join(".")}class tY extends Error{exitCode=2;isUsageError=!0;constructor(w){super(w);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(w).stack}format(w=!1){if(w&&this.stack)return`${this.message}
298
298
 
299
299
  Stack trace:
300
- ${this.stack}`;return this.message}}function wG(){let{env:w}=sj,{TERM:$,TERM_PROGRAM:Y}=w;if(sj.platform!=="win32")return $!=="linux";return Boolean(w.WT_SESSION)||Boolean(w.TERMINUS_SUBLIME)||w.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||w.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var oY="\x1B",Q0=`${oY}[`;var Zw={to(w,$){if(!$)return`${Q0}${w+1}G`;return`${Q0}${$+1};${w+1}H`},move(w,$){let Y="";if(w<0)Y+=`${Q0}${-w}D`;else if(w>0)Y+=`${Q0}${w}C`;if($<0)Y+=`${Q0}${-$}A`;else if($>0)Y+=`${Q0}${$}B`;return Y},up:(w=1)=>`${Q0}${w}A`,down:(w=1)=>`${Q0}${w}B`,forward:(w=1)=>`${Q0}${w}C`,backward:(w=1)=>`${Q0}${w}D`,nextLine:(w=1)=>`${Q0}E`.repeat(w),prevLine:(w=1)=>`${Q0}F`.repeat(w),left:`${Q0}G`,hide:`${Q0}?25l`,show:`${Q0}?25h`,save:`${oY}7`,restore:`${oY}8`};var JJ={screen:`${Q0}2J`,up:(w=1)=>`${Q0}1J`.repeat(w),down:(w=1)=>`${Q0}J`.repeat(w),line:`${Q0}2K`,lineEnd:`${Q0}K`,lineStart:`${Q0}1K`,lines(w){let $="";for(let Y=0;Y<w;Y++)$+=this.line+(Y<w-1?Zw.up():"");if(w)$+=Zw.left;return $}},rR={screen:`${oY}c`};function $G(w,$){let Y=[];for(let A=0;A<=$.length;A++)Y[A]=[A];for(let A=0;A<=w.length;A++)Y[0][A]=A;for(let A=1;A<=$.length;A++)for(let X=1;X<=w.length;X++)if($.charAt(A-1)===w.charAt(X-1))Y[A][X]=Y[A-1][X-1];else Y[A][X]=Math.min(Y[A-1][X-1]+1,Y[A][X-1]+1,Y[A-1][X]+1);return Y[$.length][w.length]}function UQ(w,$,Y=2,A=3){return $.map((X)=>({cmd:X,distance:$G(w,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class WQ{rawName;description;name;names;isBoolean;required;config;negated;constructor(w,$,Y){if(this.rawName=w,this.description=$,this.config=Object.assign({},Y),w=w.replace(/\.\*/g,""),this.negated=!1,this.names=UJ(w).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return JQ(X)}).sort((A,X)=>A.length>X.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(w.includes("<"))this.required=!0;else if(w.includes("["))this.required=!1;else this.isBoolean=!0}}var aR=WJ.argv,YG=`${WJ.platform}-${WJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,ej=tY.argv,AG=`${tY.platform}-${tY.arch} node-${tY.version}`;class jJ{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(w,$,Y,A){this.rawName=w,this.description=$,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=UJ(w);let X=UJ(w),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=r6(w),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage(w){return this.usageText=w,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(w,$="-v, --version"){return this.versionNumber=w,this.option($,"Display version number"),this}example(w){return this.examples.push(w),this}option(w,$,Y){let A=new WQ(w,$,Y);return this.options.push(A),this}alias(w){return this.aliasNames.push(w),this}action(w){return this.commandAction=w,this}before(w){return this.beforeHooks.push(w),this}after(w){return this.afterHooks.push(w),this}use(w){return this.middleware.push(w),this}isMatched(w){if(this.aliasNames.includes(w))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===w;return this.name===w}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof QJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(w){return w=w.split(".")[0],!!this.options.find(($)=>{return $.names.includes(w)})}outputHelp(){let{name:w,commands:$}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${w}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${w} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let W=oj($.map((G)=>G.rawName)),Q=new Map,f=[];for(let G of $)if(G.namespace){if(!Q.has(G.namespace))Q.set(G.namespace,[]);Q.get(G.namespace).push(G)}else f.push(G);let z="";if(f.length>0)z+=f.map((G)=>{return` ${XJ(G.rawName,W.length)} ${G.description}`}).join(`
300
+ ${this.stack}`;return this.message}}function YG(){let{env:w}=ej,{TERM:$,TERM_PROGRAM:Y}=w;if(ej.platform!=="win32")return $!=="linux";return Boolean(w.WT_SESSION)||Boolean(w.TERMINUS_SUBLIME)||w.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||w.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var eY="\x1B",Q0=`${eY}[`;var xw={to(w,$){if(!$)return`${Q0}${w+1}G`;return`${Q0}${$+1};${w+1}H`},move(w,$){let Y="";if(w<0)Y+=`${Q0}${-w}D`;else if(w>0)Y+=`${Q0}${w}C`;if($<0)Y+=`${Q0}${-$}A`;else if($>0)Y+=`${Q0}${$}B`;return Y},up:(w=1)=>`${Q0}${w}A`,down:(w=1)=>`${Q0}${w}B`,forward:(w=1)=>`${Q0}${w}C`,backward:(w=1)=>`${Q0}${w}D`,nextLine:(w=1)=>`${Q0}E`.repeat(w),prevLine:(w=1)=>`${Q0}F`.repeat(w),left:`${Q0}G`,hide:`${Q0}?25l`,show:`${Q0}?25h`,save:`${eY}7`,restore:`${eY}8`};var UJ={screen:`${Q0}2J`,up:(w=1)=>`${Q0}1J`.repeat(w),down:(w=1)=>`${Q0}J`.repeat(w),line:`${Q0}2K`,lineEnd:`${Q0}K`,lineStart:`${Q0}1K`,lines(w){let $="";for(let Y=0;Y<w;Y++)$+=this.line+(Y<w-1?xw.up():"");if(w)$+=xw.left;return $}},aR={screen:`${eY}c`};function AG(w,$){let Y=[];for(let A=0;A<=$.length;A++)Y[A]=[A];for(let A=0;A<=w.length;A++)Y[0][A]=A;for(let A=1;A<=$.length;A++)for(let X=1;X<=w.length;X++)if($.charAt(A-1)===w.charAt(X-1))Y[A][X]=Y[A-1][X-1];else Y[A][X]=Math.min(Y[A-1][X-1]+1,Y[A][X-1]+1,Y[A-1][X]+1);return Y[$.length][w.length]}function jQ(w,$,Y=2,A=3){return $.map((X)=>({cmd:X,distance:AG(w,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class QQ{rawName;description;name;names;isBoolean;required;config;negated;constructor(w,$,Y){if(this.rawName=w,this.description=$,this.config=Object.assign({},Y),w=w.replace(/\.\*/g,""),this.negated=!1,this.names=WJ(w).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return WQ(X)}).sort((A,X)=>A.length>X.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(w.includes("<"))this.required=!0;else if(w.includes("["))this.required=!1;else this.isBoolean=!0}}var oR=jJ.argv,XG=`${jJ.platform}-${jJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,$Q=aY.argv,JG=`${aY.platform}-${aY.arch} node-${aY.version}`;class QJ{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(w,$,Y,A){this.rawName=w,this.description=$,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=WJ(w);let X=WJ(w),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=a6(w),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage(w){return this.usageText=w,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(w,$="-v, --version"){return this.versionNumber=w,this.option($,"Display version number"),this}example(w){return this.examples.push(w),this}option(w,$,Y){let A=new QQ(w,$,Y);return this.options.push(A),this}alias(w){return this.aliasNames.push(w),this}action(w){return this.commandAction=w,this}before(w){return this.beforeHooks.push(w),this}after(w){return this.afterHooks.push(w),this}use(w){return this.middleware.push(w),this}isMatched(w){if(this.aliasNames.includes(w))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===w;return this.name===w}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof fJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(w){return w=w.split(".")[0],!!this.options.find(($)=>{return $.names.includes(w)})}outputHelp(){let{name:w,commands:$}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${w}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${w} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let W=wQ($.map((G)=>G.rawName)),Q=new Map,f=[];for(let G of $)if(G.namespace){if(!Q.has(G.namespace))Q.set(G.namespace,[]);Q.get(G.namespace).push(G)}else f.push(G);let z="";if(f.length>0)z+=f.map((G)=>{return` ${JJ(G.rawName,W.length)} ${G.description}`}).join(`
301
301
  `);let B=Array.from(Q.keys()).sort();for(let G of B){let T=Q.get(G);if(z.length>0)z+=`
302
302
 
303
303
  `;z+=` ${G}:
304
- `,z+=T.map((K)=>{return` ${XJ(K.rawName,W.length-2)} ${K.description}`}).join(`
304
+ `,z+=T.map((K)=>{return` ${JJ(K.rawName,W.length-2)} ${K.description}`}).join(`
305
305
  `)}J.push({title:"Commands",body:z}),J.push({title:"For more info, run any command with the `--help` flag",body:$.map((G)=>` $ ${w}${G.displayName===""?"":` ${G.displayName}`} --help`).join(`
306
- `)})}let j=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)j=j.filter((W)=>W.name!=="version");if(j.length>0){let W=oj(j.map((Q)=>Q.rawName));J.push({title:"Options",body:j.map((Q)=>{return` ${XJ(Q.rawName,W.length)} ${Q.description} ${Q.config.default===void 0?"":`(default: ${Q.config.default})`}`}).join(`
306
+ `)})}let j=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)j=j.filter((W)=>W.name!=="version");if(j.length>0){let W=wQ(j.map((Q)=>Q.rawName));J.push({title:"Options",body:j.map((Q)=>{return` ${JJ(Q.rawName,W.length)} ${Q.description} ${Q.config.default===void 0?"":`(default: ${Q.config.default})`}`}).join(`
307
307
  `)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((W)=>{if(typeof W==="function")return W(w);return W}).join(`
308
308
  `)});if(X)J=X(J)||J;console.log(J.map((W)=>{return W.title?`${W.title}:
309
309
  ${W.body}`:W.body}).join(`
310
310
 
311
- `))}outputVersion(){let{name:w}=this.cli,{versionNumber:$}=this.cli.globalCommand;if($)console.log(`${w}/${$} ${typeof Bun<"u"?YG:AG}`)}checkRequiredArgs(){let w=this.args.filter(($)=>$.required).length;if(this.cli.args.length<w){let Y=this.args.filter((X)=>X.required).slice(this.cli.args.length),A=Y.map((X)=>`<${X.value}>`).join(" ");throw new rY(`Missing required argument${Y.length>1?"s":""}: ${A}
311
+ `))}outputVersion(){let{name:w}=this.cli,{versionNumber:$}=this.cli.globalCommand;if($)console.log(`${w}/${$} ${typeof Bun<"u"?XG:JG}`)}checkRequiredArgs(){let w=this.args.filter(($)=>$.required).length;if(this.cli.args.length<w){let Y=this.args.filter((X)=>X.required).slice(this.cli.args.length),A=Y.map((X)=>`<${X.value}>`).join(" ");throw new tY(`Missing required argument${Y.length>1?"s":""}: ${A}
312
312
 
313
- Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:w,globalCommand:$}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys(w))if(Y!=="--"&&!this.hasOption(Y)&&!$.hasOption(Y)){let X=[...$.options,...this.options].flatMap((W)=>W.names),J=Y.length>1?`--${Y}`:`-${Y}`,U=UQ(Y,X),j=`Unknown option \`${J}\``;if(U.length>0)j+=`
313
+ Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:w,globalCommand:$}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys(w))if(Y!=="--"&&!this.hasOption(Y)&&!$.hasOption(Y)){let X=[...$.options,...this.options].flatMap((W)=>W.names),J=Y.length>1?`--${Y}`:`-${Y}`,U=jQ(Y,X),j=`Unknown option \`${J}\``;if(U.length>0)j+=`
314
314
 
315
315
  Did you mean one of these?`,U.forEach((W)=>{let Q=W.length>1?`--${W}`:`-${W}`;j+=`
316
316
  • ${Q}`});throw j+=`
317
317
 
318
- Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new rY(j)}}}checkOptionValue(){let{options:w,globalCommand:$}=this.cli,Y=[...$.options,...this.options];for(let A of Y){let X=w[A.name.split(".")[0]];if(A.required){let J=Y.some((U)=>U.negated&&U.names.includes(A.name));if(X===!0||X===!1&&!J)throw new rY(`Option \`${A.rawName}\` requires a value.
318
+ Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new tY(j)}}}checkOptionValue(){let{options:w,globalCommand:$}=this.cli,Y=[...$.options,...this.options];for(let A of Y){let X=w[A.name.split(".")[0]];if(A.required){let J=Y.some((U)=>U.negated&&U.names.includes(A.name));if(X===!0||X===!1&&!J)throw new tY(`Option \`${A.rawName}\` requires a value.
319
319
 
320
- Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class QJ extends jJ{constructor(w){super("@@global@@","",{},w)}}var XG=jJ,j$={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 p1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function JG(){return!0}function UG(){let w={};w.supportsColor=JG();function $(A,X=[]){let J=A===""?[]:[...X,A],U=function(W){if(!w.supportsColor)return W;let Q="",f="";for(let z of J)if(z in p1&&p1[z]in j$){let B=p1[z];Q+=j$[B][0],f=j$[B][1]+f}else if(z in j$)Q+=j$[z][0],f=j$[z][1]+f;return Q+W+f},j=[...Object.keys(j$),...Object.keys(p1)];for(let W of j)if(!(W in U))Object.defineProperty(U,W,{get(){return $(W,J)}});return U}let Y=[...Object.keys(j$),...Object.keys(p1)];for(let A of Y)if(!(A in w))Object.defineProperty(w,A,{get(){return $(A)}});return w}var r1=UG();class fJ extends l6{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(w=""){super();this.name=w,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new QJ(this),this.globalCommand.usage("<command> [options]")}handleSignals(w){if(this.signalHandlersSet)return this;let $=async(Y)=>{if(console.log(`
320
+ Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class fJ extends QJ{constructor(w){super("@@global@@","",{},w)}}var UG=QJ,W$={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 l1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function WG(){return!0}function jG(){let w={};w.supportsColor=WG();function $(A,X=[]){let J=A===""?[]:[...X,A],U=function(W){if(!w.supportsColor)return W;let Q="",f="";for(let z of J)if(z in l1&&l1[z]in W$){let B=l1[z];Q+=W$[B][0],f=W$[B][1]+f}else if(z in W$)Q+=W$[z][0],f=W$[z][1]+f;return Q+W+f},j=[...Object.keys(W$),...Object.keys(l1)];for(let W of j)if(!(W in U))Object.defineProperty(U,W,{get(){return $(W,J)}});return U}let Y=[...Object.keys(W$),...Object.keys(l1)];for(let A of Y)if(!(A in w))Object.defineProperty(w,A,{get(){return $(A)}});return w}var p1=jG();class zJ extends r6{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(w=""){super();this.name=w,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new fJ(this),this.globalCommand.usage("<command> [options]")}handleSignals(w){if(this.signalHandlersSet)return this;let $=async(Y)=>{if(console.log(`
321
321
 
322
- Received ${Y}, cleaning up...`),w)try{await w()}catch(A){console.error("Error during cleanup:",A)}W$.exit(0)};return W$.on("SIGINT",()=>$("SIGINT")),W$.on("SIGTERM",()=>$("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(w=!0){return this.enableDidYouMean=w,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(w){return this.globalCommand.usage(w),this}command(w,$,Y){if(!Y)Y={};let A=new XG(w,$||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option(w,$,Y){return this.globalCommand.option(w,$,Y),this}help(w){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=w,this.showHelpOnExit=!0,this}version(w,$="-v, --version"){return this.globalCommand.version(w,$),this.showVersionOnExit=!0,this}example(w){return this.globalCommand.example(w),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:w,options:$},Y,A){if(this.args=w,this.options=$,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(w){if(console.log(r1.red(`
322
+ Received ${Y}, cleaning up...`),w)try{await w()}catch(A){console.error("Error during cleanup:",A)}U$.exit(0)};return U$.on("SIGINT",()=>$("SIGINT")),U$.on("SIGTERM",()=>$("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(w=!0){return this.enableDidYouMean=w,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(w){return this.globalCommand.usage(w),this}command(w,$,Y){if(!Y)Y={};let A=new UG(w,$||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option(w,$,Y){return this.globalCommand.option(w,$,Y),this}help(w){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=w,this.showHelpOnExit=!0,this}version(w,$="-v, --version"){return this.globalCommand.version(w,$),this.showVersionOnExit=!0,this}example(w){return this.globalCommand.example(w),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:w,options:$},Y,A){if(this.args=w,this.options=$,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(w){if(console.log(p1.red(`
323
323
  ✗ Command "${w}" not found.
324
- `)),this.enableDidYouMean){let $=[];for(let A of this.commands){if(A.displayName)$.push(A.displayName);if(A.aliasNames)$.push(...A.aliasNames)}let Y=UQ(w,$);if(Y.length>0)console.log(r1.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${r1.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(r1.dim("Run"),`${this.name} --help`,r1.dim("to see all available commands")),W$.exit(1)}async parse(w=ej,$={}){let{run:Y=!0,exitOnError:A=!1}=$;if(A)try{return await this.parse(w,{run:Y})}catch(W){throw this.handleUsageError(W),W}if(this.rawArgs=w,!this.name)this.name=w[1]?e6(w[1]):"cli";let X=!0,J=w.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let W of this.commands)if(W.isMatched(U)){let Q=this.mri(J,W);X=!1;let f={...Q,args:Q.args.slice(1)};this.setParsedInfo(f,W,U),this.emit(`command:${U}`,W);break}}if(X){for(let W of this.commands)if(W.name===""){X=!1;let Q=this.mri(J,W);this.setParsedInfo(Q,W),this.emit("command:!",W);break}}if(X){let W=this.mri(w.slice(2));this.setParsedInfo(W)}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 j={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 j}mri(w,$){let Y=[...this.globalCommand.options,...$?$.options:[]],A=t6(Y),X=[],J=w.indexOf("--");if(J>-1)X=w.slice(J+1),w=w.slice(0,J);let U=p6(w,A),j={_:U._};for(let B of Object.keys(U))if(B!=="_")j[JQ(B)]=U[B];let W=j._,Q={"--":X},f=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,z=Object.create(null);for(let B of Y){if(!f&&B.config.default!==void 0)for(let G of B.names)Q[G]=B.config.default;if(Array.isArray(B.config.type)){if(z[B.name]===void 0)z[B.name]={shouldTransform:!0,transformFunction:B.config.type[0]}}}for(let B of Object.keys(j))if(B!=="_"){let G=B.split(".");s6(Q,G,j[B]),o6(Q,z)}return{args:W,options:Q}}async run(w=ej){return this.parse(w,{run:!0,exitOnError:!0})}handleUsageError(w){if(!(!!w&&typeof w==="object"&&w.name==="ClappError"&&w.isUsageError!==!1))return;let A=w,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
325
- Run \`${this.name??"cli"} --help\` for usage.`;W$.stderr.write(`${J}${X}${U}
326
- `),W$.exit(A.exitCode??2)}async runMatchedCommand(){let{args:w,options:$,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((j,W)=>{if(j.variadic)A.push(w.slice(W));else A.push(w[W])}),A.push($);let X={command:Y,args:A,options:$};for(let j of Y.beforeHooks)await j(X);let J,U=async()=>{let j=Y.commandAction.apply(this,A);if(j instanceof Promise)J=await j;else J=j;return J};if(Y.middleware.length>0){let j=0,W=async()=>{if(j<Y.middleware.length){let Q=Y.middleware[j++];await Q({...X,next:W})}else await U()};await W()}else await U();for(let j of Y.afterHooks)await j(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return W$.removeAllListeners("SIGINT"),W$.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 jQ{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(w){if(!this.enabled){this.misses++;return}let $=this.cache.get(w);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(w),this.misses++;return}return this.hits++,$.value}set(w,$,Y=5000){if(!this.enabled)return;this.cache.set(w,{value:$,timestamp:Date.now(),ttl:Y})}has(w){if(!this.enabled)return!1;let $=this.cache.get(w);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(w),!1;return!0}delete(w){this.cache.delete(w)}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 w=Date.now();for(let[$,Y]of this.cache.entries())if(w-Y.timestamp>Y.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var oR=new jQ;function WG(){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 wQ.isatty(1)&&wQ.isatty(2)}var QQ=WG();function X0(w,$){if(!QQ)return(Y)=>Y;return(Y)=>w+Y+$}var jG=X0("\x1B[0m","\x1B[0m"),QG=X0("\x1B[31m","\x1B[39m"),fG=X0("\x1B[32m","\x1B[39m"),zG=X0("\x1B[33m","\x1B[39m"),BG=X0("\x1B[34m","\x1B[39m"),GG=X0("\x1B[35m","\x1B[39m"),EG=X0("\x1B[36m","\x1B[39m"),KG=X0("\x1B[37m","\x1B[39m"),FG=X0("\x1B[90m","\x1B[39m"),TG=X0("\x1B[1m","\x1B[22m"),NG=X0("\x1B[3m","\x1B[23m"),qG=X0("\x1B[4m","\x1B[24m"),HG=X0("\x1B[2m","\x1B[22m"),RG=X0("\x1B[7m","\x1B[27m"),MG=X0("\x1B[8m","\x1B[28m"),yG=X0("\x1B[9m","\x1B[29m"),IG=X0("\x1B[41m","\x1B[49m"),CG=X0("\x1B[42m","\x1B[49m"),VG=X0("\x1B[43m","\x1B[49m"),LG=X0("\x1B[44m","\x1B[49m"),SG=X0("\x1B[45m","\x1B[49m"),hG=X0("\x1B[46m","\x1B[49m"),OG=X0("\x1B[47m","\x1B[49m"),_G=QQ,DG={reset:jG,red:QG,green:fG,yellow:zG,blue:BG,magenta:GG,cyan:EG,white:KG,gray:FG,bold:TG,italic:NG,underline:qG,dim:HG,inverse:RG,hidden:MG,strikethrough:yG,bgRed:IG,bgGreen:CG,bgYellow:VG,bgBlue:LG,bgMagenta:SG,bgCyan:hG,bgWhite:OG,isColorSupported:_G},aY=DG,kG=["up","down","left","right","space","enter","cancel"],sY={actions:new Set(kG),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function fQ(w,$){if(typeof w==="string")return sY.aliases.get(w)===$;for(let Y of w){if(Y===void 0)continue;if(fQ(Y,$))return!0}return!1}function ZG(w,$){if(w===$)return[];let Y=w.split(`
324
+ `)),this.enableDidYouMean){let $=[];for(let A of this.commands){if(A.displayName)$.push(A.displayName);if(A.aliasNames)$.push(...A.aliasNames)}let Y=jQ(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")),U$.exit(1)}async parse(w=$Q,$={}){let{run:Y=!0,exitOnError:A=!1}=$;if(A)try{return await this.parse(w,{run:Y})}catch(W){throw this.handleUsageError(W),W}if(this.rawArgs=w,!this.name)this.name=w[1]?$G(w[1]):"cli";let X=!0,J=w.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let W of this.commands)if(W.isMatched(U)){let Q=this.mri(J,W);X=!1;let f={...Q,args:Q.args.slice(1)};this.setParsedInfo(f,W,U),this.emit(`command:${U}`,W);break}}if(X){for(let W of this.commands)if(W.name===""){X=!1;let Q=this.mri(J,W);this.setParsedInfo(Q,W),this.emit("command:!",W);break}}if(X){let W=this.mri(w.slice(2));this.setParsedInfo(W)}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 j={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 j}mri(w,$){let Y=[...this.globalCommand.options,...$?$.options:[]],A=s6(Y),X=[],J=w.indexOf("--");if(J>-1)X=w.slice(J+1),w=w.slice(0,J);let U=t6(w,A),j={_:U._};for(let B of Object.keys(U))if(B!=="_")j[WQ(B)]=U[B];let W=j._,Q={"--":X},f=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,z=Object.create(null);for(let B of Y){if(!f&&B.config.default!==void 0)for(let G of B.names)Q[G]=B.config.default;if(Array.isArray(B.config.type)){if(z[B.name]===void 0)z[B.name]={shouldTransform:!0,transformFunction:B.config.type[0]}}}for(let B of Object.keys(j))if(B!=="_"){let G=B.split(".");e6(Q,G,j[B]),wG(Q,z)}return{args:W,options:Q}}async run(w=$Q){return this.parse(w,{run:!0,exitOnError:!0})}handleUsageError(w){if(!(!!w&&typeof w==="object"&&w.name==="ClappError"&&w.isUsageError!==!1))return;let A=w,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
325
+ Run \`${this.name??"cli"} --help\` for usage.`;U$.stderr.write(`${J}${X}${U}
326
+ `),U$.exit(A.exitCode??2)}async runMatchedCommand(){let{args:w,options:$,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((j,W)=>{if(j.variadic)A.push(w.slice(W));else A.push(w[W])}),A.push($);let X={command:Y,args:A,options:$};for(let j of Y.beforeHooks)await j(X);let J,U=async()=>{let j=Y.commandAction.apply(this,A);if(j instanceof Promise)J=await j;else J=j;return J};if(Y.middleware.length>0){let j=0,W=async()=>{if(j<Y.middleware.length){let Q=Y.middleware[j++];await Q({...X,next:W})}else await U()};await W()}else await U();for(let j of Y.afterHooks)await j(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return U$.removeAllListeners("SIGINT"),U$.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 fQ{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(w){if(!this.enabled){this.misses++;return}let $=this.cache.get(w);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(w),this.misses++;return}return this.hits++,$.value}set(w,$,Y=5000){if(!this.enabled)return;this.cache.set(w,{value:$,timestamp:Date.now(),ttl:Y})}has(w){if(!this.enabled)return!1;let $=this.cache.get(w);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(w),!1;return!0}delete(w){this.cache.delete(w)}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 w=Date.now();for(let[$,Y]of this.cache.entries())if(w-Y.timestamp>Y.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var wM=new fQ;function QG(){if("FORCE_COLOR"in r1.env)return r1.env.FORCE_COLOR!=="0";if("NO_COLOR"in r1.env||r1.env.TERM==="dumb")return!1;if(r1.platform==="win32")return!0;return YQ.isatty(1)&&YQ.isatty(2)}var zQ=QG();function J0(w,$){if(!zQ)return(Y)=>Y;return(Y)=>w+Y+$}var fG=J0("\x1B[0m","\x1B[0m"),zG=J0("\x1B[31m","\x1B[39m"),BG=J0("\x1B[32m","\x1B[39m"),GG=J0("\x1B[33m","\x1B[39m"),EG=J0("\x1B[34m","\x1B[39m"),KG=J0("\x1B[35m","\x1B[39m"),FG=J0("\x1B[36m","\x1B[39m"),TG=J0("\x1B[37m","\x1B[39m"),NG=J0("\x1B[90m","\x1B[39m"),qG=J0("\x1B[1m","\x1B[22m"),HG=J0("\x1B[3m","\x1B[23m"),RG=J0("\x1B[4m","\x1B[24m"),MG=J0("\x1B[2m","\x1B[22m"),yG=J0("\x1B[7m","\x1B[27m"),IG=J0("\x1B[8m","\x1B[28m"),CG=J0("\x1B[9m","\x1B[29m"),VG=J0("\x1B[41m","\x1B[49m"),LG=J0("\x1B[42m","\x1B[49m"),SG=J0("\x1B[43m","\x1B[49m"),hG=J0("\x1B[44m","\x1B[49m"),OG=J0("\x1B[45m","\x1B[49m"),_G=J0("\x1B[46m","\x1B[49m"),DG=J0("\x1B[47m","\x1B[49m"),xG=zQ,kG={reset:fG,red:zG,green:BG,yellow:GG,blue:EG,magenta:KG,cyan:FG,white:TG,gray:NG,bold:qG,italic:HG,underline:RG,dim:MG,inverse:yG,hidden:IG,strikethrough:CG,bgRed:VG,bgGreen:LG,bgYellow:SG,bgBlue:hG,bgMagenta:OG,bgCyan:_G,bgWhite:DG,isColorSupported:xG},sY=kG,PG=["up","down","left","right","space","enter","cancel"],oY={actions:new Set(PG),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function BQ(w,$){if(typeof w==="string")return oY.aliases.get(w)===$;for(let Y of w){if(Y===void 0)continue;if(BQ(Y,$))return!0}return!1}function iG(w,$){if(w===$)return[];let Y=w.split(`
327
327
  `),A=$.split(`
328
- `),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var XM=xG.platform.startsWith("win"),$Q=Symbol("clapp:cancel");function pY(w,$){let Y=w;if(Y.isTTY)Y.setRawMode($)}function uG(w){return w.replace(/\x1b\[[0-9;]*m/g,"")}function cG(w){return uG(w).length}function AQ(w,$,Y){if(!$||$<1)return w;let A=Y?.hard??!1,X=Y?.trim??!0,J=w.split(`
329
- `),U=[];for(let j of J){if(cG(j)<=$){U.push(X?j.trimEnd():j);continue}if(A){let W="",Q=0,f=0;while(f<j.length){let z=j.slice(f).match(/^\x1b\[[0-9;]*m/);if(z){W+=z[0],f+=z[0].length;continue}if(Q>=$)U.push(X?W.trimEnd():W),W="",Q=0;W+=j[f],Q++,f++}if(W)U.push(X?W.trimEnd():W)}else U.push(X?j.trimEnd():j)}return U.join(`
330
- `)}class zJ{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=PG,output:A=iG,render:X,signal:J,...U}=w;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=$,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber(w,$){let Y=this._subscribers.get(w)??[];Y.push($),this._subscribers.set(w,Y)}on(w,$){return this.setSubscriber(w,{cb:$}),this}once(w,$){return this.setSubscriber(w,{cb:$,once:!0}),this}emit(w,...$){let Y=this._subscribers.get(w)??[],A=[];for(let X of Y)if(X.cb(...$),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise((w)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),w($Q);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=bG.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),pY(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Zw.show),this.output.off("resize",this.render),pY(this.input,!1),w(this.value)}),this.once("cancel",()=>{this.output.write(Zw.show),this.output.off("resize",this.render),pY(this.input,!1),w($Q)})})}_isActionKey(w,$){return w==="\t"}_setValue(w){this.value=w,this.emit("value",this.value)}_setUserInput(w,$){if(this.userInput=w??"",this.emit("userInput",this.userInput),$&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(w,$){if(this._track&&$.name!=="return"){if($.name&&this._isActionKey(w,$))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=$.name==="tab"||$.name==="escape"||$.name==="backspace"||$.name==="delete"||$.name==="enter"||$.name==="return"||$.name&&["up","down","left","right"].includes($.name);if(w&&!Y&&w.length===1&&w>=" ")this._manualLine+=w;else if($.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($?.name){if(!this._track&&sY.aliases.has($.name))this.emit("cursor",sY.aliases.get($.name));if(sY.actions.has($.name))this.emit("cursor",$.name)}if(w&&(w.toLowerCase()==="y"||w.toLowerCase()==="n"))this.emit("confirm",w.toLowerCase()==="y");if(this.emit("key",w?.toLowerCase(),$),$?.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(fQ([w,$?.name,$?.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(`
331
- `),pY(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 w=AQ(this._prevFrame,YQ.stdout.columns,{hard:!0,trim:!1}).split(`
332
- `).length-1;this.output.write(Zw.move(-999,w*-1))}render(){let w=AQ(this._render(this)??"",YQ.stdout.columns,{hard:!0,trim:!1});if(w===this._prevFrame)return;if(this.state==="initial")this.output.write(Zw.hide);else{let $=ZG(this._prevFrame,w);if(this.restoreCursor(),$&&$?.length===1){let Y=$[0];this.output.write(Zw.move(0,Y)),this.output.write(JJ.lines(1));let A=w.split(`
333
- `);this.output.write(A[Y]),this._prevFrame=w,this.output.write(Zw.move(0,A.length-Y-1));return}if($&&$?.length>1){let Y=$[0];this.output.write(Zw.move(0,Y)),this.output.write(JJ.down());let X=w.split(`
328
+ `),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var UM=ZG.platform.startsWith("win"),AQ=Symbol("clapp:cancel");function rY(w,$){let Y=w;if(Y.isTTY)Y.setRawMode($)}function vG(w){return w.replace(/\x1b\[[0-9;]*m/g,"")}function mG(w){return vG(w).length}function JQ(w,$,Y){if(!$||$<1)return w;let A=Y?.hard??!1,X=Y?.trim??!0,J=w.split(`
329
+ `),U=[];for(let j of J){if(mG(j)<=$){U.push(X?j.trimEnd():j);continue}if(A){let W="",Q=0,f=0;while(f<j.length){let z=j.slice(f).match(/^\x1b\[[0-9;]*m/);if(z){W+=z[0],f+=z[0].length;continue}if(Q>=$)U.push(X?W.trimEnd():W),W="",Q=0;W+=j[f],Q++,f++}if(W)U.push(X?W.trimEnd():W)}else U.push(X?j.trimEnd():j)}return U.join(`
330
+ `)}class BJ{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=bG,output:A=uG,render:X,signal:J,...U}=w;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=$,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber(w,$){let Y=this._subscribers.get(w)??[];Y.push($),this._subscribers.set(w,Y)}on(w,$){return this.setSubscriber(w,{cb:$}),this}once(w,$){return this.setSubscriber(w,{cb:$,once:!0}),this}emit(w,...$){let Y=this._subscribers.get(w)??[],A=[];for(let X of Y)if(X.cb(...$),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise((w)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),w(AQ);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=cG.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),rY(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(xw.show),this.output.off("resize",this.render),rY(this.input,!1),w(this.value)}),this.once("cancel",()=>{this.output.write(xw.show),this.output.off("resize",this.render),rY(this.input,!1),w(AQ)})})}_isActionKey(w,$){return w==="\t"}_setValue(w){this.value=w,this.emit("value",this.value)}_setUserInput(w,$){if(this.userInput=w??"",this.emit("userInput",this.userInput),$&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(w,$){if(this._track&&$.name!=="return"){if($.name&&this._isActionKey(w,$))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=$.name==="tab"||$.name==="escape"||$.name==="backspace"||$.name==="delete"||$.name==="enter"||$.name==="return"||$.name&&["up","down","left","right"].includes($.name);if(w&&!Y&&w.length===1&&w>=" ")this._manualLine+=w;else if($.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($?.name){if(!this._track&&oY.aliases.has($.name))this.emit("cursor",oY.aliases.get($.name));if(oY.actions.has($.name))this.emit("cursor",$.name)}if(w&&(w.toLowerCase()==="y"||w.toLowerCase()==="n"))this.emit("confirm",w.toLowerCase()==="y");if(this.emit("key",w?.toLowerCase(),$),$?.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(BQ([w,$?.name,$?.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(`
331
+ `),rY(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 w=JQ(this._prevFrame,XQ.stdout.columns,{hard:!0,trim:!1}).split(`
332
+ `).length-1;this.output.write(xw.move(-999,w*-1))}render(){let w=JQ(this._render(this)??"",XQ.stdout.columns,{hard:!0,trim:!1});if(w===this._prevFrame)return;if(this.state==="initial")this.output.write(xw.hide);else{let $=iG(this._prevFrame,w);if(this.restoreCursor(),$&&$?.length===1){let Y=$[0];this.output.write(xw.move(0,Y)),this.output.write(UJ.lines(1));let A=w.split(`
333
+ `);this.output.write(A[Y]),this._prevFrame=w,this.output.write(xw.move(0,A.length-Y-1));return}if($&&$?.length>1){let Y=$[0];this.output.write(xw.move(0,Y)),this.output.write(UJ.down());let X=w.split(`
334
334
  `).slice(Y);this.output.write(X.join(`
335
- `)),this._prevFrame=w;return}this.output.write(JJ.down())}if(this.output.write(w),this.state==="initial")this.state="active";this._prevFrame=w}}function vG(w,$){if(w===void 0)return 0;if($.length===0)return 0;let A=$.findIndex((X)=>X.value===w);return A!==-1?A:0}function mG(w,$){return($.label??String($.value)).toLowerCase().includes(w.toLowerCase())}function gG(w,$){if(!$)return;if(w)return $;return $[0]}class dG extends zJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#w=0;#Y="";#A;#$;get cursor(){return this.#w}get userInputWithCursor(){if(!this.userInput)return aY.inverse(aY.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let w=this.userInput.slice(0,this._cursor),[$,...Y]=this.userInput.slice(this._cursor);return`${w}${aY.inverse($)}${Y.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(w){super(w);this.#$=w.options;let $=this.options;this.filteredOptions=[...$],this.multiple=w.multiple===!0,this.#A=w.filter??mG;let Y;if(w.initialValue&&Array.isArray(w.initialValue))if(this.multiple)Y=w.initialValue;else Y=w.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 X=$.findIndex((J)=>J.value===A);if(X!==-1)this.toggleSelected(A),this.#w=X}this.focusedValue=this.options[this.#w]?.value,this.on("key",(A,X)=>this.#X(A,X)),this.on("userInput",(A)=>this.#J(A))}_isActionKey(w,$){return w==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&w!==void 0&&w!==""}#X(w,$){let Y=$.name==="up",A=$.name==="down",X=$.name==="return";if(Y||A){if(this.#w=Math.max(0,Math.min(this.#w+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=gG(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.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(w){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(w))this.selectedValues=this.selectedValues.filter(($)=>$!==w);else this.selectedValues=[...this.selectedValues,w];else this.selectedValues=[w]}#J(w){if(w!==this.#Y){this.#Y=w;let $=this.options;if(w)this.filteredOptions=$.filter((Y)=>this.#A(w,Y));else this.filteredOptions=[...$];if(this.#w=vG(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class nG extends zJ{options;cursor=0;#w;getGroupItems(w){return this.options.filter(($)=>$.group===w)}isGroupSelected(w){let $=this.getGroupItems(w),Y=this.value;if(Y===void 0)return!1;return $.every((A)=>Y.includes(A.value))}toggleValue(){let w=this.options[this.cursor];if(this.value===void 0)this.value=[];if(w.group===!0){let $=String(w.value),Y=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((A)=>Y.findIndex((X)=>X.value===A)===-1);else this.value=[...this.value,...Y.map((A)=>A.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(w.value);this.value=$?this.value.filter((Y)=>Y!==w.value):[...this.value,w.value]}}constructor(w){super(w,!1);let{options:$}=w;this.#w=w.selectableGroups!==!1,this.options=Object.entries($).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((X)=>({...X,group:Y}))]),this.value=[...w.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===w.cursorAt),this.#w?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.#w&&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.#w&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var lG=wG();var w0=(w,$)=>lG?w:$,WM=w0("◆","*"),jM=w0("■","x"),QM=w0("▲","x"),fM=w0("◇","o"),zM=w0("┌","T"),pG=w0("│","|"),BM=w0("└","—"),GM=w0("●",">"),EM=w0("○"," "),KM=w0("◻","[•]"),FM=w0("◼","[+]"),TM=w0("◻","[ ]"),NM=w0("▪","•"),qM=w0("─","-"),HM=w0("╮","+"),RM=w0("├","+"),MM=w0("╯","+"),yM=w0("●","•"),IM=w0("◆","*"),CM=w0("▲","!"),VM=w0("■","x");var LM={light:w0("─","-"),heavy:w0("━","="),block:w0("█","#")};function rG(){return`${aY.gray(pG)} `}var SM=rG();PA();UU();P8();x$();z0();import{spawn as RR}from"node:child_process";import*as m8 from"node:process";class g8{processes=new Map;isShuttingDown=!1;async startProcess(w,$,Y){if(this.processes.has(w)){E("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||m8.cwd();E("start",`Starting process ${w}:`,Y),E("start",` Command: ${A} ${X.join(" ")}`,Y),E("start",` Working directory: ${J}`,Y),E("start",` Environment variables: ${A$($.env)}`,Y);let U=RR(A,X,{cwd:J,env:{...m8.env,...$.env},shell:!0,stdio:"inherit"});return this.processes.set(w,{command:$.command,cwd:J,process:U,env:$.env}),new Promise((j,W)=>{if(U.on("error",(Q)=>{if(!this.isShuttingDown)E("start",`Process ${w} failed to start: ${Q}`,Y),this.processes.delete(w),W(Q)}),U.on("exit",(Q)=>{if(!this.isShuttingDown&&Q!==null&&Q!==0)E("start",`Process ${w} exited with code ${Q}; leaving the proxy running`,Y),this.processes.delete(w),W(Error(`Process ${w} exited with code ${Q}`))}),Y)U.stdout?.on("data",(Q)=>{E("process",`[${w}] ${Q.toString().trim()}`,!0)}),U.stderr?.on("data",(Q)=>{E("process",`[${w}] ERR: ${Q.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete(w),W(Error(`Process ${w} was killed during startup`));else E("start",`Process ${w} started successfully`,Y),j()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);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(w),E("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){E("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){E("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){E("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,E("start","Stopping all processes",w);let $=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,w).catch((A)=>{H.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled($),this.processes.clear(),this.isShuttingDown=!1}isRunning(w){let $=this.processes.get(w);return!!$?.process&&!$.process.killed}}var d8=new g8;g$();x$();import{execSync as SR}from"node:child_process";import*as s8 from"node:http";import*as h6 from"node:net";import*as O6 from"node:os";import*as _6 from"node:path";import*as t from"node:process";var n8=(w,$)=>(Y)=>`\x1B[${w}m${Y}\x1B[${$}m`,Ow={bold:n8(1,22),dim:n8(2,22),green:n8(32,39),cyan:n8(36,39)};PA();P8();x$();g$();z0();import*as I6 from"node:fs";import*as C6 from"node:path";import*as _w from"node:process";function MR(w,$){let A=($&&$!=="/"?`${w}${$}`:w).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function mj(w){if(w.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let $=w.verbose??!1,Y=w.registryDir,A=new Set,X=w.proxies.map((B)=>{let G=B.id??MR(B.to,B.path);if(!C$(G))throw Error(`invalid registry id "${G}" derived from to="${B.to}"`);if(A.has(G))throw Error(`duplicate registry id "${G}" — set an explicit \`id\` on one of the proxies`);return A.add(G),{...B,id:G}}),J=new Date().toISOString();for(let B of X)await c1({id:B.id,from:B.from,to:B.to,path:B.path,pid:w.persistent?void 0:_w.pid,cwd:_w.cwd(),createdAt:J,cleanUrls:B.cleanUrls,changeOrigin:B.changeOrigin,pathRewrites:B.pathRewrites,static:B.static,loadBalancer:B.loadBalancer},Y,$);let U=await v8({rpxDir:w.rpxDir,verbose:$,spawnCommand:w.spawnCommand,startupTimeoutMs:w.startupTimeoutMs,spawnEnv:w.spawnEnv});for(let B of X){let G=B.static?`static ${typeof B.static==="string"?B.static:B.static.dir}`:B.from;H.success(`https://${B.to} → ${G}`)}if(H.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),w.detached)return;let j=!1,W=Y??$w(),Q=X.map((B)=>B.id),f=async()=>{if(j)return;j=!0;for(let B of Q)await m$(B,Y,$).catch((G)=>{E("runner",`removeEntry(${B}) failed: ${G}`,$)})},z=(B)=>{E("runner",`received ${B}, unregistering ${Q.length} entries`,$),f().finally(()=>_w.exit(0))};_w.once("SIGINT",z),_w.once("SIGTERM",z),_w.once("exit",()=>{if(j)return;for(let B of Q)try{I6.unlinkSync(C6.join(W,`${B}.json`))}catch{}}),await new Promise(()=>{})}hj();fj();Hj();import{timingSafeEqual as yR}from"node:crypto";function IR(w,$){if(w==null)return!1;let Y=Buffer.from(w),A=Buffer.from($);if(Y.length!==A.length)return!1;return yR(Y,A)}function l8(w){return w.toLowerCase().replace(/\.$/,"")}var CR=["/.well-known/acme-challenge/"];function VR(w){let $=w.headers.get("host");if($)return l8($.split(":")[0]);try{return l8(new URL(w.url).hostname)}catch{return""}}function V6(w){let $=w.header.toLowerCase(),Y=new Set,A=[];for(let W of w.hosts){let Q=l8(W);if(Q.startsWith("*."))A.push(Q);else Y.add(Q)}let X=w.exemptPaths??CR,J=w.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
336
- `,U=(W)=>{let Q=l8(W);return Y.has(Q)||A.some((f)=>$Y(Q,f))},j=(W)=>{let Q=VR(W);if(!U(Q))return;let f="/";try{f=new URL(W.url).pathname}catch{}if(X.some((z)=>f.startsWith(z)))return;if(IR(W.headers.get($),w.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return j.protects=U,j}Gj();Ej();F8();M8();Tj();Nj();H8();z0();var L6={name:"@stacksjs/rpx",type:"module",version:"0.11.39",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build ./bin/cli.ts --compile --minify --outfile bin/rpx",compile:"bun build ./bin/cli.ts --compile --minify --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.13"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var dY=L6.version;var r8=new g8,hR=new C8("0.0.0.0"),nY=new Set,a8=new Set,gj=!1,p8=null,dj=null;async function o8(w){if(gj)return E("cleanup","Cleanup already in progress, skipping",w?.verbose),dj||Promise.resolve();gj=!0,E("cleanup","Starting cleanup process",w?.verbose),dj=new Promise(($)=>{p8=$});try{await r8.stopAll(w?.verbose),H.info("Shutting down proxy servers...");let $=[],Y=Array.from(nY).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),E("cleanup","Bun server stopped",w?.verbose),X();else if(typeof J.close==="function")J.close(()=>{E("cleanup","Server closed successfully",w?.verbose),X()});else X()}catch(U){E("cleanup",`Error stopping server: ${U}`,w?.verbose),X()}}));$.push(...Y),nY.clear();for(let A of a8)b1(A);if(a8.clear(),w?.hosts&&w.domains?.length){E("cleanup","Cleaning up hosts file entries",w?.verbose),E("cleanup",`Original domains for cleanup: ${JSON.stringify(w.domains)}`,w?.verbose);let A=w.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(E("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,w?.verbose),A.length>0)H.info("Cleaning up hosts file entries..."),$.push(a2(A,w?.verbose).then(()=>{E("cleanup",`Removed hosts entries for ${A.join(", ")}`,w?.verbose)}).catch((X)=>{E("cleanup",`Failed to remove hosts entries: ${X}`,w?.verbose),H.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if(w?.certs&&w.domains?.length){E("cleanup","Cleaning up SSL certificates",w?.verbose),H.info("Cleaning up SSL certificates...");let A=w.domains.map(async(X)=>{try{await f2(X,w?.verbose),E("cleanup",`Removed certificates for ${X}`,w?.verbose)}catch(J){E("cleanup",`Failed to remove certificates for ${X}: ${J}`,w?.verbose),H.warn(`Failed to clean up certificates for ${X}:`,J)}});$.push(...A)}await Promise.allSettled($),E("cleanup","All cleanup tasks completed successfully",w?.verbose),H.success("All cleanup tasks completed successfully")}catch($){E("cleanup",`Error during cleanup: ${$}`,w?.verbose),H.error("Error during cleanup:",$)}finally{if(p8)p8();p8=null,gj=!1;let $=w&&"vitePluginUsage"in w&&w.vitePluginUsage===!0;if(t.env.NODE_ENV!=="test"&&t.env.BUN_ENV!=="test"&&!$)t.exit(0)}return dj}var nj=!1;function D6(w){if(nj){E("signal",`Received second ${w} signal, forcing exit`,!0),t.exit(1);return}nj=!0,E("signal",`Received ${w} signal, initiating cleanup`,!0),o8().catch(($)=>{E("signal",`Cleanup failed after ${w}: ${$}`,!0),t.exit(1)}).finally(()=>{nj=!1})}t.once("SIGINT",()=>D6("SIGINT"));t.once("SIGTERM",()=>D6("SIGTERM"));t.on("uncaughtException",(w)=>{H.error("Uncaught exception (continuing):",w)});t.on("unhandledRejection",(w)=>{H.error("Unhandled rejection (continuing):",w)});async function lY(w,$,Y,A=5){E("connection",`Testing connection to ${w}:${$} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(t.env.RPX_BYPASS_CONNECTION_TEST==="true"){E("connection",`Bypassing connection test for ${w}:${$} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((j,W)=>{let Q=h6.connect({host:w,port:$,timeout:3000});Q.once("connect",()=>{E("connection",`Successfully connected to ${w}:${$}`,Y),Q.end(),j()}),Q.once("timeout",()=>{E("connection",`Connection to ${w}:${$} timed out`,Y),Q.destroy(),W(Error("Connection timed out"))}),Q.once("error",(f)=>{E("connection",`Failed to connect to ${w}:${$}: ${f}`,Y),Q.destroy(),W(f)})});try{await U()}catch(j){let W=j;if(Date.now()-J>X){E("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),H.warn(`Connection test to ${w}:${$} timed out, but RPX will try to proceed anyway.`);return}if(W.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((f)=>setTimeout(f,2000)),lY(w,$,Y,A-1);if(A>0)try{E("connection",`Trying HTTP request to ${w}:${$}`,Y),await new Promise((f,z)=>{let B=s8.request({hostname:w,port:$,path:"/",method:"HEAD",timeout:5000},(G)=>{E("connection",`Received HTTP response with status: ${G.statusCode}`,Y),f()});B.on("error",(G)=>z(G)),B.on("timeout",()=>{B.destroy(),z(Error("HTTP request timed out"))}),B.end()}),E("connection",`HTTP request to ${w}:${$} succeeded`,Y);return}catch(f){return E("connection",`HTTP request to ${w}:${$} failed: ${f}`,Y),E("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),lY(w,$,Y,A-1)}let Q=`Failed to connect to ${w}:${$} after ${5-A} attempts: ${W.message}`;E("connection",`${Q}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),H.warn(Q),H.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 x6(w){E("server",`Starting server with options: ${A$(w)}`,w.verbose);let $=u$(w.from),Y=new URL($.startsWith("http")?$:`http://${$}`),A=new URL((w.to?.startsWith("http")?w.to:`http://${w.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(lj(w)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){E("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,w?.verbose);try{if(!(await uY(J,w.verbose))[0]){H.info(`Adding ${A.hostname} to hosts file...`),H.info("This may require sudo/administrator privileges");try{await bY(J,w.verbose)}catch(W){if(H.error("Failed to add hosts entry:",W.message),H.warn("You can manually add this entry to your hosts file:"),H.warn(`127.0.0.1 ${A.hostname}`),H.warn(`::1 ${A.hostname}`),t.platform==="win32")H.warn("On Windows:"),H.warn("1. Run notepad as administrator"),H.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else H.warn("On Unix systems:"),H.warn("sudo nano /etc/hosts")}}else E("hosts",`Host entry already exists for ${A.hostname}`,w.verbose)}catch(j){H.error("Failed to check hosts file:",j.message)}}try{await lY(Y.hostname,X,w.verbose)}catch(j){E("server",`Connection test failed: ${j}`,w.verbose),H.error(j.message),H.warn("Continuing with proxy setup despite connection test failure..."),H.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=w._cachedSSLConfig||null;if(w.https)try{if(w.https===!0)w.https=RY({...w,to:A.hostname});if(U=await y$({...w,to:A.hostname,https:w.https}),!U){if(E("ssl",`Generating new certificates for ${A.hostname}`,w.verbose),await HY({...w,from:Y.toString(),to:A.hostname,https:w.https}),U=await y$({...w,to:A.hostname,https:w.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(j){throw E("server",`SSL setup failed: ${j}`,w.verbose),j}E("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,w.verbose),await _R({...w,from:$,originalFrom:w.from||$,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function OR(w,$,Y,A,X,J,U,j,W,Q,f,z){E("proxy",`Creating proxy server ${w} -> ${$} with cleanUrls: ${j}`,U);let B=MY(f??A.host,z);IY(B);let G=[{host:$,route:{sourceHost:A.host,upstreamPool:B,cleanUrls:j||!1,changeOrigin:W||!1,basePath:"/",auth:Q}}];if(!t8({routeEntries:G,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw b1(B),Error(`Failed to start proxy server for ${$} on port ${Y}`);a8.add(B),xR({from:w,to:$,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:j,verbose:U})}async function _R(w){E("setup",`Setting up reverse proxy: ${A$(w)}`,w.verbose);let{from:$,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:j,vitePluginUsage:W,changeOrigin:Q,cleanUrls:f}=w,z=80,B=443,G="0.0.0.0",T=w.portManager||hR,K=lj(w);try{if(K&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await uY([A],U))[0]){H.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await bY([A],U),H.success(`Added ${A} to your hosts file.`)}catch(V){H.error(`Failed to add ${A} to your hosts file: ${V}`),H.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(K&&t.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await uY([A],U))[0]){E("hosts",`${A} not found in hosts file, adding...`,U);try{await bY([A],U)}catch(V){E("hosts",`Failed to add ${A} to hosts file: ${V}`,U)}}}if(J&&!T.usedPorts.has(z)){if(!await I$(z,G,U))E("setup","Starting HTTP redirect server",U),k6(U),T.usedPorts.add(z);else if(E("setup","Port 80 is in use, skipping HTTP redirect",U),U)H.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let F=J?B:z,N=await I$(F,G,U),R;if(N){if(E("setup",`Port ${F} is already in use`,U),U)H.warn(`Port ${F} is already in use. This may be another instance of rpx or another service.`);if(F===443){if(R=await T.getNextAvailablePort(3443,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await T.getNextAvailablePort(F+1000,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=F,T.usedPorts.add(R),E("setup",`Using standard ${F===443?"HTTPS":"HTTP"} port ${F} for ${A}`,U);await OR($,A,R,X,J,W,U,f,Q,VY(w.auth),Y,w.loadBalancer)}catch(F){E("setup",`Setup failed: ${F}`,U),H.error(`Failed to setup reverse proxy: ${F.message}`),o8({domains:[A],hosts:typeof j==="boolean"?j:j?.hosts,certs:typeof j==="boolean"?j:j?.certs,verbose:U,vitePluginUsage:W})}}function k6(w,$=80,Y=443,A,X){E("redirect",`Starting HTTP redirect server on port ${$}`,w);let J=s8.createServer((U,j)=>{let W=U.url?U.url.split("?",1)[0]:"";if(W.startsWith("/.well-known/acme-challenge/")){if(X){let B=X.challengeStore.handlePath(W);if(B!==void 0){E("redirect",`Serving on-demand ACME challenge ${W}`,w),j.writeHead(200,{"content-type":"text/plain"}),j.end(B);return}}if(A){let B=R8(A,W);if(B!=null){E("redirect",`Serving ACME challenge ${W}`,w),j.writeHead(200,{"content-type":"text/plain"}),j.end(B);return}}if(X){j.writeHead(404,{"content-type":"text/plain"}),j.end("challenge not found");return}}let Q=U.headers.host||"",f=Q.includes(":")?Q.slice(0,Q.indexOf(":")):Q;if(X&&f&&!X.hasCert(f))X.ensureCert(f).catch(()=>{});let z=Y===443?f:`${f}:${Y}`;E("redirect",`Redirecting request from ${Q}${U.url} to https://${z}`,w),j.writeHead(301,{Location:`https://${z}${U.url}`}),j.end()}).listen($);nY.add(J),E("redirect","HTTP redirect server started",w)}function Z6(w){let $={...mw,...w};if(E("proxy",`Starting proxy with options: ${A$($)}`,$?.verbose),$.viaDaemon){if(!$.from||!$.to){H.error("viaDaemon mode requires both `from` and `to`");return}mj({proxies:[{id:$.id,from:$.from,to:$.to,path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}],verbose:$.verbose}).catch((W)=>{H.error(`Failed to register with rpx daemon: ${W.message}`),t.exit(1)});return}let Y=$.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=t.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&$?.verbose)H.warn(`The .${A} TLD may not work reliably for local development`),H.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),H.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (gY(),Z8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:$.verbose}).then((Q)=>{if(Q)Promise.resolve().then(()=>{if($.verbose)if(U.includes(A))H.success(`DNS server started for .${A} domains`);else H.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`,$.verbose)})}).catch((W)=>{E("dns",`Failed to start DNS server: ${W}`,$.verbose)});let j={from:$.from,to:$.to,cleanUrls:$.cleanUrls,https:RY($),cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,changeOrigin:$.changeOrigin,verbose:$.verbose,regenerateUntrustedCerts:$.regenerateUntrustedCerts};E("proxy",`Server options: ${A$(j)}`,$.verbose),x6(j).catch((W)=>{E("proxy",`Failed to start proxy: ${W}`,$.verbose),H.error(`Failed to start proxy: ${W.message}`),o8({domains:[$.to],hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose})})}function DR(w){return w?.verbose||!1}function lj(w){if(w?.hostsManagement===!1)return!1;let $=w?.cleanup;if($===!1)return!1;if($&&typeof $==="object"&&$.hosts===!1)return!1;return!0}async function P6(w){let $={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=DR($),A=lj($);if(E("config",`Starting with config: ${A$($,2)}`,Y),E("config",`Is multi-proxy? ${"proxies"in $}`,Y),E("config",`Hosts management enabled? ${A}`,Y),$.viaDaemon){let M="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((C)=>({id:C.id,from:C.from,to:C.to,path:C.path,cleanUrls:C.cleanUrls??$.cleanUrls,changeOrigin:C.changeOrigin??$.changeOrigin,pathRewrites:C.pathRewrites})):[{id:$.id,from:$.from,to:$.to??"rpx.localhost",path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}];await mj({proxies:M,verbose:Y});return}if("proxies"in $&&Array.isArray($.proxies)){E("servers",`Found ${$.proxies.length} proxies in config`,Y);for(let q of $.proxies)if(q.start){let M=`${q.from}-${q.to}`;try{E("watch",`Starting command for ${M} with command: ${q.start.command}`,Y),H.info(`Starting command for ${M}...`),await r8.startProcess(M,q.start,Y);let C=u$(q.from),O=new URL(C.startsWith("http")?C:`http://${C}`),J0=O.hostname||"localhost",u0=Number(O.port)||80;try{await lY(J0,u0,Y),E("watch",`Dev server is ready at ${J0}:${u0}`,Y)}catch(Gw){E("watch",`Connection check failed, but continuing with proxy setup: ${Gw}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(C){throw E("watch",`Failed to start command for ${M}: ${C}`,Y),Error(`Failed to start command for ${M}: ${C}`)}}else E("watch",`No start command for proxy ${q.from} -> ${q.to}`,Y)}else if("start"in $&&$.start){E("watch","Found start command in single proxy config",Y);let q=`${$.from}-${$.to}`;try{if($.start)E("watch",`Starting command: ${$.start.command}`,Y),await r8.startProcess(q,$.start,Y);let M=u$($.from),C=new URL(M.startsWith("http")?M:`http://${M}`),O=C.hostname||"localhost",J0=Number(C.port)||80;try{await lY(O,J0,Y),E("watch",`Dev server is ready at ${O}:${J0}`,Y)}catch(u0){E("watch",`Connection check failed, but continuing with proxy setup: ${u0}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw E("watch",`Failed to run start command: ${M}`,Y),Error(`Failed to run start command: ${M}`)}}else E("watch","No start command found in config",Y);let X="proxies"in $&&Array.isArray($.proxies)?$.proxies[0]?.to:("to"in $)?$.to:"rpx.localhost";if(t.platform!=="win32"&&($.https||A)){if(!T$())try{E("sudo","Pre-acquiring sudo credentials for privileged operations",Y),SR("sudo -v",{stdio:"inherit"})}catch{E("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if($.productionCerts){if(J=await xY($.productionCerts,Y),J.length>0)E("ssl",`Using ${J.length} production SNI cert(s): ${J.map((q)=>q.serverName).join(", ")}`,Y)}if($.https){let q=J.length>0?null:await y$($);if(!q&&J.length===0){if(E("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,$.verbose),await HY($),q=await y$($),!q)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else E("ssl",`Using existing and trusted certificates for ${X}`,$.verbose);$._cachedSSLConfig=q}let U="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((q)=>({...q,https:$.https,cleanup:$.cleanup,cleanUrls:q.cleanUrls??("cleanUrls"in $?$.cleanUrls:!1),vitePluginUsage:$.vitePluginUsage,changeOrigin:q.changeOrigin??$.changeOrigin,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig})):[{from:"from"in $?$.from:"localhost:5173",to:"to"in $?$.to:"rpx.localhost",cleanUrls:"cleanUrls"in $?$.cleanUrls:!1,https:$.https,cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,start:"start"in $?$.start:void 0,changeOrigin:$.changeOrigin,auth:"auth"in $?$.auth:void 0,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig}],j=U.map((q)=>q.to||"rpx.localhost"),W=J.length>0?J:$._cachedSSLConfig??null,Q=j.filter((q)=>q&&!q.includes("localhost")&&!q.includes("127.0.0.1")),f=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"],B=[...new Set(Q.map((q)=>q.split(".").pop()?.toLowerCase()))],G=B.filter((q)=>!!q&&f.includes(q));if(G.length>0&&Y)H.warn(`The following TLDs may not work reliably for local development: ${G.map((q)=>`.${q}`).join(", ")}`),H.info(" These TLDs have HSTS preloading which can bypass local DNS"),H.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&t.platform==="darwin"&&Q.length>0){let{setupDevelopmentDns:q}=await Promise.resolve().then(() => (gY(),Z8));if(await q({domains:Q,verbose:Y})){if(Y)if(B.every((O)=>!!O&&z.includes(O)))H.success(`DNS server started for ${B.map((O)=>`.${O}`).join(", ")} domains`);else H.success(`DNS server started for ${B.map((O)=>`.${O}`).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",$.verbose);try{let{tearDownDevelopmentDns:q}=await Promise.resolve().then(() => (gY(),Z8));await q({verbose:$.verbose})}catch(q){E("cleanup",`Error stopping DNS server: ${q}`,$.verbose)}try{await r8.stopAll($.verbose)}catch(q){E("cleanup",`Error stopping processes: ${q}`,$.verbose)}await o8({domains:j,hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose||!1})};t.on("SIGINT",T),t.on("SIGTERM",T);let K=$.singlePortMode===!0,F=$.httpsPort??443,N=$.httpPort??80,R=$.originGuard?V6($.originGuard):null,L=!!W&&(U.length>1||K||J.length>0),V=!W&&K&&U.length>0;if(L&&W){E("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${F}`,Y);let q=await S6(U,A,Y),M=null,C=$.onDemandTls,O=C?.enabled?new u1({config:C,certsDir:C.certsDir??$.productionCerts?.certsDir??_6.join(O6.homedir(),".stacks","rpx","on-demand-certs"),initial:J,verbose:Y,onCertAdded:(Ew)=>{if(kY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",Y),setTimeout(()=>t.kill(t.pid,"SIGTERM"),10).unref();else Gw(Ew)}}):null,J0=null,u0=!1;async function Gw(Ew){if(J0=Ew,u0)return;u0=!0;try{while(J0){let kw=J0;if(J0=null,E("proxies",`rebuilding :${F} with ${kw.length} SNI cert(s)`,Y),M)nY.delete(M),M.stop(!1);let t0=!1;for(let _=0;!t0&&_<60;_++){let Cw=t8({routeEntries:q,listenPort:F,sslConfig:kw,originGuard:R,verbose:Y});if(Cw){M=Cw,t0=!0;break}await new Promise((n1)=>setTimeout(n1,Math.min(25*2**Math.min(_,4),500)))}if(!t0)H.error(`rpx: CRITICAL — could not rebind :${F} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{u0=!1}}if(!await I$(N,"0.0.0.0",Y))k6(Y,N,F,$.acmeChallengeWebroot,O);if(await I$(F,"0.0.0.0",Y)){if(E("proxies",`Port ${F} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${F} is in use. Shared HTTPS proxy cannot start.`);return}let xw=O&&O.sniEntries().length>0?O.sniEntries():W;if(M=t8({routeEntries:q,listenPort:F,sslConfig:xw,originGuard:R,verbose:Y}),!M){H.error(`Shared HTTPS proxy failed to bind :${F}; not exiting`);return}}else if(V){E("proxies",`Creating shared HTTP server for ${U.length} domains on port ${N}`,Y);let q=await S6(U,A,Y);if(await I$(N,"0.0.0.0",Y)){if(E("proxies",`Port ${N} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${N} is in use. Shared HTTP proxy cannot start.`);return}if(!t8({routeEntries:q,listenPort:N,sslConfig:null,originGuard:R,verbose:Y})){H.error(`Shared HTTP proxy failed to bind :${N}; not exiting`);return}}else for(let q of U)try{let M=q.to||"rpx.localhost";E("proxy",`Starting proxy for ${M} with SSL config: ${!!W}`,q.verbose),await x6({from:q.from||"localhost:5173",to:M,cleanUrls:q.cleanUrls||!1,https:q.https||!1,cleanup:q.cleanup||!1,vitePluginUsage:q.vitePluginUsage||!1,verbose:q.verbose||!1,_cachedSSLConfig:$._cachedSSLConfig,changeOrigin:q.changeOrigin||!1,loadBalancer:q.loadBalancer,auth:q.auth,path:q.path,pathRewrites:q.pathRewrites})}catch(M){E("proxies",`Failed to start proxy for ${q.to}: ${M}`,q.verbose),H.error(`Failed to start proxy for ${q.to}:`,M)}}async function S6(w,$,Y){let A=[],X=new Set;for(let J of w){let U=J.to||"rpx.localhost",j=J.cleanUrls||!1,W=J.path,Q=X$(W),f=VY(J.auth);if(J.redirect){let z=V2(J.redirect);A.push({host:U,path:W,route:{redirect:z,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → redirect ${z.status} ${z.to}${f?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:q8(J.static,j),cleanUrls:j,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${f?" (auth)":""}`,Y);else{let z=u$(J.from),B=new URL(z.startsWith("http")?z:`http://${z}`),G=MY(J.from??B.host,J.loadBalancer);IY(G),a8.add(G),A.push({host:U,path:W,route:{sourceHost:B.host,upstreamPool:G,cleanUrls:j,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → ${B.host}${f?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),$&&!j1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await uY([U],Y))[0])await bY([U],Y)}catch{E("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function t8(w){let{routeEntries:$,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=w,U=OY($),j=SY((f,z)=>_Y(U,f,z),J),W=X?(f,z)=>X(f)??j(f,z):j,Q=hY(J);try{let f=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:NY(),...A?{tls:v$(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,B){return W(z,B)},websocket:Q,error(z){return E("server",`Shared proxy server error: ${z}`,J),new Response(`Server Error: ${z.message}`,{status:500})}});return nY.add(f),E("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),f}catch(f){return E("proxies",`Failed to start shared proxy: ${f}`,J),console.error("Failed to start shared proxy:",f),null}}function xR(w){if(w?.vitePluginUsage||!w?.verbose)return;if(console.log(""),console.log(` ${Ow.green(Ow.bold("rpx"))} ${Ow.green(`v${dY}`)}`),console.log(` ${Ow.green("➜")} ${Ow.dim(w?.from??"")} ${Ow.dim("➜")} ${Ow.cyan(w?.ssl?`https://${w?.to}`:`http://${w?.to}`)}`),w?.listenPort!==(w?.ssl?443:80))console.log(` ${Ow.green("➜")} Listening on port ${w?.listenPort}`);if(w?.cleanUrls)console.log(` ${Ow.green("➜")} Clean URLs enabled`)}z0();P0.chdir(ZR(kR(PR(import.meta.url)),".."));var b0=new fJ("rpx");b0.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(w)=>{if(!w?.from||!w.to)return P6(mw);let $={from:w.from,to:w.to,https:{keyPath:w.keyPath,certPath:w.certPath,caCertPath:w.caCertPath},cleanup:{certs:w.certsCleanup||!1,hosts:w.hostsCleanup||!1},verbose:w.verbose||!1,changeOrigin:w.changeOrigin||!1,singlePortMode:w.singlePortMode||!1,httpPort:w.httpPort!==void 0?Number(w.httpPort):void 0,httpsPort:w.httpsPort!==void 0?Number(w.httpsPort):void 0,viaDaemon:w.viaDaemon||!1,id:w.id};if(w.startCommand){let Y={command:w.startCommand};if(w.startCwd)Y.cwd=w.startCwd;if(w.startEnv)try{Y.env=JSON.parse(w.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),P0.exit(1)}$.start=Y}return Z6($)});b0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{let Y=z8(mw)?mw.proxies.find((A)=>A.to===w||`${A.from}-${A.to}`===w):mw.to===w?mw:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${w}`),P0.exit(1);try{await d8.startProcess(w,Y.start,$.verbose),console.log(`Started dev server for ${w}`)}catch(A){console.error(`Failed to start dev server for ${w}:`,A),P0.exit(1)}});b0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{try{await d8.stopProcess(w,$.verbose),console.log(`Stopped dev server for ${w}`)}catch(Y){console.error(`Failed to stop dev server for ${w}:`,Y),P0.exit(1)}});b0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(w)=>{try{await d8.stopAll(w.verbose),console.log("Stopped all dev servers")}catch($){console.error("Failed to stop all dev servers:",$),P0.exit(1)}});async function i6(w){let Y={...(await Pf().catch(()=>null))?.onDemand??{},enabled:!0};if(w){let A=w.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}b0.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("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(w)=>{try{let $=w.onDemand?await i6(w.roots):void 0;await(await R6({rpxDir:w.rpxDir,registryDir:w.registryDir,httpsPort:typeof w.httpsPort==="string"?Number.parseInt(w.httpsPort,10):w.httpsPort,httpPort:typeof w.httpPort==="string"?Number.parseInt(w.httpPort,10):w.httpPort,hostname:w.hostname,productionCerts:w.certsDir?{certsDir:w.certsDir}:void 0,workers:w.workers===void 0?void 0:typeof w.workers==="string"?Number.parseInt(w.workers,10):w.workers,onDemandSites:$,verbose:w.verbose??!0})).done,P0.exit(0)}catch($){console.error(`Failed to start rpx daemon: ${$.message}`),P0.exit(1)}});b0.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(w)=>{let $=typeof w.timeout==="string"?Number.parseInt(w.timeout,10):w.timeout,Y=await M6({rpxDir:w.rpxDir,timeoutMs:$,forceAfterTimeout:w.force!==!1,verbose:w.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)":""}`)});b0.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(w)=>{let $=w.rpxDir??V0(),Y=await L$($),A=await c8($),X=w.registryDir,J=await Bw(X).catch(()=>[]);if(w.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:S$($),rpxDir:$,registryDir:X??$w(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${S$($)} → pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${S$($)}`);if(console.log(`registry: ${X??$w()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let j=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} → ${U.from} (id=${U.id}${j})`)}});b0.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(w)=>{if(!w.id||!w.from||!w.to)console.error("rpx register requires --id, --from, and --to"),P0.exit(1);if(!C$(w.id))console.error(`invalid id: ${JSON.stringify(w.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),P0.exit(1);try{await c1({id:w.id,from:w.from,to:w.to,cwd:w.cwd,createdAt:new Date().toISOString(),cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin},w.registryDir,w.verbose)}catch($){console.error(`failed to write registry entry: ${$.message}`),P0.exit(1)}if(w.skipSpawn){console.log(`registered ${w.to} → ${w.from} (daemon spawn skipped)`);return}try{let $=await v8({rpxDir:w.rpxDir,verbose:w.verbose}),Y=$.spawned?"spawned":"attached to";console.log(`registered https://${w.to} → ${w.from} (${Y} daemon pid=${$.pid})`)}catch($){console.error(`registered entry but daemon spawn failed: ${$.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),P0.exit(1)}});b0.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(!C$(w))console.error(`invalid id: ${JSON.stringify(w)}`),P0.exit(1);let Y=await yj(w,$.registryDir,$.verbose);if(!Y){console.log(`no registry entry for id=${w}`);return}await m$(w,$.registryDir,$.verbose),console.log(`unregistered ${Y.to} (id=${w})`)});b0.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(w)=>{let $=w.rpxDir??V0();if(await c8($)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await y6({rpxDir:$,verbose:w.verbose}),console.log("DNS reconcile complete")});b0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(w)=>{let $=await i6(w.roots),Y=gf($),A=await Bw(w.registryDir).catch(()=>[]),X=new Set(A.map((j)=>j.to)),J=Y.map((j)=>({host:j.host,dir:j.dir,command:j.command,source:j.source,live:X.has(j.host)}));if(w.json){console.log(JSON.stringify(J,null,2));return}let U=$.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) — scanned ${U.join(", ")}:`);for(let j of J)console.log(` ${j.live?"●":"○"} https://${j.host} ${j.live?"(live)":"(idle)"}`),console.log(` ${j.command} ${j.dir}`)});b0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(w,$)=>{let{readFile:Y}=await import("node:fs/promises"),{join:A}=await import("node:path"),X=$.rpxDir??V0(),J=A(X,"sites",`${iA(w.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${w} (it may not have been booted yet) — looked in ${J}`);return}let j=$.lines===void 0?void 0:typeof $.lines==="string"?Number.parseInt($.lines,10):$.lines,W=U.split(`
335
+ `)),this._prevFrame=w;return}this.output.write(UJ.down())}if(this.output.write(w),this.state==="initial")this.state="active";this._prevFrame=w}}function gG(w,$){if(w===void 0)return 0;if($.length===0)return 0;let A=$.findIndex((X)=>X.value===w);return A!==-1?A:0}function dG(w,$){return($.label??String($.value)).toLowerCase().includes(w.toLowerCase())}function nG(w,$){if(!$)return;if(w)return $;return $[0]}class lG extends BJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#w=0;#Y="";#A;#$;get cursor(){return this.#w}get userInputWithCursor(){if(!this.userInput)return sY.inverse(sY.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let w=this.userInput.slice(0,this._cursor),[$,...Y]=this.userInput.slice(this._cursor);return`${w}${sY.inverse($)}${Y.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(w){super(w);this.#$=w.options;let $=this.options;this.filteredOptions=[...$],this.multiple=w.multiple===!0,this.#A=w.filter??dG;let Y;if(w.initialValue&&Array.isArray(w.initialValue))if(this.multiple)Y=w.initialValue;else Y=w.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 X=$.findIndex((J)=>J.value===A);if(X!==-1)this.toggleSelected(A),this.#w=X}this.focusedValue=this.options[this.#w]?.value,this.on("key",(A,X)=>this.#X(A,X)),this.on("userInput",(A)=>this.#J(A))}_isActionKey(w,$){return w==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&w!==void 0&&w!==""}#X(w,$){let Y=$.name==="up",A=$.name==="down",X=$.name==="return";if(Y||A){if(this.#w=Math.max(0,Math.min(this.#w+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=nG(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.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(w){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(w))this.selectedValues=this.selectedValues.filter(($)=>$!==w);else this.selectedValues=[...this.selectedValues,w];else this.selectedValues=[w]}#J(w){if(w!==this.#Y){this.#Y=w;let $=this.options;if(w)this.filteredOptions=$.filter((Y)=>this.#A(w,Y));else this.filteredOptions=[...$];if(this.#w=gG(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class pG extends BJ{options;cursor=0;#w;getGroupItems(w){return this.options.filter(($)=>$.group===w)}isGroupSelected(w){let $=this.getGroupItems(w),Y=this.value;if(Y===void 0)return!1;return $.every((A)=>Y.includes(A.value))}toggleValue(){let w=this.options[this.cursor];if(this.value===void 0)this.value=[];if(w.group===!0){let $=String(w.value),Y=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((A)=>Y.findIndex((X)=>X.value===A)===-1);else this.value=[...this.value,...Y.map((A)=>A.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(w.value);this.value=$?this.value.filter((Y)=>Y!==w.value):[...this.value,w.value]}}constructor(w){super(w,!1);let{options:$}=w;this.#w=w.selectableGroups!==!1,this.options=Object.entries($).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((X)=>({...X,group:Y}))]),this.value=[...w.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===w.cursorAt),this.#w?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.#w&&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.#w&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var rG=YG();var $0=(w,$)=>rG?w:$,QM=$0("◆","*"),fM=$0("■","x"),zM=$0("▲","x"),BM=$0("◇","o"),GM=$0("┌","T"),tG=$0("│","|"),EM=$0("└","—"),KM=$0("●",">"),FM=$0("○"," "),TM=$0("◻","[•]"),NM=$0("◼","[+]"),qM=$0("◻","[ ]"),HM=$0("▪","•"),RM=$0("─","-"),MM=$0("╮","+"),yM=$0("├","+"),IM=$0("╯","+"),CM=$0("●","•"),VM=$0("◆","*"),LM=$0("▲","!"),SM=$0("■","x");var hM={light:$0("─","-"),heavy:$0("━","="),block:$0("█","#")};function aG(){return`${sY.gray(tG)} `}var OM=aG();iA();WU();i8();_$();z0();import{spawn as yR}from"node:child_process";import*as g8 from"node:process";class d8{processes=new Map;isShuttingDown=!1;async startProcess(w,$,Y){if(this.processes.has(w)){E("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||g8.cwd();E("start",`Starting process ${w}:`,Y),E("start",` Command: ${A} ${X.join(" ")}`,Y),E("start",` Working directory: ${J}`,Y),E("start",` Environment variables: ${$$($.env)}`,Y);let U=yR(A,X,{cwd:J,env:{...g8.env,...$.env},shell:!0,stdio:"inherit"});return this.processes.set(w,{command:$.command,cwd:J,process:U,env:$.env}),new Promise((j,W)=>{if(U.on("error",(Q)=>{if(!this.isShuttingDown)E("start",`Process ${w} failed to start: ${Q}`,Y),this.processes.delete(w),W(Q)}),U.on("exit",(Q)=>{if(!this.isShuttingDown&&Q!==null&&Q!==0)E("start",`Process ${w} exited with code ${Q}; leaving the proxy running`,Y),this.processes.delete(w),W(Error(`Process ${w} exited with code ${Q}`))}),Y)U.stdout?.on("data",(Q)=>{E("process",`[${w}] ${Q.toString().trim()}`,!0)}),U.stderr?.on("data",(Q)=>{E("process",`[${w}] ERR: ${Q.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete(w),W(Error(`Process ${w} was killed during startup`));else E("start",`Process ${w} started successfully`,Y),j()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);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(w),E("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){E("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){E("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){E("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,E("start","Stopping all processes",w);let $=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,w).catch((A)=>{H.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled($),this.processes.clear(),this.isShuttingDown=!1}isRunning(w){let $=this.processes.get(w);return!!$?.process&&!$.process.killed}}var n8=new d8;v$();_$();import{execSync as OR}from"node:child_process";import*as o8 from"node:http";import*as _6 from"node:net";import*as D6 from"node:os";import*as x6 from"node:path";import*as a from"node:process";var l8=(w,$)=>(Y)=>`\x1B[${w}m${Y}\x1B[${$}m`,_w={bold:l8(1,22),dim:l8(2,22),green:l8(32,39),cyan:l8(36,39)};iA();i8();_$();v$();z0();import*as V6 from"node:fs";import*as L6 from"node:path";import*as Dw from"node:process";function IR(w,$){let A=($&&$!=="/"?`${w}${$}`:w).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function gj(w){if(w.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let $=w.verbose??!1,Y=w.registryDir,A=new Set,X=w.proxies.map((B)=>{let G=B.id??IR(B.to,B.path);if(!I$(G))throw Error(`invalid registry id "${G}" derived from to="${B.to}"`);if(A.has(G))throw Error(`duplicate registry id "${G}" — set an explicit \`id\` on one of the proxies`);return A.add(G),{...B,id:G}}),J=new Date().toISOString();for(let B of X)await b1({id:B.id,from:B.from,to:B.to,path:B.path,pid:w.persistent?void 0:Dw.pid,cwd:Dw.cwd(),createdAt:J,cleanUrls:B.cleanUrls,changeOrigin:B.changeOrigin,pathRewrites:B.pathRewrites,static:B.static,loadBalancer:B.loadBalancer},Y,$);let U=await m8({rpxDir:w.rpxDir,verbose:$,spawnCommand:w.spawnCommand,startupTimeoutMs:w.startupTimeoutMs,spawnEnv:w.spawnEnv});for(let B of X){let G=B.static?`static ${typeof B.static==="string"?B.static:B.static.dir}`:B.from;H.success(`https://${B.to} → ${G}`)}if(H.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),w.detached)return;let j=!1,W=Y??Aw(),Q=X.map((B)=>B.id),f=async()=>{if(j)return;j=!0;for(let B of Q)await c$(B,Y,$).catch((G)=>{E("runner",`removeEntry(${B}) failed: ${G}`,$)})},z=(B)=>{E("runner",`received ${B}, unregistering ${Q.length} entries`,$),f().finally(()=>Dw.exit(0))};Dw.once("SIGINT",z),Dw.once("SIGTERM",z),Dw.once("exit",()=>{if(j)return;for(let B of Q)try{V6.unlinkSync(L6.join(W,`${B}.json`))}catch{}}),await new Promise(()=>{})}Oj();zj();Rj();import{timingSafeEqual as CR}from"node:crypto";function VR(w,$){if(w==null)return!1;let Y=Buffer.from(w),A=Buffer.from($);if(Y.length!==A.length)return!1;return CR(Y,A)}function p8(w){return w.toLowerCase().replace(/\.$/,"")}var LR=["/.well-known/acme-challenge/"];function SR(w){let $=w.headers.get("host");if($)return p8($.split(":")[0]);try{return p8(new URL(w.url).hostname)}catch{return""}}function S6(w){let $=w.header.toLowerCase(),Y=new Set,A=[];for(let W of w.hosts){let Q=p8(W);if(Q.startsWith("*."))A.push(Q);else Y.add(Q)}let X=w.exemptPaths??LR,J=w.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
336
+ `,U=(W)=>{let Q=p8(W);return Y.has(Q)||A.some((f)=>wY(Q,f))},j=(W)=>{let Q=SR(W);if(!U(Q))return;let f="/";try{f=new URL(W.url).pathname}catch{}if(X.some((z)=>f.startsWith(z)))return;if(VR(W.headers.get($),w.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return j.protects=U,j}Ej();Kj();T8();y8();Nj();qj();R8();z0();var h6={name:"@stacksjs/rpx",type:"module",version:"0.11.40",description:"A modern and smart reverse proxy.",author:"Chris Breuer <chris@stacksjs.org>",license:"MIT",homepage:"https://github.com/stacksjs/rpx",repository:{type:"git",url:"git+https://github.com/stacksjs/rpx.git"},bugs:{url:"https://github.com/stacksjs/rpx/issues"},keywords:["reverse proxy","ssl","development","environment","proxy","bun","stacks","typescript","javascript"],exports:{".":{types:"./dist/index.d.ts",bun:"./dist/index.js",import:"./dist/index.js"}},module:"./dist/index.js",types:"./dist/index.d.ts",bin:{rpx:"./dist/bin/cli.js","reverse-proxy":"./dist/bin/cli.js"},files:["README.md","dist"],scripts:{build:"bun build.ts && bun build ./bin/cli.ts --compile --minify --outfile bin/rpx",compile:"bun build ./bin/cli.ts --compile --minify --outfile bin/rpx","compile:all":"bun run compile:linux-x64 && bun run compile:linux-arm64 && bun run compile:windows-x64 && bun run compile:darwin-x64 && bun run compile:darwin-arm64","compile:linux-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-x64 --outfile bin/rpx-linux-x64","compile:linux-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-linux-arm64 --outfile bin/rpx-linux-arm64","compile:windows-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-windows-x64 --outfile bin/rpx-windows-x64.exe","compile:darwin-x64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-x64 --outfile bin/rpx-darwin-x64","compile:darwin-arm64":"bun build ./bin/cli.ts --compile --minify --target=bun-darwin-arm64 --outfile bin/rpx-darwin-arm64",bench:"bun run bench/run.ts","bench:html":"bun run bench/run.ts --html","bench:latency":"bun run bench/run.ts --latency","bench:throughput":"bun run bench/run.ts --throughput",lint:"bunx --bun pickier .","lint:fix":"bunx --bun pickier . --fix",fresh:"bunx rimraf node_modules/ bun.lock && bun i",changelog:"changelogen --output CHANGELOG.md",prepublishOnly:"bun build.ts","release:binaries":"bun run compile:all && bun run zip",test:"bun test",typecheck:"bunx tsc --noEmit",zip:"bun run zip:all","zip:all":"bun run zip:linux-x64 && bun run zip:linux-arm64 && bun run zip:windows-x64 && bun run zip:darwin-x64 && bun run zip:darwin-arm64","zip:linux-x64":"zip -j bin/rpx-linux-x64.zip bin/rpx-linux-x64","zip:linux-arm64":"zip -j bin/rpx-linux-arm64.zip bin/rpx-linux-arm64","zip:windows-x64":"zip -j bin/rpx-windows-x64.zip bin/rpx-windows-x64.exe","zip:darwin-x64":"zip -j bin/rpx-darwin-x64.zip bin/rpx-darwin-x64","zip:darwin-arm64":"zip -j bin/rpx-darwin-arm64.zip bin/rpx-darwin-arm64"},dependencies:{"@stacksjs/clapp":"^0.2.10","@stacksjs/tlsx":"^0.13.13"},devDependencies:{bunfig:"^0.15.6",mitata:"^1.0.34",typescript:"^7.0.2"},"simple-git-hooks":{"pre-commit":"bunx lint-staged"},"lint-staged":{"*.{js,ts}":"bunx --bun pickier . --fix"}};var gY=h6.version;var t8=new d8,_R=new V8("0.0.0.0"),dY=new Set,s8=new Set,dj=!1,r8=null,nj=null;async function e8(w){if(dj)return E("cleanup","Cleanup already in progress, skipping",w?.verbose),nj||Promise.resolve();dj=!0,E("cleanup","Starting cleanup process",w?.verbose),nj=new Promise(($)=>{r8=$});try{await t8.stopAll(w?.verbose),H.info("Shutting down proxy servers...");let $=[],Y=Array.from(dY).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),E("cleanup","Bun server stopped",w?.verbose),X();else if(typeof J.close==="function")J.close(()=>{E("cleanup","Server closed successfully",w?.verbose),X()});else X()}catch(U){E("cleanup",`Error stopping server: ${U}`,w?.verbose),X()}}));$.push(...Y),dY.clear();for(let A of s8)P1(A);if(s8.clear(),w?.hosts&&w.domains?.length){E("cleanup","Cleaning up hosts file entries",w?.verbose),E("cleanup",`Original domains for cleanup: ${JSON.stringify(w.domains)}`,w?.verbose);let A=w.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(E("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,w?.verbose),A.length>0)H.info("Cleaning up hosts file entries..."),$.push(o2(A,w?.verbose).then(()=>{E("cleanup",`Removed hosts entries for ${A.join(", ")}`,w?.verbose)}).catch((X)=>{E("cleanup",`Failed to remove hosts entries: ${X}`,w?.verbose),H.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if(w?.certs&&w.domains?.length){E("cleanup","Cleaning up SSL certificates",w?.verbose),H.info("Cleaning up SSL certificates...");let A=w.domains.map(async(X)=>{try{await B2(X,w?.verbose),E("cleanup",`Removed certificates for ${X}`,w?.verbose)}catch(J){E("cleanup",`Failed to remove certificates for ${X}: ${J}`,w?.verbose),H.warn(`Failed to clean up certificates for ${X}:`,J)}});$.push(...A)}await Promise.allSettled($),E("cleanup","All cleanup tasks completed successfully",w?.verbose),H.success("All cleanup tasks completed successfully")}catch($){E("cleanup",`Error during cleanup: ${$}`,w?.verbose),H.error("Error during cleanup:",$)}finally{if(r8)r8();r8=null,dj=!1;let $=w&&"vitePluginUsage"in w&&w.vitePluginUsage===!0;if(a.env.NODE_ENV!=="test"&&a.env.BUN_ENV!=="test"&&!$)a.exit(0)}return nj}var lj=!1;function k6(w){if(lj){E("signal",`Received second ${w} signal, forcing exit`,!0),a.exit(1);return}lj=!0,E("signal",`Received ${w} signal, initiating cleanup`,!0),e8().catch(($)=>{E("signal",`Cleanup failed after ${w}: ${$}`,!0),a.exit(1)}).finally(()=>{lj=!1})}a.once("SIGINT",()=>k6("SIGINT"));a.once("SIGTERM",()=>k6("SIGTERM"));a.on("uncaughtException",(w)=>{H.error("Uncaught exception (continuing):",w)});a.on("unhandledRejection",(w)=>{H.error("Unhandled rejection (continuing):",w)});async function nY(w,$,Y,A=5){E("connection",`Testing connection to ${w}:${$} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(a.env.RPX_BYPASS_CONNECTION_TEST==="true"){E("connection",`Bypassing connection test for ${w}:${$} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((j,W)=>{let Q=_6.connect({host:w,port:$,timeout:3000});Q.once("connect",()=>{E("connection",`Successfully connected to ${w}:${$}`,Y),Q.end(),j()}),Q.once("timeout",()=>{E("connection",`Connection to ${w}:${$} timed out`,Y),Q.destroy(),W(Error("Connection timed out"))}),Q.once("error",(f)=>{E("connection",`Failed to connect to ${w}:${$}: ${f}`,Y),Q.destroy(),W(f)})});try{await U()}catch(j){let W=j;if(Date.now()-J>X){E("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),H.warn(`Connection test to ${w}:${$} timed out, but RPX will try to proceed anyway.`);return}if(W.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((f)=>setTimeout(f,2000)),nY(w,$,Y,A-1);if(A>0)try{E("connection",`Trying HTTP request to ${w}:${$}`,Y),await new Promise((f,z)=>{let B=o8.request({hostname:w,port:$,path:"/",method:"HEAD",timeout:5000},(G)=>{E("connection",`Received HTTP response with status: ${G.statusCode}`,Y),f()});B.on("error",(G)=>z(G)),B.on("timeout",()=>{B.destroy(),z(Error("HTTP request timed out"))}),B.end()}),E("connection",`HTTP request to ${w}:${$} succeeded`,Y);return}catch(f){return E("connection",`HTTP request to ${w}:${$} failed: ${f}`,Y),E("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),nY(w,$,Y,A-1)}let Q=`Failed to connect to ${w}:${$} after ${5-A} attempts: ${W.message}`;E("connection",`${Q}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),H.warn(Q),H.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 Z6(w){E("server",`Starting server with options: ${$$(w)}`,w.verbose);let $=i$(w.from),Y=new URL($.startsWith("http")?$:`http://${$}`),A=new URL((w.to?.startsWith("http")?w.to:`http://${w.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(pj(w)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){E("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,w?.verbose);try{if(!(await bY(J,w.verbose))[0]){H.info(`Adding ${A.hostname} to hosts file...`),H.info("This may require sudo/administrator privileges");try{await iY(J,w.verbose)}catch(W){if(H.error("Failed to add hosts entry:",W.message),H.warn("You can manually add this entry to your hosts file:"),H.warn(`127.0.0.1 ${A.hostname}`),H.warn(`::1 ${A.hostname}`),a.platform==="win32")H.warn("On Windows:"),H.warn("1. Run notepad as administrator"),H.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else H.warn("On Unix systems:"),H.warn("sudo nano /etc/hosts")}}else E("hosts",`Host entry already exists for ${A.hostname}`,w.verbose)}catch(j){H.error("Failed to check hosts file:",j.message)}}try{await nY(Y.hostname,X,w.verbose)}catch(j){E("server",`Connection test failed: ${j}`,w.verbose),H.error(j.message),H.warn("Continuing with proxy setup despite connection test failure..."),H.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=w._cachedSSLConfig||null;if(w.https)try{if(w.https===!0)w.https=HY({...w,to:A.hostname});if(U=await M$({...w,to:A.hostname,https:w.https}),!U){if(E("ssl",`Generating new certificates for ${A.hostname}`,w.verbose),await qY({...w,from:Y.toString(),to:A.hostname,https:w.https}),U=await M$({...w,to:A.hostname,https:w.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(j){throw E("server",`SSL setup failed: ${j}`,w.verbose),j}E("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,w.verbose),await xR({...w,from:$,originalFrom:w.from||$,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function DR(w,$,Y,A,X,J,U,j,W,Q,f,z){E("proxy",`Creating proxy server ${w} -> ${$} with cleanUrls: ${j}`,U);let B=RY(f??A.host,z);yY(B);let G=[{host:$,route:{sourceHost:A.host,upstreamPool:B,cleanUrls:j||!1,changeOrigin:W||!1,basePath:"/",auth:Q}}];if(!a8({routeEntries:G,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw P1(B),Error(`Failed to start proxy server for ${$} on port ${Y}`);s8.add(B),ZR({from:w,to:$,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:j,verbose:U})}async function xR(w){E("setup",`Setting up reverse proxy: ${$$(w)}`,w.verbose);let{from:$,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:j,vitePluginUsage:W,changeOrigin:Q,cleanUrls:f}=w,z=80,B=443,G="0.0.0.0",T=w.portManager||_R,K=pj(w);try{if(K&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await bY([A],U))[0]){H.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await iY([A],U),H.success(`Added ${A} to your hosts file.`)}catch(L){H.error(`Failed to add ${A} to your hosts file: ${L}`),H.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(K&&a.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await bY([A],U))[0]){E("hosts",`${A} not found in hosts file, adding...`,U);try{await iY([A],U)}catch(L){E("hosts",`Failed to add ${A} to hosts file: ${L}`,U)}}}if(J&&!T.usedPorts.has(z)){if(!await y$(z,G,U))E("setup","Starting HTTP redirect server",U),P6(U),T.usedPorts.add(z);else if(E("setup","Port 80 is in use, skipping HTTP redirect",U),U)H.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let F=J?B:z,N=await y$(F,G,U),R;if(N){if(E("setup",`Port ${F} is already in use`,U),U)H.warn(`Port ${F} is already in use. This may be another instance of rpx or another service.`);if(F===443){if(R=await T.getNextAvailablePort(3443,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await T.getNextAvailablePort(F+1000,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=F,T.usedPorts.add(R),E("setup",`Using standard ${F===443?"HTTPS":"HTTP"} port ${F} for ${A}`,U);await DR($,A,R,X,J,W,U,f,Q,CY(w.auth),Y,w.loadBalancer)}catch(F){E("setup",`Setup failed: ${F}`,U),H.error(`Failed to setup reverse proxy: ${F.message}`),e8({domains:[A],hosts:typeof j==="boolean"?j:j?.hosts,certs:typeof j==="boolean"?j:j?.certs,verbose:U,vitePluginUsage:W})}}function P6(w,$=80,Y=443,A,X){E("redirect",`Starting HTTP redirect server on port ${$}`,w);let J=o8.createServer((U,j)=>{let W=U.url?U.url.split("?",1)[0]:"";if(W.startsWith("/.well-known/acme-challenge/")){if(X){let B=X.challengeStore.handlePath(W);if(B!==void 0){E("redirect",`Serving on-demand ACME challenge ${W}`,w),j.writeHead(200,{"content-type":"text/plain"}),j.end(B);return}}if(A){let B=M8(A,W);if(B!=null){E("redirect",`Serving ACME challenge ${W}`,w),j.writeHead(200,{"content-type":"text/plain"}),j.end(B);return}}if(X){j.writeHead(404,{"content-type":"text/plain"}),j.end("challenge not found");return}}let Q=U.headers.host||"",f=Q.includes(":")?Q.slice(0,Q.indexOf(":")):Q;if(X&&f&&!X.hasCert(f))X.ensureCert(f).catch(()=>{});let z=Y===443?f:`${f}:${Y}`;E("redirect",`Redirecting request from ${Q}${U.url} to https://${z}`,w),j.writeHead(301,{Location:`https://${z}${U.url}`}),j.end()}).listen($);dY.add(J),E("redirect","HTTP redirect server started",w)}function i6(w){let $={...cw,...w};if(E("proxy",`Starting proxy with options: ${$$($)}`,$?.verbose),$.viaDaemon){if(!$.from||!$.to){H.error("viaDaemon mode requires both `from` and `to`");return}gj({proxies:[{id:$.id,from:$.from,to:$.to,path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}],verbose:$.verbose}).catch((W)=>{H.error(`Failed to register with rpx daemon: ${W.message}`),a.exit(1)});return}let Y=$.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=a.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&$?.verbose)H.warn(`The .${A} TLD may not work reliably for local development`),H.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),H.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (mY(),P8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:$.verbose}).then((Q)=>{if(Q)Promise.resolve().then(()=>{if($.verbose)if(U.includes(A))H.success(`DNS server started for .${A} domains`);else H.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`,$.verbose)})}).catch((W)=>{E("dns",`Failed to start DNS server: ${W}`,$.verbose)});let j={from:$.from,to:$.to,cleanUrls:$.cleanUrls,https:HY($),cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,changeOrigin:$.changeOrigin,verbose:$.verbose,regenerateUntrustedCerts:$.regenerateUntrustedCerts};E("proxy",`Server options: ${$$(j)}`,$.verbose),Z6(j).catch((W)=>{E("proxy",`Failed to start proxy: ${W}`,$.verbose),H.error(`Failed to start proxy: ${W.message}`),e8({domains:[$.to],hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose})})}function kR(w){return w?.verbose||!1}function pj(w){if(w?.hostsManagement===!1)return!1;let $=w?.cleanup;if($===!1)return!1;if($&&typeof $==="object"&&$.hosts===!1)return!1;return!0}async function b6(w){let $={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=kR($),A=pj($);if(E("config",`Starting with config: ${$$($,2)}`,Y),E("config",`Is multi-proxy? ${"proxies"in $}`,Y),E("config",`Hosts management enabled? ${A}`,Y),$.viaDaemon){let C="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((M)=>({id:M.id,from:M.from,to:M.to,path:M.path,cleanUrls:M.cleanUrls??$.cleanUrls,changeOrigin:M.changeOrigin??$.changeOrigin,pathRewrites:M.pathRewrites})):[{id:$.id,from:$.from,to:$.to??"rpx.localhost",path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}];await gj({proxies:C,verbose:Y});return}if("proxies"in $&&Array.isArray($.proxies)){E("servers",`Found ${$.proxies.length} proxies in config`,Y);for(let q of $.proxies)if(q.start){let C=`${q.from}-${q.to}`;try{E("watch",`Starting command for ${C} with command: ${q.start.command}`,Y),H.info(`Starting command for ${C}...`),await t8.startProcess(C,q.start,Y);let M=i$(q.from),D=new URL(M.startsWith("http")?M:`http://${M}`),d=D.hostname||"localhost",r0=Number(D.port)||80;try{await nY(d,r0,Y),E("watch",`Dev server is ready at ${d}:${r0}`,Y)}catch(Jw){E("watch",`Connection check failed, but continuing with proxy setup: ${Jw}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw E("watch",`Failed to start command for ${C}: ${M}`,Y),Error(`Failed to start command for ${C}: ${M}`)}}else E("watch",`No start command for proxy ${q.from} -> ${q.to}`,Y)}else if("start"in $&&$.start){E("watch","Found start command in single proxy config",Y);let q=`${$.from}-${$.to}`;try{if($.start)E("watch",`Starting command: ${$.start.command}`,Y),await t8.startProcess(q,$.start,Y);let C=i$($.from),M=new URL(C.startsWith("http")?C:`http://${C}`),D=M.hostname||"localhost",d=Number(M.port)||80;try{await nY(D,d,Y),E("watch",`Dev server is ready at ${D}:${d}`,Y)}catch(r0){E("watch",`Connection check failed, but continuing with proxy setup: ${r0}`,Y),H.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 X="proxies"in $&&Array.isArray($.proxies)?$.proxies[0]?.to:("to"in $)?$.to:"rpx.localhost";if(a.platform!=="win32"&&($.https||A)){if(!F$())try{E("sudo","Pre-acquiring sudo credentials for privileged operations",Y),OR("sudo -v",{stdio:"inherit"})}catch{E("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if($.productionCerts){if(J=await DY($.productionCerts,Y),J.length>0)E("ssl",`Using ${J.length} production SNI cert(s): ${J.map((q)=>q.serverName).join(", ")}`,Y)}if($.https){let q=J.length>0?null:await M$($);if(!q&&J.length===0){if(E("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,$.verbose),await qY($),q=await M$($),!q)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else E("ssl",`Using existing and trusted certificates for ${X}`,$.verbose);$._cachedSSLConfig=q}let U="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((q)=>({...q,https:$.https,cleanup:$.cleanup,cleanUrls:q.cleanUrls??("cleanUrls"in $?$.cleanUrls:!1),vitePluginUsage:$.vitePluginUsage,changeOrigin:q.changeOrigin??$.changeOrigin,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig})):[{from:"from"in $?$.from:"localhost:5173",to:"to"in $?$.to:"rpx.localhost",cleanUrls:"cleanUrls"in $?$.cleanUrls:!1,https:$.https,cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,start:"start"in $?$.start:void 0,changeOrigin:$.changeOrigin,auth:"auth"in $?$.auth:void 0,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig}],j=U.map((q)=>q.to||"rpx.localhost"),W=J.length>0?J:$._cachedSSLConfig??null,Q=j.filter((q)=>q&&!q.includes("localhost")&&!q.includes("127.0.0.1")),f=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"],B=[...new Set(Q.map((q)=>q.split(".").pop()?.toLowerCase()))],G=B.filter((q)=>!!q&&f.includes(q));if(G.length>0&&Y)H.warn(`The following TLDs may not work reliably for local development: ${G.map((q)=>`.${q}`).join(", ")}`),H.info(" These TLDs have HSTS preloading which can bypass local DNS"),H.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&a.platform==="darwin"&&Q.length>0){let{setupDevelopmentDns:q}=await Promise.resolve().then(() => (mY(),P8));if(await q({domains:Q,verbose:Y})){if(Y)if(B.every((D)=>!!D&&z.includes(D)))H.success(`DNS server started for ${B.map((D)=>`.${D}`).join(", ")} domains`);else H.success(`DNS server started for ${B.map((D)=>`.${D}`).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",$.verbose);try{let{tearDownDevelopmentDns:q}=await Promise.resolve().then(() => (mY(),P8));await q({verbose:$.verbose})}catch(q){E("cleanup",`Error stopping DNS server: ${q}`,$.verbose)}try{await t8.stopAll($.verbose)}catch(q){E("cleanup",`Error stopping processes: ${q}`,$.verbose)}await e8({domains:j,hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose||!1})};a.on("SIGINT",T),a.on("SIGTERM",T);let K=$.singlePortMode===!0,F=$.httpsPort??443,N=$.httpPort??80,R=$.originGuard?S6($.originGuard):null,V=!!W&&(U.length>1||K||J.length>0),L=!W&&K&&U.length>0;if(V&&W){E("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${F}`,Y);let q=await O6(U,A,Y),C=null,M=$.onDemandTls,D=M?.enabled?new i1({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??x6.join(D6.homedir(),".stacks","rpx","on-demand-certs"),initial:J,verbose:Y,onCertAdded:(a0)=>{if(xY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",Y),setTimeout(()=>a.kill(a.pid,"SIGTERM"),10).unref();else Jw(a0)}}):null,d=null,r0=!1;async function Jw(a0){if(d=a0,r0)return;r0=!0;try{while(d){let Vw=d;if(d=null,E("proxies",`rebuilding :${F} with ${Vw.length} SNI cert(s)`,Y),C)dY.delete(C),C.stop(!1);let Lw=!1;for(let _=0;!Lw&&_<60;_++){let u0=a8({routeEntries:q,listenPort:F,sslConfig:Vw,originGuard:R,verbose:Y});if(u0){C=u0,Lw=!0;break}await new Promise((d1)=>setTimeout(d1,Math.min(25*2**Math.min(_,4),500)))}if(!Lw)H.error(`rpx: CRITICAL — could not rebind :${F} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{r0=!1}}if(!await y$(N,"0.0.0.0",Y))P6(Y,N,F,$.acmeChallengeWebroot,D);if(await y$(F,"0.0.0.0",Y)){if(E("proxies",`Port ${F} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${F} is in use. Shared HTTPS proxy cannot start.`);return}let J$=D&&D.sniEntries().length>0?D.sniEntries():W;if(C=a8({routeEntries:q,listenPort:F,sslConfig:J$,originGuard:R,verbose:Y}),!C){H.error(`Shared HTTPS proxy failed to bind :${F}; not exiting`);return}}else if(L){E("proxies",`Creating shared HTTP server for ${U.length} domains on port ${N}`,Y);let q=await O6(U,A,Y);if(await y$(N,"0.0.0.0",Y)){if(E("proxies",`Port ${N} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${N} is in use. Shared HTTP proxy cannot start.`);return}if(!a8({routeEntries:q,listenPort:N,sslConfig:null,originGuard:R,verbose:Y})){H.error(`Shared HTTP proxy failed to bind :${N}; not exiting`);return}}else for(let q of U)try{let C=q.to||"rpx.localhost";E("proxy",`Starting proxy for ${C} with SSL config: ${!!W}`,q.verbose),await Z6({from:q.from||"localhost:5173",to:C,cleanUrls:q.cleanUrls||!1,https:q.https||!1,cleanup:q.cleanup||!1,vitePluginUsage:q.vitePluginUsage||!1,verbose:q.verbose||!1,_cachedSSLConfig:$._cachedSSLConfig,changeOrigin:q.changeOrigin||!1,loadBalancer:q.loadBalancer,auth:q.auth,path:q.path,pathRewrites:q.pathRewrites})}catch(C){E("proxies",`Failed to start proxy for ${q.to}: ${C}`,q.verbose),H.error(`Failed to start proxy for ${q.to}:`,C)}}async function O6(w,$,Y){let A=[],X=new Set;for(let J of w){let U=J.to||"rpx.localhost",j=J.cleanUrls||!1,W=J.path,Q=Y$(W),f=CY(J.auth);if(J.redirect){let z=S2(J.redirect);A.push({host:U,path:W,route:{redirect:z,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → redirect ${z.status} ${z.to}${f?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:H8(J.static,j),cleanUrls:j,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${f?" (auth)":""}`,Y);else{let z=i$(J.from),B=new URL(z.startsWith("http")?z:`http://${z}`),G=RY(J.from??B.host,J.loadBalancer);yY(G),s8.add(G),A.push({host:U,path:W,route:{sourceHost:B.host,upstreamPool:G,cleanUrls:j,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:Q,auth:f}}),E("proxies",`Route: ${U}${W??""} → ${B.host}${f?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),$&&!U1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await bY([U],Y))[0])await iY([U],Y)}catch{E("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function a8(w){let{routeEntries:$,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=w,U=hY($),j=LY((f,z)=>OY(U,f,z),J),W=X?(f,z)=>X(f)??j(f,z):j,Q=SY(J);try{let f=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:TY(),...A?{tls:u$(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,B){return W(z,B)},websocket:Q,error(z){return E("server",`Shared proxy server error: ${z}`,J),new Response(`Server Error: ${z.message}`,{status:500})}});return dY.add(f),E("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),f}catch(f){return E("proxies",`Failed to start shared proxy: ${f}`,J),console.error("Failed to start shared proxy:",f),null}}function ZR(w){if(w?.vitePluginUsage||!w?.verbose)return;if(console.log(""),console.log(` ${_w.green(_w.bold("rpx"))} ${_w.green(`v${gY}`)}`),console.log(` ${_w.green("➜")} ${_w.dim(w?.from??"")} ${_w.dim("➜")} ${_w.cyan(w?.ssl?`https://${w?.to}`:`http://${w?.to}`)}`),w?.listenPort!==(w?.ssl?443:80))console.log(` ${_w.green("➜")} Listening on port ${w?.listenPort}`);if(w?.cleanUrls)console.log(` ${_w.green("➜")} Clean URLs enabled`)}z0();P0.chdir(iR(PR(bR(import.meta.url)),".."));var b0=new zJ("rpx");b0.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(w)=>{if(!w?.from||!w.to)return b6(cw);let $={from:w.from,to:w.to,https:{keyPath:w.keyPath,certPath:w.certPath,caCertPath:w.caCertPath},cleanup:{certs:w.certsCleanup||!1,hosts:w.hostsCleanup||!1},verbose:w.verbose||!1,changeOrigin:w.changeOrigin||!1,singlePortMode:w.singlePortMode||!1,httpPort:w.httpPort!==void 0?Number(w.httpPort):void 0,httpsPort:w.httpsPort!==void 0?Number(w.httpsPort):void 0,viaDaemon:w.viaDaemon||!1,id:w.id};if(w.startCommand){let Y={command:w.startCommand};if(w.startCwd)Y.cwd=w.startCwd;if(w.startEnv)try{Y.env=JSON.parse(w.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),P0.exit(1)}$.start=Y}return i6($)});b0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{let Y=B8(cw)?cw.proxies.find((A)=>A.to===w||`${A.from}-${A.to}`===w):cw.to===w?cw:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${w}`),P0.exit(1);try{await n8.startProcess(w,Y.start,$.verbose),console.log(`Started dev server for ${w}`)}catch(A){console.error(`Failed to start dev server for ${w}:`,A),P0.exit(1)}});b0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{try{await n8.stopProcess(w,$.verbose),console.log(`Stopped dev server for ${w}`)}catch(Y){console.error(`Failed to stop dev server for ${w}:`,Y),P0.exit(1)}});b0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(w)=>{try{await n8.stopAll(w.verbose),console.log("Stopped all dev servers")}catch($){console.error("Failed to stop all dev servers:",$),P0.exit(1)}});async function u6(w){let Y={...(await uf().catch(()=>null))?.onDemand??{},enabled:!0};if(w){let A=w.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}b0.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("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(w)=>{try{let $=w.onDemand?await u6(w.roots):void 0;await(await y6({rpxDir:w.rpxDir,registryDir:w.registryDir,httpsPort:typeof w.httpsPort==="string"?Number.parseInt(w.httpsPort,10):w.httpsPort,httpPort:typeof w.httpPort==="string"?Number.parseInt(w.httpPort,10):w.httpPort,hostname:w.hostname,productionCerts:w.certsDir?{certsDir:w.certsDir}:void 0,workers:w.workers===void 0?void 0:typeof w.workers==="string"?Number.parseInt(w.workers,10):w.workers,onDemandSites:$,verbose:w.verbose??!0})).done,P0.exit(0)}catch($){console.error(`Failed to start rpx daemon: ${$.message}`),P0.exit(1)}});b0.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(w)=>{let $=typeof w.timeout==="string"?Number.parseInt(w.timeout,10):w.timeout,Y=await I6({rpxDir:w.rpxDir,timeoutMs:$,forceAfterTimeout:w.force!==!1,verbose:w.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)":""}`)});b0.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(w)=>{let $=w.rpxDir??V0(),Y=await V$($),A=await v8($),X=w.registryDir,J=await Kw(X).catch(()=>[]);if(w.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:L$($),rpxDir:$,registryDir:X??Aw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${L$($)} → pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${L$($)}`);if(console.log(`registry: ${X??Aw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let j=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} → ${U.from} (id=${U.id}${j})`)}});b0.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(w)=>{if(!w.id||!w.from||!w.to)console.error("rpx register requires --id, --from, and --to"),P0.exit(1);if(!I$(w.id))console.error(`invalid id: ${JSON.stringify(w.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),P0.exit(1);try{await b1({id:w.id,from:w.from,to:w.to,cwd:w.cwd,createdAt:new Date().toISOString(),cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin},w.registryDir,w.verbose)}catch($){console.error(`failed to write registry entry: ${$.message}`),P0.exit(1)}if(w.skipSpawn){console.log(`registered ${w.to} → ${w.from} (daemon spawn skipped)`);return}try{let $=await m8({rpxDir:w.rpxDir,verbose:w.verbose}),Y=$.spawned?"spawned":"attached to";console.log(`registered https://${w.to} → ${w.from} (${Y} daemon pid=${$.pid})`)}catch($){console.error(`registered entry but daemon spawn failed: ${$.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),P0.exit(1)}});b0.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(!I$(w))console.error(`invalid id: ${JSON.stringify(w)}`),P0.exit(1);let Y=await Ij(w,$.registryDir,$.verbose);if(!Y){console.log(`no registry entry for id=${w}`);return}await c$(w,$.registryDir,$.verbose),console.log(`unregistered ${Y.to} (id=${w})`)});b0.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(w)=>{let $=w.rpxDir??V0();if(await v8($)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await C6({rpxDir:$,verbose:w.verbose}),console.log("DNS reconcile complete")});b0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(w)=>{let $=await u6(w.roots),Y=nf($),A=await Kw(w.registryDir).catch(()=>[]),X=new Set(A.map((j)=>j.to)),J=Y.map((j)=>({host:j.host,dir:j.dir,command:j.command,source:j.source,live:X.has(j.host)}));if(w.json){console.log(JSON.stringify(J,null,2));return}let U=$.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) — scanned ${U.join(", ")}:`);for(let j of J)console.log(` ${j.live?"●":"○"} https://${j.host} ${j.live?"(live)":"(idle)"}`),console.log(` ${j.command} ${j.dir}`)});b0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(w,$)=>{let{readFile:Y}=await import("node:fs/promises"),{join:A}=await import("node:path"),X=$.rpxDir??V0(),J=A(X,"sites",`${bA(w.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${w} (it may not have been booted yet) — looked in ${J}`);return}let j=$.lines===void 0?void 0:typeof $.lines==="string"?Number.parseInt($.lines,10):$.lines,W=U.split(`
337
337
  `);P0.stdout.write((j&&j>0?W.slice(-j):W).join(`
338
- `))});b0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(dY)});b0.version(dY);b0.help();b0.run();
338
+ `))});b0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(gY)});b0.version(gY);b0.help();b0.run();