@stacksjs/rpx 0.11.27 → 0.11.28

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,24 +1,24 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
3
  #!/usr/bin/env bun
4
- import{createRequire as YK}from"node:module";var e6=Object.defineProperty;var $K=($)=>$;function wK($,w){this[$]=$K.bind(null,w)}var Gj=($,w)=>{for(var Y in w)e6($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:wK.bind(w,Y)})};var t=($,w)=>()=>($&&(w=$($=0)),w);var b=YK(import.meta.url);import{existsSync as Lj,statSync as Oj}from"fs";import{existsSync as W7,mkdirSync as BI,readdirSync as jI,readFileSync as B7,writeFileSync as zI}from"fs";import{homedir as rw}from"os";import{dirname as FI,resolve as Y$}from"path";import vA from"process";import{existsSync as _j,statSync as Sj}from"fs";import{existsSync as uJ,mkdirSync as j7,readdirSync as z7,writeFileSync as G7}from"fs";import{homedir as tw}from"os";import{dirname as Zj,resolve as c0}from"path";import Zw from"process";import{join as K7,relative as F7,resolve as hj}from"path";import yA from"process";import{existsSync as q9,mkdirSync as VI,readdirSync as CI,writeFileSync as QI}from"fs";import{homedir as HJ}from"os";import{dirname as OI,resolve as v0}from"path";import zY from"process";import{join as N7,relative as q7,resolve as kj}from"path";import LA from"process";import{existsSync as E9,mkdirSync as kI,readdirSync as DI,writeFileSync as xI}from"fs";import{dirname as bI,resolve as OA}from"path";import vJ from"process";import{Buffer as zw}from"buffer";import{createCipheriv as E7,createDecipheriv as T7,randomBytes as fJ}from"crypto";import{closeSync as RJ,createReadStream as Dj,createWriteStream as H7,existsSync as MJ,fsyncSync as xj,openSync as Pj,writeFileSync as f7}from"fs";import{access as R7,constants as bj,mkdir as M7,readdir as UA,rename as uj,stat as aw,unlink as WA,writeFile as IJ}from"fs/promises";import{join as sw}from"path";import y0 from"process";import{pipeline as I7}from"stream/promises";import{createGzip as vj}from"zlib";import ow from"process";import b$ from"process";import{Buffer as x$}from"buffer";import{createCipheriv as V7,createDecipheriv as C7,randomBytes as VJ}from"crypto";import{closeSync as CJ,createReadStream as cj,createWriteStream as Q7,existsSync as BA,fsyncSync as ij,openSync as mj,writeFileSync as y7}from"fs";import{access as L7,constants as gj,mkdir as O7,readdir as jA,rename as dj,stat as ew,unlink as zA,writeFile as QJ}from"fs/promises";import{isAbsolute as _7,join as $1,resolve as S7}from"path";import k from"process";import{pipeline as Z7}from"stream/promises";import{createGzip as lj}from"zlib";import w1 from"process";import u$ from"process";import GA from"process";import{existsSync as KA}from"fs";import{resolve as yJ}from"path";import{existsSync as h7}from"fs";import{existsSync as k7,readdirSync as D7}from"fs";import{extname as LJ,resolve as nj}from"path";import x7 from"process";import{join as P7,relative as b7,resolve as pj}from"path";import _A from"process";import{Buffer as P$}from"buffer";import{createCipheriv as u7,createDecipheriv as v7,randomBytes as OJ}from"crypto";import{closeSync as _J,createReadStream as rj,createWriteStream as c7,existsSync as FA,fsyncSync as tj,openSync as aj,writeFileSync as i7}from"fs";import{access as m7,constants as sj,mkdir as g7,readdir as NA,rename as oj,stat as Y1,unlink as qA,writeFile as SJ}from"fs/promises";import{isAbsolute as d7,join as A1,resolve as l7}from"path";import D from"process";import{pipeline as n7}from"stream/promises";import{createGzip as ej}from"zlib";import X1 from"process";import v$ from"process";import TA from"process";import{existsSync as HA}from"fs";import{resolve as PJ}from"path";import{existsSync as KN}from"fs";class F9{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!Lj($))return!0;return Oj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=Lj(Y)?Oj(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class N9{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function t7($,w){this[$]=r7.bind(null,w)}class sJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!_j($))return!0;return Sj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=_j(Y)?Sj(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class oJ{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function o7($,w={}){let A=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return A?`${$}:${A}`:$}function e7($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function $F($){return $.getStats().size*2}function eJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let A=[...w];for(let X of $)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)=>SA(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!$0(w)||!$0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if($0(X)&&$0(Y[A]))Y[A]=eJ(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((B)=>SA(B,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 SA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!SA($[Y],w[Y]))return!1;return!0}if($0($)&&$0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!SA($[X],w[X]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function wF($,w){if(!E9($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return eJ(w,A)}catch{return null}}catch{return null}}async function YF({name:$="",cwd:w,defaultConfig:Y}){let A=w||vJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=OA(A,`${U}${B}`),j=await wF(W,Y);if(j!==null)return j}try{let U=OA(A,"package.json");if(E9(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return eJ(Y,W)}catch{}}}catch{}return Y}function AF($,w={}){let Y=LA.cwd();while(Y.includes("storage"))Y=kj(Y,"..");let A=kj(Y,$||"");if(w?.relative)return q7(LA.cwd(),A);return A}async function XF(){try{let $=await YF({name:"clarity",defaultConfig:MA,cwd:LA.cwd(),endpoint:"",headers:{}});return{...MA,...$}}catch{return MA}}function U0(){if(b$.env.NODE_ENV==="test"||b$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function JF(){if(b$.env.NODE_ENV==="test"||b$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof b$<"u"){let $=b$.type;if($==="renderer"||$==="worker")return!1;return!!(b$.versions&&(b$.versions.node||b$.versions.bun))}return!1}class H9{async format($){let w=await JF(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:ow.pid,hostname:w(),environment:ow.env.NODE_ENV||"development",platform:ow.platform,version:ow.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ow.env.NODE_ENV||ow.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;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...iJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new H9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??y0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...IA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...IA};return{...IA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:iJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await R7(this.config.logDirectory,bj.F_OK|bj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await M7(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:zw.from($);try{if(!MJ(this.currentLogFile))await IJ(this.currentLogFile,"",{mode:420});if(X=Pj(this.currentLogFile,"a",420),f7(X,W,{flag:"a"}),xj(X),X!==void 0)RJ(X),X=void 0;if((await aw(this.currentLogFile)).size===0){if(await IJ(this.currentLogFile,W,{flag:"w",mode:420}),(await aw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{RJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 sw(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 sw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return sw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return fJ(16).toString("hex")}generateKey(){return fJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=fJ(16),A=E7("aes-256-gcm",w,Y),X=zw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:zw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=vj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(zw.from(zw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(U0())return;let $=await aw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await UA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await aw(Y).catch(()=>null))try{if(await uj(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await WA(B)}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 aw(Y).catch(()=>null))await uj(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await UA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await WA(sw(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=Dj($),A=H7(w),X=vj();await I7(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),MJ(this.currentLogFile))try{let $=Pj(this.currentLogFile,"r+");xj($),RJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await UA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await WA(sw(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?a.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=y0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${a.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.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,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!U0()){let j=O9[$],z=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:a.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:a.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let K=B.split(`
4
+ import{createRequire as AK}from"node:module";var $K=Object.defineProperty;var wK=($)=>$;function YK($,w){this[$]=wK.bind(null,w)}var Kj=($,w)=>{for(var Y in w)$K($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:YK.bind(w,Y)})};var t=($,w)=>()=>($&&(w=$($=0)),w);var b=AK(import.meta.url);import{existsSync as Oj,statSync as _j}from"fs";import{existsSync as B7,mkdirSync as zI,readdirSync as GI,readFileSync as j7,writeFileSync as KI}from"fs";import{homedir as tw}from"os";import{dirname as qI,resolve as Y$}from"path";import vA from"process";import{existsSync as Sj,statSync as Zj}from"fs";import{existsSync as uJ,mkdirSync as z7,readdirSync as G7,writeFileSync as K7}from"fs";import{homedir as aw}from"os";import{dirname as hj,resolve as c0}from"path";import Zw from"process";import{join as F7,relative as N7,resolve as Dj}from"path";import yA from"process";import{existsSync as E9,mkdirSync as QI,readdirSync as yI,writeFileSync as LI}from"fs";import{homedir as HJ}from"os";import{dirname as SI,resolve as v0}from"path";import zY from"process";import{join as q7,relative as E7,resolve as kj}from"path";import LA from"process";import{existsSync as T9,mkdirSync as xI,readdirSync as PI,writeFileSync as bI}from"fs";import{dirname as vI,resolve as OA}from"path";import vJ from"process";import{Buffer as zw}from"buffer";import{createCipheriv as T7,createDecipheriv as H7,randomBytes as fJ}from"crypto";import{closeSync as RJ,createReadStream as xj,createWriteStream as f7,existsSync as MJ,fsyncSync as Pj,openSync as bj,writeFileSync as R7}from"fs";import{access as M7,constants as uj,mkdir as I7,readdir as UA,rename as vj,stat as sw,unlink as WA,writeFile as IJ}from"fs/promises";import{join as ow}from"path";import y0 from"process";import{pipeline as V7}from"stream/promises";import{createGzip as cj}from"zlib";import ew from"process";import b$ from"process";import{Buffer as x$}from"buffer";import{createCipheriv as C7,createDecipheriv as Q7,randomBytes as VJ}from"crypto";import{closeSync as CJ,createReadStream as ij,createWriteStream as y7,existsSync as BA,fsyncSync as mj,openSync as gj,writeFileSync as L7}from"fs";import{access as O7,constants as dj,mkdir as _7,readdir as jA,rename as lj,stat as $1,unlink as zA,writeFile as QJ}from"fs/promises";import{isAbsolute as S7,join as w1,resolve as Z7}from"path";import D from"process";import{pipeline as h7}from"stream/promises";import{createGzip as nj}from"zlib";import Y1 from"process";import u$ from"process";import GA from"process";import{existsSync as KA}from"fs";import{resolve as yJ}from"path";import{existsSync as D7}from"fs";import{existsSync as k7,readdirSync as x7}from"fs";import{extname as LJ,resolve as pj}from"path";import P7 from"process";import{join as b7,relative as u7,resolve as rj}from"path";import _A from"process";import{Buffer as P$}from"buffer";import{createCipheriv as v7,createDecipheriv as c7,randomBytes as OJ}from"crypto";import{closeSync as _J,createReadStream as tj,createWriteStream as i7,existsSync as FA,fsyncSync as aj,openSync as sj,writeFileSync as m7}from"fs";import{access as g7,constants as oj,mkdir as d7,readdir as NA,rename as ej,stat as A1,unlink as qA,writeFile as SJ}from"fs/promises";import{isAbsolute as l7,join as X1,resolve as n7}from"path";import k from"process";import{pipeline as p7}from"stream/promises";import{createGzip as $9}from"zlib";import J1 from"process";import v$ from"process";import TA from"process";import{existsSync as HA}from"fs";import{resolve as PJ}from"path";import{existsSync as FN}from"fs";class N9{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!Oj($))return!0;return _j($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=Oj(Y)?_j(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class q9{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function a7($,w){this[$]=t7.bind(null,w)}class sJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!Sj($))return!0;return Zj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=Sj(Y)?Zj(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class oJ{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function e7($,w={}){let A=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return A?`${$}:${A}`:$}function $F($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function wF($){return $.getStats().size*2}function eJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let A=[...w];for(let X of $)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)=>SA(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!$0(w)||!$0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if($0(X)&&$0(Y[A]))Y[A]=eJ(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((B)=>SA(B,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 SA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!SA($[Y],w[Y]))return!1;return!0}if($0($)&&$0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!SA($[X],w[X]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function YF($,w){if(!T9($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return eJ(w,A)}catch{return null}}catch{return null}}async function AF({name:$="",cwd:w,defaultConfig:Y}){let A=w||vJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=OA(A,`${U}${B}`),j=await YF(W,Y);if(j!==null)return j}try{let U=OA(A,"package.json");if(T9(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return eJ(Y,W)}catch{}}}catch{}return Y}function XF($,w={}){let Y=LA.cwd();while(Y.includes("storage"))Y=kj(Y,"..");let A=kj(Y,$||"");if(w?.relative)return E7(LA.cwd(),A);return A}async function JF(){try{let $=await AF({name:"clarity",defaultConfig:MA,cwd:LA.cwd(),endpoint:"",headers:{}});return{...MA,...$}}catch{return MA}}function U0(){if(b$.env.NODE_ENV==="test"||b$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UF(){if(b$.env.NODE_ENV==="test"||b$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof b$<"u"){let $=b$.type;if($==="renderer"||$==="worker")return!1;return!!(b$.versions&&(b$.versions.node||b$.versions.bun))}return!1}class f9{async format($){let w=await UF(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:ew.pid,hostname:w(),environment:ew.env.NODE_ENV||"development",platform:ew.platform,version:ew.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:ew.env.NODE_ENV||ew.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;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...iJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new f9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??y0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...IA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...IA};return{...IA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:iJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await M7(this.config.logDirectory,uj.F_OK|uj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await I7(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:zw.from($);try{if(!MJ(this.currentLogFile))await IJ(this.currentLogFile,"",{mode:420});if(X=bj(this.currentLogFile,"a",420),R7(X,W,{flag:"a"}),Pj(X),X!==void 0)RJ(X),X=void 0;if((await sw(this.currentLogFile)).size===0){if(await IJ(this.currentLogFile,W,{flag:"w",mode:420}),(await sw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{RJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 ow(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 ow(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return ow(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return fJ(16).toString("hex")}generateKey(){return fJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=fJ(16),A=T7("aes-256-gcm",w,Y),X=zw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:zw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=cj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(zw.from(zw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(U0())return;let $=await sw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await UA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await sw(Y).catch(()=>null))try{if(await vj(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await WA(B)}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 sw(Y).catch(()=>null))await vj(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await UA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await WA(ow(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=xj($),A=f7(w),X=cj();await V7(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),MJ(this.currentLogFile))try{let $=bj(this.currentLogFile,"r+");Pj($),RJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await UA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await WA(ow(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?a.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=y0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${a.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.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,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!U0()){let j=_9[$],z=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:a.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:a.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let K=B.split(`
5
5
  `);for(let F of K)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:a.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let W=`${J} ${this.environment}.${$.toUpperCase()}: ${U}
6
6
  `;if(B)W+=`${B}
7
7
  `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time($){let w=performance.now();if(this.fancy&&!U0()){let Y=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:a.blue("◐"),tag:Y,message:`${a.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
8
- `,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let z=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:a.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(j.trim());await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new ZA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(U0())throw Error("createReadStream is not supported in browser environments");if(!MJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Dj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=zw.isBuffer($)?$:zw.from($,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),B=T7("aes-256-gcm",Y,X);return B.setAuthTag(J),zw.concat([B.update(U),B.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U0()}isServerMode(){return!U0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!U0()){let J=$.split(`
8
+ `,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let z=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:a.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(j.trim());await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new ZA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(U0())throw Error("createReadStream is not supported in browser environments");if(!MJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=zw.isBuffer($)?$:zw.from($,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),B=H7("aes-256-gcm",Y,X);return B.setAuthTag(J),zw.concat([B.update(U),B.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U0()}isServerMode(){return!U0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!U0()){let J=$.split(`
9
9
  `),U=Math.max(...J.map((z)=>z.length))+2,B=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,j=J.map((z)=>{let G=" ".repeat(U-z.length-2);return`│ ${z}${G} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:a.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(B)})),j.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(W),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let X=`${A} ${this.environment}.INFO: [BOX] ${$}
10
10
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(U0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${a.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();y0.stdin.removeListener("data",Y);try{if(typeof y0.stdin.setRawMode==="function")y0.stdin.setRawMode(!1)}catch{}y0.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof y0.stdin.setRawMode==="function")y0.stdin.setRawMode(!0)}catch{}y0.stdin.resume(),y0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,B=0;if(Y=$.replace(U,(W,j)=>{if(j==="%")return"%";if(B>=w.length)return W;let z=w[B++];switch(j){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return W}}),B<w.length)Y+=` ${w.slice(B).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?a.gray(this.formatTag(this.name)):"",B=a.blue("◐");console.error(`${B} ${U} ${a.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
11
11
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||U0()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,B)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),B!==void 0)this.activeProgressBar.message=B;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,B="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;y0.stdout.write(`${"\r".padEnd(y0.stdout.columns||80)}\r`),this.log(B,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||U0()||!y0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=a.green("━".repeat(A)),U=a.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=w||Y===100?a.green("✓"):a.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=y0.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,y0.stdout.write($.lastRenderedLine),w)y0.stdout.write(`
12
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||U0()||!y0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await UA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=sw(this.config.logDirectory,A);if($.before)try{if((await aw(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}function RA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let A=[...w];for(let X of $)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)=>hA(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!d(w)||!d($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(d(X)&&d(Y[A]))Y[A]=RA(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((B)=>hA(B,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 $U($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:RA($,w);if(Array.isArray($))return Y==="replace"?w:RA($,w);if(!d(w)||!d($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[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]=RA(U,J);else if(d(J)&&d(U))A[X]=$U(U,J,Y);else A[X]=J}return A}function hA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!hA($[Y],w[Y]))return!1;return!0}if(d($)&&d(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!hA($[X],w[X]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function EA($,w,Y="replace"){if(!q9($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return $U(w,X,Y)}catch{return null}}catch{return null}}function UF($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${G.map(K).join("_")}`,T=`${A}_${G.map((q)=>q.toUpperCase()).join("_")}`;if(Y)O0.info(`Checking environment variable ${F} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let q=zY.env[F]||zY.env[T];if(q!==void 0){if(Y)O0.info(`Using environment variable ${q?F:T} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(q);else if(typeof z==="boolean")W[j]=q.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(q);if(Array.isArray(E))W[j]=E;else W[j]=q.split(",").map((f)=>f.trim())}catch{W[j]=q.split(",").map((E)=>E.trim())}else W[j]=q}}}return W}return J(X)}async function WF({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?UF($,X,J):X,j=Y||zY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)O0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),K=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],q=Array.from(new Set([j,v0(j,"config"),v0(j,".config"),A?v0(j,A):void 0].filter(Boolean)));for(let E of q){if(J)O0.info(`Searching for configuration in: ${E}`);let M=[v0(j,"config"),v0(j,".config")].concat(A?[v0(j,A)]:[]).includes(E)?[...G,...K,...F,...T]:[...K,...G,...T,...F];for(let Q of M)for(let V of z){let H=v0(E,`${Q}${V}`),I=await EA(H,W,B);if(I!==null){if(J)O0.success(`Configuration loaded from: ${H}`);return I}}}if($){let E=v0(HJ(),".config",$),f=["config",`${$}.config`];if(w)f.push(`${w}.config`);if(J)O0.info(`Checking user config directory: ${E}`);for(let M of f)for(let Q of z){let V=v0(E,`${M}${Q}`),H=await EA(V,W,B);if(H!==null){if(J)O0.success(`Configuration loaded from user config directory: ${V}`);return H}}}if($){let E=v0(HJ(),".config"),f=[`.${$}.config`];if(w)f.push(`.${w}.config`);if(J)O0.info(`Checking user config directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=v0(E,`${M}${Q}`),H=await EA(V,W,B);if(H!==null){if(J)O0.success(`Configuration loaded from user config directory dotfile: ${V}`);return H}}}if($){let E=HJ(),f=[`.${$}.config`,`.${$}`];if(w)f.push(`.${w}.config`),f.push(`.${w}`);if(J)O0.info(`Checking user home directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=v0(E,`${M}${Q}`),H=await EA(V,W,B);if(H!==null){if(J)O0.success(`Configuration loaded from user home directory: ${V}`);return H}}}try{let E=v0(j,"package.json");if(q9(E)){let f=await import(E),M=f[$];if(!M&&w){if(M=f[w],M&&J)O0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)O0.success(`Configuration loaded from package.json: ${M===f[$]?$:w}`);return $U(W,M,B)}catch(Q){if(J)O0.warn("Failed to merge package.json config:",Q)}}}catch(E){if(J)O0.warn("Failed to load package.json:",E)}if(J)O0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function BF($,w={}){let Y=yA.cwd();while(Y.includes("storage"))Y=hj(Y,"..");let A=hj(Y,$||"");if(w?.relative)return F7(yA.cwd(),A);return A}async function jF(){try{let $=await WF({name:"clarity",alias:"logging",defaultConfig:VA,cwd:yA.cwd()});return{...VA,...$||{}}}catch{return VA}}function F0(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zF(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof u$<"u"){let $=u$.type;if($==="renderer"||$==="worker")return!1;return!!(u$.versions&&(u$.versions.node||u$.versions.bun))}return!1}class f9{async format($){let w=await zF(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:w1.pid,hostname:w(),environment:w1.env.NODE_ENV||"development",platform:w1.platform,version:w1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:w1.env.NODE_ENV||w1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class kA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...mJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new f9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...CA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...CA};return{...CA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:mJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await L7(this.config.logDirectory,gj.F_OK|gj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await O7(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:x$.from($);try{if(!BA(this.currentLogFile))await QJ(this.currentLogFile,"",{mode:420});if(X=mj(this.currentLogFile,"a",420),y7(X,W,{flag:"a"}),ij(X),X!==void 0)CJ(X),X=void 0;if((await ew(this.currentLogFile)).size===0){if(await QJ(this.currentLogFile,W,{flag:"w",mode:420}),(await ew(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{CJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 $=new Date().toISOString().split("T")[0];return $1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return VJ(16).toString("hex")}generateKey(){return VJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=VJ(16),A=V7("aes-256-gcm",w,Y),X=x$.isBuffer($)?$:x$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=x$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=lj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(x$.from(x$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(F0())return;if(!this.shouldWriteToFile())return;let $=await ew(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await jA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await ew(Y).catch(()=>null))try{if(await dj(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await zA(B)}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 ew(Y).catch(()=>null))await dj(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await jA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await zA($1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=cj($),A=Q7(w),X=lj();await Z7(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),BA(this.currentLogFile))try{let $=mj(this.currentLogFile,"r+");ij($),CJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await jA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await zA($1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=k.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${u.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),w}supportsHyperlinks(){if(F0())return!1;let $=k.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=k.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(_7(w)||w.startsWith("./")||w.startsWith("../"))w=S7(w);else return null;return BA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":_9[$],K=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:u.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:u.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
12
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||U0()||!y0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await UA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=ow(this.config.logDirectory,A);if($.before)try{if((await sw(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}function RA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let A=[...w];for(let X of $)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)=>hA(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!d(w)||!d($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(d(X)&&d(Y[A]))Y[A]=RA(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((B)=>hA(B,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 $U($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:RA($,w);if(Array.isArray($))return Y==="replace"?w:RA($,w);if(!d(w)||!d($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[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]=RA(U,J);else if(d(J)&&d(U))A[X]=$U(U,J,Y);else A[X]=J}return A}function hA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!hA($[Y],w[Y]))return!1;return!0}if(d($)&&d(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!hA($[X],w[X]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function EA($,w,Y="replace"){if(!E9($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return $U(w,X,Y)}catch{return null}}catch{return null}}function WF($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${G.map(K).join("_")}`,T=`${A}_${G.map((q)=>q.toUpperCase()).join("_")}`;if(Y)O0.info(`Checking environment variable ${F} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let q=zY.env[F]||zY.env[T];if(q!==void 0){if(Y)O0.info(`Using environment variable ${q?F:T} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(q);else if(typeof z==="boolean")W[j]=q.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(q);if(Array.isArray(E))W[j]=E;else W[j]=q.split(",").map((f)=>f.trim())}catch{W[j]=q.split(",").map((E)=>E.trim())}else W[j]=q}}}return W}return J(X)}async function BF({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?WF($,X,J):X,j=Y||zY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)O0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),K=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],q=Array.from(new Set([j,v0(j,"config"),v0(j,".config"),A?v0(j,A):void 0].filter(Boolean)));for(let E of q){if(J)O0.info(`Searching for configuration in: ${E}`);let M=[v0(j,"config"),v0(j,".config")].concat(A?[v0(j,A)]:[]).includes(E)?[...G,...K,...F,...T]:[...K,...G,...T,...F];for(let Q of M)for(let V of z){let H=v0(E,`${Q}${V}`),I=await EA(H,W,B);if(I!==null){if(J)O0.success(`Configuration loaded from: ${H}`);return I}}}if($){let E=v0(HJ(),".config",$),f=["config",`${$}.config`];if(w)f.push(`${w}.config`);if(J)O0.info(`Checking user config directory: ${E}`);for(let M of f)for(let Q of z){let V=v0(E,`${M}${Q}`),H=await EA(V,W,B);if(H!==null){if(J)O0.success(`Configuration loaded from user config directory: ${V}`);return H}}}if($){let E=v0(HJ(),".config"),f=[`.${$}.config`];if(w)f.push(`.${w}.config`);if(J)O0.info(`Checking user config directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=v0(E,`${M}${Q}`),H=await EA(V,W,B);if(H!==null){if(J)O0.success(`Configuration loaded from user config directory dotfile: ${V}`);return H}}}if($){let E=HJ(),f=[`.${$}.config`,`.${$}`];if(w)f.push(`.${w}.config`),f.push(`.${w}`);if(J)O0.info(`Checking user home directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=v0(E,`${M}${Q}`),H=await EA(V,W,B);if(H!==null){if(J)O0.success(`Configuration loaded from user home directory: ${V}`);return H}}}try{let E=v0(j,"package.json");if(E9(E)){let f=await import(E),M=f[$];if(!M&&w){if(M=f[w],M&&J)O0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)O0.success(`Configuration loaded from package.json: ${M===f[$]?$:w}`);return $U(W,M,B)}catch(Q){if(J)O0.warn("Failed to merge package.json config:",Q)}}}catch(E){if(J)O0.warn("Failed to load package.json:",E)}if(J)O0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function jF($,w={}){let Y=yA.cwd();while(Y.includes("storage"))Y=Dj(Y,"..");let A=Dj(Y,$||"");if(w?.relative)return N7(yA.cwd(),A);return A}async function zF(){try{let $=await BF({name:"clarity",alias:"logging",defaultConfig:VA,cwd:yA.cwd()});return{...VA,...$||{}}}catch{return VA}}function F0(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function GF(){if(u$.env.NODE_ENV==="test"||u$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof u$<"u"){let $=u$.type;if($==="renderer"||$==="worker")return!1;return!!(u$.versions&&(u$.versions.node||u$.versions.bun))}return!1}class R9{async format($){let w=await GF(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Y1.pid,hostname:w(),environment:Y1.env.NODE_ENV||"development",platform:Y1.platform,version:Y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Y1.env.NODE_ENV||Y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class DA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...mJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new R9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...CA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...CA};return{...CA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:mJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await O7(this.config.logDirectory,dj.F_OK|dj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await _7(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:x$.from($);try{if(!BA(this.currentLogFile))await QJ(this.currentLogFile,"",{mode:420});if(X=gj(this.currentLogFile,"a",420),L7(X,W,{flag:"a"}),mj(X),X!==void 0)CJ(X),X=void 0;if((await $1(this.currentLogFile)).size===0){if(await QJ(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(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{CJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 w1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return w1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return w1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return VJ(16).toString("hex")}generateKey(){return VJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=VJ(16),A=C7("aes-256-gcm",w,Y),X=x$.isBuffer($)?$:x$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=x$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=nj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(x$.from(x$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(F0())return;if(!this.shouldWriteToFile())return;let $=await $1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await jA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await $1(Y).catch(()=>null))try{if(await lj(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await zA(B)}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 $1(Y).catch(()=>null))await lj(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await jA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await zA(w1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=ij($),A=y7(w),X=nj();await h7(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),BA(this.currentLogFile))try{let $=gj(this.currentLogFile,"r+");mj($),CJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await jA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await zA(w1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=D.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${u.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),w}supportsHyperlinks(){if(F0())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=D.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(S7(w)||w.startsWith("./")||w.startsWith("../"))w=Z7(w);else return null;return BA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":S9[$],K=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:u.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:u.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
13
13
  `);for(let q of T)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:u.gray(` ${q}`),level:$,showTimestamp:!1}))}break}}else if(!F0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
14
14
  `;if(B)z+=`${B}
15
- `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!F0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!F0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!F0()&&k.stdout.isTTY)k.stdout.write(`
16
- `);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!F0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:Y,message:`${u.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
17
- `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":u.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!F0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new kA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(F0())throw Error("createReadStream is not supported in browser environments");if(!BA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return cj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=x$.isBuffer($)?$:x$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=C7("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=x$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
15
+ `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!F0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!F0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!F0()&&D.stdout.isTTY)D.stdout.write(`
16
+ `);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!F0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:Y,message:`${u.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
17
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":u.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!F0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new DA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(F0())throw Error("createReadStream is not supported in browser environments");if(!BA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return ij(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=x$.isBuffer($)?$:x$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=Q7("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=x$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
18
18
  `),W=Math.max(...B.map((K)=>K.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((K)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(K),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(j),showTimestamp:!1})),G.forEach((K)=>console.error(K)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(z),showTimestamp:!1}))}else if(!F0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
19
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(F0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${u.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let K=w[j++];switch(G){case"s":return String(K);case"d":case"i":return Number(K).toString();case"j":case"o":return JSON.stringify(K,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${j}${W} ${u.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
20
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!k.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?u.green("✓"):u.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=k.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,k.stdout.write($.lastRenderedLine),w)k.stdout.write(`
21
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(F0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await jA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=$1(this.config.logDirectory,A);if($.before)try{if((await ew(J)).mtime>=$.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 zA(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(w){console.error("Error during log clearing process:",w)}}}async function R9($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function M9($){return $ instanceof a0}function GF($){return $ instanceof DA}function KF($){if(M9($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class cA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return FY.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=GA.env[W]||(j?GA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=GA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof xA)throw G;throw Gw.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Gw.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(GA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
19
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(F0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${u.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();D.stdin.removeListener("data",Y);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let K=w[j++];switch(G){case"s":return String(K);case"d":case"i":return Number(K).toString();case"j":case"o":return JSON.stringify(K,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${j}${W} ${u.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
20
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?u.green("✓"):u.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=D.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,D.stdout.write($.lastRenderedLine),w)D.stdout.write(`
21
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||F0()||!D.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(F0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await jA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=w1(this.config.logDirectory,A);if($.before)try{if((await $1(J)).mtime>=$.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 zA(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(w){console.error("Error during log clearing process:",w)}}}async function M9($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function I9($){return $ instanceof a0}function KF($){return $ instanceof kA}function FF($){if(I9($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class cA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return FY.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=GA.env[W]||(j?GA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=GA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof xA)throw G;throw Gw.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Gw.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(GA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
22
22
 
23
23
  `;for(let A of $)Y+=`${A.key}
24
24
  `,Y+=` Type: ${A.type}
@@ -30,25 +30,25 @@ import{createRequire as YK}from"node:module";var e6=Object.defineProperty;var $K
30
30
  `;Y+=`| Variable | Type | Description | Example |
31
31
  `,Y+=`|----------|------|-------------|----------|
32
32
  `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
33
- `;return Y}}function FF($,w){let Y=y9("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function I9($,w,Y={}){return V9($,w,Y,new WeakMap)}function V9($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return C9($,w,X,A);if(!A$(w)||!A$($))return w;return TF($,w,Y,A)}function C9($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return NF($,w);case"smart":return qF($,w,A);default:return w}return w}function NF($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>cJ(X,A)))Y.push(A);return Y}function qF($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(A$(w[0])&&A$($[0]))return EF($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function EF($,w,Y){let A=[...w];for(let X of $){if(!A$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>A$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function TF($,w,Y,A){let X=w;if(A$(X)&&A.has(X))return A.get(X);let J={...$};if(A$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(A$(B)&&A$(W))J[U]=V9(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=C9(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function wU($,w,Y="replace"){return I9($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function cJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!cJ($[Y],w[Y]))return!1;return!0}if(A$($)&&A$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!cJ($[X],w[X]))return!1}return!0}return!1}function A$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class iA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:B=!1}=Y;if(X){let j=J1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!KA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new GY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new GY($,Error("Configuration must export a valid object"),"unknown");let E={config:wU(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)J1.setWithFileCheck("file",E,$,J);return E}catch(j){throw j instanceof Error?Gw.configLoad($,j):Gw.configLoad($,Error(String(j)))}};if(U)return FY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(yJ(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return R9(async()=>{return KA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!KA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=yJ($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=yJ($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!KA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class YU{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await FY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!h7(w))throw new KY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new KY(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Z9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class AU{fileLoader=new iA;envProcessor=new cA;validator=new YU;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)K$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw K$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||Zw.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(c0(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw Gw.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?jY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)K$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)K$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?jY($,Y,X):Y,B=[c0(tw(),".config",$),c0(tw(),".config"),tw()];for(let W of B){if(X)K$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)K$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?jY($,A,J):A;try{let W=c0(Y,"package.json");if(!uJ(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)K$.success(`Configuration loaded from package.json: ${G}`);return{config:wU(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)K$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:jY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 Gw.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return J1.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);J1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,c0($,"config"),c0($,".config"),w?c0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let X=[];return X.push(...this.getLocalSearchPaths($,w,Y,A)),X.push(...this.getHomeSearchPaths($,w)),X.push(c0(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[c0(tw(),".config",$),c0(tw(),".config"),tw()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function $9($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function HF($){return c$.loadConfig({...$,__strictErrorHandling:!0})}async function Q9($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await c$.loadConfig($);else A=await c$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)K$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await c$.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function fF($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await c$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&$9(Y)))return(await c$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await c$.loadConfig({...$,cwd:$.cwd||Zw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&$9(w)))return(await c$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function RF($,w,Y="replace"){let A=new iA;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function jY($,w,Y=!1){let A=new cA,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=Zw.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function MF($){let w=c0(Zw.cwd(),$.configDir),Y=c0(Zw.cwd(),$.generatedDir),A=c0(Y,"config-types.ts");if(!uJ(Zj(A)))j7(Zj(A),{recursive:!0,mode:511});let X=uJ(w)?z7(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${aF}
33
+ `;return Y}}function NF($,w){let Y=L9("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function V9($,w,Y={}){return C9($,w,Y,new WeakMap)}function C9($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return Q9($,w,X,A);if(!A$(w)||!A$($))return w;return HF($,w,Y,A)}function Q9($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return qF($,w);case"smart":return EF($,w,A);default:return w}return w}function qF($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>cJ(X,A)))Y.push(A);return Y}function EF($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(A$(w[0])&&A$($[0]))return TF($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function TF($,w,Y){let A=[...w];for(let X of $){if(!A$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>A$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function HF($,w,Y,A){let X=w;if(A$(X)&&A.has(X))return A.get(X);let J={...$};if(A$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(A$(B)&&A$(W))J[U]=C9(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=Q9(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function wU($,w,Y="replace"){return V9($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function cJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!cJ($[Y],w[Y]))return!1;return!0}if(A$($)&&A$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!cJ($[X],w[X]))return!1}return!0}return!1}function A$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class iA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:B=!1}=Y;if(X){let j=U1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!KA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new GY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new GY($,Error("Configuration must export a valid object"),"unknown");let E={config:wU(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)U1.setWithFileCheck("file",E,$,J);return E}catch(j){throw j instanceof Error?Gw.configLoad($,j):Gw.configLoad($,Error(String(j)))}};if(U)return FY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(yJ(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return M9(async()=>{return KA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!KA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=yJ($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=yJ($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!KA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class YU{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await FY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!D7(w))throw new KY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new KY(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:h9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class AU{fileLoader=new iA;envProcessor=new cA;validator=new YU;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)K$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw K$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||Zw.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(c0(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw Gw.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?jY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)K$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)K$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?jY($,Y,X):Y,B=[c0(aw(),".config",$),c0(aw(),".config"),aw()];for(let W of B){if(X)K$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)K$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?jY($,A,J):A;try{let W=c0(Y,"package.json");if(!uJ(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)K$.success(`Configuration loaded from package.json: ${G}`);return{config:wU(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)K$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:jY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 Gw.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($,A);U1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,c0($,"config"),c0($,".config"),w?c0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let X=[];return X.push(...this.getLocalSearchPaths($,w,Y,A)),X.push(...this.getHomeSearchPaths($,w)),X.push(c0(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[c0(aw(),".config",$),c0(aw(),".config"),aw()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function w9($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function fF($){return c$.loadConfig({...$,__strictErrorHandling:!0})}async function y9($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await c$.loadConfig($);else A=await c$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)K$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await c$.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function RF($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await c$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&w9(Y)))return(await c$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await c$.loadConfig({...$,cwd:$.cwd||Zw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&w9(w)))return(await c$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function MF($,w,Y="replace"){let A=new iA;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function jY($,w,Y=!1){let A=new cA,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=Zw.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function IF($){let w=c0(Zw.cwd(),$.configDir),Y=c0(Zw.cwd(),$.generatedDir),A=c0(Y,"config-types.ts");if(!uJ(hj(A)))z7(hj(A),{recursive:!0,mode:511});let X=uJ(w)?G7(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${sF}
34
34
  export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
35
- `;G7(A,J,{mode:438})}function IF($){let w=null,Y=null,A=()=>{if(!Y)Y=Q9($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)K$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in $?$.defaultConfig:{};return w=X,A(),new Proxy({},{get(J,U){if(w)return w[U];let B=X[U];return A(),B},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,B){if(!w)w={...X};return w[U]=B,!0}})}function VF($){let w=nj(x7.cwd(),$?.configDir||"./config");function Y(){if(!k7(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=D7(w).filter((W)=>X.has(LJ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:j}of U){let z=LJ(j).toLowerCase(),G=B.get(W);if(!G){B.set(W,j);continue}let K=LJ(G).toLowerCase();if(J.indexOf(z)<J.indexOf(K))B.set(W,j)}return Array.from(B.entries()).map(([W,j])=>({base:W,file:j})).sort((W,j)=>W.base.localeCompare(j.base))}function A(){let X=Y(),J=X.map((j)=>j.base),U=J.length?J.map((j)=>`'${j}'`).join(" | "):"string",B=X.length?`{
36
- ${X.map((j)=>{let z=nj(w,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${z}').default`}).join(`,
35
+ `;K7(A,J,{mode:438})}function VF($){let w=null,Y=null,A=()=>{if(!Y)Y=y9($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)K$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in $?$.defaultConfig:{};return w=X,A(),new Proxy({},{get(J,U){if(w)return w[U];let B=X[U];return A(),B},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,B){if(!w)w={...X};return w[U]=B,!0}})}function CF($){let w=pj(P7.cwd(),$?.configDir||"./config");function Y(){if(!k7(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=x7(w).filter((W)=>X.has(LJ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:j}of U){let z=LJ(j).toLowerCase(),G=B.get(W);if(!G){B.set(W,j);continue}let K=LJ(G).toLowerCase();if(J.indexOf(z)<J.indexOf(K))B.set(W,j)}return Array.from(B.entries()).map(([W,j])=>({base:W,file:j})).sort((W,j)=>W.base.localeCompare(j.base))}function A(){let X=Y(),J=X.map((j)=>j.base),U=J.length?J.map((j)=>`'${j}'`).join(" | "):"string",B=X.length?`{
36
+ ${X.map((j)=>{let z=pj(w,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${z}').default`}).join(`,
37
37
  `)}
38
38
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
39
39
  export type ConfigByName = ${B}
40
40
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
41
41
  export type ConfigOf = Config
42
- `}return{name:"bunfig-plugin",setup(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 oF($,w={}){let Y=_A.cwd();while(Y.includes("storage"))Y=pj(Y,"..");let A=pj(Y,$||"");if(w?.relative)return b7(_A.cwd(),A);return A}function q0(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function $N(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof v$<"u"){let $=v$.type;if($==="renderer"||$==="worker")return!1;return!!(v$.versions&&(v$.versions.node||v$.versions.bun))}return!1}class x9{async format($){let w=await $N(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:X1.pid,hostname:w(),environment:X1.env.NODE_ENV||"development",platform:X1.platform,version:X1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:X1.env.NODE_ENV||X1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class mA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...PA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new x9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...xJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...xJ};return{...xJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:PA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await m7(this.config.logDirectory,sj.F_OK|sj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await g7(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P$.from($);try{if(!FA(this.currentLogFile))await SJ(this.currentLogFile,"",{mode:420});if(X=aj(this.currentLogFile,"a",420),i7(X,W,{flag:"a"}),tj(X),X!==void 0)_J(X),X=void 0;if((await Y1(this.currentLogFile)).size===0){if(await SJ(this.currentLogFile,W,{flag:"w",mode:420}),(await Y1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{_J(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 A1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return A1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return A1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return OJ(16).toString("hex")}generateKey(){return OJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=OJ(16),A=u7("aes-256-gcm",w,Y),X=P$.isBuffer($)?$:P$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=P$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=ej(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(P$.from(P$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let $=await Y1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await NA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await Y1(Y).catch(()=>null))try{if(await oj(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await qA(B)}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 SJ(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 Y1(Y).catch(()=>null))await oj(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await NA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await qA(A1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=rj($),A=c7(w),X=ej();await n7(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),FA(this.currentLogFile))try{let $=aj(this.currentLogFile,"r+");tj($),_J($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await NA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await qA(A1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=D.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${i.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=i.underline(i.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>i.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>i.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>i.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>i.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>i.strikethrough(A)),w}supportsHyperlinks(){if(q0())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=D.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(d7(w)||w.startsWith("./")||w.startsWith("../"))w=l7(w);else return null;return FA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":JN[$],K=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:i.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:i.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
42
+ `}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 eF($,w={}){let Y=_A.cwd();while(Y.includes("storage"))Y=rj(Y,"..");let A=rj(Y,$||"");if(w?.relative)return u7(_A.cwd(),A);return A}function q0(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wN(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof v$<"u"){let $=v$.type;if($==="renderer"||$==="worker")return!1;return!!(v$.versions&&(v$.versions.node||v$.versions.bun))}return!1}class P9{async format($){let w=await wN(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:J1.pid,hostname:w(),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 mA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...PA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new P9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...xJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...xJ};return{...xJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:PA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await g7(this.config.logDirectory,oj.F_OK|oj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await d7(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P$.from($);try{if(!FA(this.currentLogFile))await SJ(this.currentLogFile,"",{mode:420});if(X=sj(this.currentLogFile,"a",420),m7(X,W,{flag:"a"}),aj(X),X!==void 0)_J(X),X=void 0;if((await A1(this.currentLogFile)).size===0){if(await SJ(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(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{_J(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 $=new Date().toISOString().split("T")[0];return X1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return OJ(16).toString("hex")}generateKey(){return OJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=OJ(16),A=v7("aes-256-gcm",w,Y),X=P$.isBuffer($)?$:P$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=P$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=$9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(P$.from(P$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let $=await A1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await NA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await A1(Y).catch(()=>null))try{if(await ej(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await qA(B)}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 SJ(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 ej(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await NA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await qA(X1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=tj($),A=i7(w),X=$9();await p7(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),FA(this.currentLogFile))try{let $=sj(this.currentLogFile,"r+");aj($),_J($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await NA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await qA(X1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=k.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${i.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=i.underline(i.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>i.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>i.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>i.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>i.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>i.strikethrough(A)),w}supportsHyperlinks(){if(q0())return!1;let $=k.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=k.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(l7(w)||w.startsWith("./")||w.startsWith("../"))w=n7(w);else return null;return FA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":UN[$],K=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:i.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:i.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
43
43
  `);for(let q of T)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:i.gray(` ${q}`),level:$,showTimestamp:!1}))}break}}else if(!q0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
44
44
  `;if(B)z+=`${B}
45
- `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!q0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!q0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!q0()&&D.stdout.isTTY)D.stdout.write(`
46
- `);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!q0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":i.blue("◐"),tag:Y,message:`${i.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
47
- `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":i.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!q0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new mA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(q0())throw Error("createReadStream is not supported in browser environments");if(!FA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=P$.isBuffer($)?$:P$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=v7("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=P$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q0()}isServerMode(){return!q0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
45
+ `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!q0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!q0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!q0()&&k.stdout.isTTY)k.stdout.write(`
46
+ `);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!q0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":i.blue("◐"),tag:Y,message:`${i.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
47
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":i.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!q0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new mA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(q0())throw Error("createReadStream is not supported in browser environments");if(!FA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return tj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=P$.isBuffer($)?$:P$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=c7("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=P$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q0()}isServerMode(){return!q0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
48
48
  `),W=Math.max(...B.map((K)=>K.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((K)=>{return this.formatConsoleMessage({timestamp:Y,message:i.cyan(K),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(j),showTimestamp:!1})),G.forEach((K)=>console.error(K)),console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(z),showTimestamp:!1}))}else if(!q0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
49
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(q0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${i.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();D.stdin.removeListener("data",Y);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let K=w[j++];switch(G){case"s":return String(K);case"d":case"i":return Number(K).toString();case"j":case"o":return JSON.stringify(K,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${j}${W} ${i.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
50
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=i.green("━".repeat(A)),U=i.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?i.green("✓"):i.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=D.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,D.stdout.write($.lastRenderedLine),w)D.stdout.write(`
51
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||q0()||!D.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await NA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=A1(this.config.logDirectory,A);if($.before)try{if((await Y1(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}async function UN($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class JU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return aJ.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=TA.env[W]||(j?TA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=TA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof XU)throw G;throw U1.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw U1.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(TA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
49
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(q0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${i.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let K=w[j++];switch(G){case"s":return String(K);case"d":case"i":return Number(K).toString();case"j":case"o":return JSON.stringify(K,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${j}${W} ${i.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
50
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!k.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=i.green("━".repeat(A)),U=i.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?i.green("✓"):i.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=k.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,k.stdout.write($.lastRenderedLine),w)k.stdout.write(`
51
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||q0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await NA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=X1(this.config.logDirectory,A);if($.before)try{if((await A1(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}async function WN($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class JU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return aJ.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=TA.env[W]||(j?TA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=TA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof XU)throw G;throw W1.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw W1.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(TA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
52
52
 
53
53
  `;for(let A of $)Y+=`${A.key}
54
54
  `,Y+=` Type: ${A.type}
@@ -60,28 +60,28 @@ export type ConfigOf = Config
60
60
  `;Y+=`| Variable | Type | Description | Example |
61
61
  `,Y+=`|----------|------|-------------|----------|
62
62
  `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
63
- `;return Y}}function WN($,w,Y={}){return g9($,w,Y,new WeakMap)}function g9($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return d9($,w,X,A);if(!X$(w)||!X$($))return w;return GN($,w,Y,A)}function d9($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return BN($,w);case"smart":return jN($,w,A);default:return w}return w}function BN($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>tJ(X,A)))Y.push(A);return Y}function jN($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(X$(w[0])&&X$($[0]))return zN($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function zN($,w,Y){let A=[...w];for(let X of $){if(!X$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>X$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function GN($,w,Y,A){let X=w;if(X$(X)&&A.has(X))return A.get(X);let J={...$};if(X$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(X$(B)&&X$(W))J[U]=g9(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=d9(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function l9($,w,Y="replace"){return WN($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function tJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!tJ($[Y],w[Y]))return!1;return!0}if(X$($)&&X$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!tJ($[X],w[X]))return!1}return!0}return!1}function X$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class n9{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:B=!1}=Y;if(X){let j=QA.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!HA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new bA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new bA($,Error("Configuration must export a valid object"),"unknown");let E={config:l9(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)QA.setWithFileCheck("file",E,$,J);return E}catch(j){throw j instanceof Error?U1.configLoad($,j):U1.configLoad($,Error(String(j)))}};if(U)return aJ.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(PJ(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return UN(async()=>{return HA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!HA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=PJ($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=PJ($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!HA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class p9{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await aJ.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!KN(w))throw new uA(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new uA(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:FN},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function NN($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class r9{fileLoader=new n9;envProcessor=new JU;validator=new p9;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)C$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw C$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||vA.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(Y$(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw U1.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${NN(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?fA($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)C$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)C$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?fA($,Y,X):Y,B=[Y$(rw(),".config",$),Y$(rw(),".config"),rw()];for(let W of B){if(X)C$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)C$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?fA($,A,J):A;try{let W=Y$(Y,"package.json");if(!W7(W))return null;let j={};try{j=JSON.parse(B7(W,"utf8"))}catch(K){if(J)C$.warn("Failed to parse package.json:",[K instanceof Error?K:Error(String(K))]);return null}let z=j[$],G=$;if(!z&&w){let K=Array.isArray(w)?w:[w];for(let F of K){if(!F)continue;if(j[F]){z=j[F],G=F;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)C$.success(`Configuration loaded from package.json: ${G}`);return{config:l9(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)C$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:fA($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 U1.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($,A);QA.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,Y$($,"config"),Y$($,".config"),w?Y$($,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(Y$(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[Y$(rw(),".config",$),Y$(rw(),".config"),rw()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}async function UU($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await bJ.loadConfig($);else A=await bJ.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)C$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await bJ.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}function fA($,w,Y=!1){let A=new JU,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=vA.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}var QA,aJ,p7,r7=($)=>$,a7=($,w)=>{for(var Y in w)p7($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:t7.bind(w,Y)})},s7=($,w)=>()=>($&&(w=$($=0)),w),T9,y9,J1,FY,L9,CF,QF,w9,MA,iJ,L0,a,yF,Y9,LF,A9,OF,_F,ZJ,SF,X9,J9,hJ,ZF,hF,kF,DF,IA,O9,xF,O0,PF,bF,U9,VA,mJ,N0,u,uF,W9,vF,B9,cF,iF,kJ,mF,j9,z9,gF,DJ,dF,lF,nF,pF,rF,CA,_9,tF,aF="0.15.6",a0,DA,GY,gJ,dJ,xA,lJ,nJ,KY,pJ,rJ,Gw,S9,Z9,K$,c$,h9,k9,sF,eF,D9,PA,CV,I0,i,QV,wN,yV,YN,LV,OV,G9,_V,AN,XN,SV,K9,ZV,hV,kV,DV,xV,xJ,JN,PV,F$,P9,bA,b9,u9,XU,v9,c9,uA,i9,m9,U1,FN,C$,bJ,iV,mV;var WU=t(()=>{QA=new F9,aJ=new N9,p7=Object.defineProperty;T9={};a7(T9,{withErrorRecovery:()=>R9,tryLoadConfig:()=>RF,loadConfigWithResult:()=>HF,loadConfig:()=>Q9,isRetryableError:()=>KF,isConfigNotFoundError:()=>GF,isBunfigError:()=>M9,globalPerformanceMonitor:()=>FY,globalCache:()=>J1,getEnvOrDefault:()=>FF,generateConfigTypes:()=>MF,defaultGeneratedDir:()=>k9,defaultConfigDir:()=>h9,deepMergeWithArrayStrategy:()=>wU,deepMerge:()=>I9,createLibraryConfig:()=>IF,config:()=>fF,bunfigPlugin:()=>VF,applyEnvVarsToConfig:()=>jY,TypeGenerationError:()=>nJ,SchemaValidationError:()=>KY,PluginError:()=>rJ,PerformanceMonitor:()=>oJ,FileSystemError:()=>lJ,ErrorFactory:()=>Gw,EnvVarError:()=>xA,EnvProcessor:()=>cA,ConfigValidator:()=>YU,ConfigValidationError:()=>gJ,ConfigNotFoundError:()=>DA,ConfigMergeError:()=>dJ,ConfigLoader:()=>AU,ConfigLoadError:()=>GY,ConfigFileLoader:()=>iA,ConfigCache:()=>sJ,CacheUtils:()=>L9,BunfigError:()=>a0,BrowserConfigError:()=>pJ,ArrayMergeStrategies:()=>S9});sF=s7(async()=>{y9=import.meta.require,J1=new sJ,FY=new oJ,L9={createKey:o7,isEquivalent:e7,estimateMemoryUsage:$F},CF=OA(vJ.cwd(),"config"),QF=OA(vJ.cwd(),"src/generated"),w9=LA.env.CLARITY_LOG_DIR||N7(AF(),"logs"),MA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:w9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},iJ=await XF(),L0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},a=L0,yF=L0.red,Y9=L0.green,LF=L0.yellow,A9=L0.blue,OF=L0.magenta,_F=L0.cyan,ZJ=L0.white,SF=L0.gray,X9=L0.bgRed,J9=L0.bgYellow,hJ=L0.bold,ZF=L0.dim,hF=L0.italic,kF=L0.underline,DF=L0.reset,IA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},O9={debug:"\uD83D\uDD0D",info:A9("ℹ"),success:Y9("✓"),warning:J9(ZJ(hJ(" WARN "))),error:X9(ZJ(hJ(" ERROR ")))},xF=new ZA("stacks"),O0=new ZA("bunfig",{showTags:!0}),PF=v0(zY.cwd(),"config"),bF=v0(zY.cwd(),"src/generated"),U9=yA.env.CLARITY_LOG_DIR||K7(BF(),"logs"),VA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:U9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mJ=await jF(),N0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},u=N0,uF=N0.red,W9=N0.green,vF=N0.yellow,B9=N0.blue,cF=N0.magenta,iF=N0.cyan,kJ=N0.white,mF=N0.gray,j9=N0.bgRed,z9=N0.bgYellow,gF=N0.bgGray,DJ=N0.bold,dF=N0.dim,lF=N0.italic,nF=N0.underline,pF=N0.strikethrough,rF=N0.reset,CA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_9={debug:"\uD83D\uDD0D",info:B9("ℹ"),success:W9("✓"),warning:z9(kJ(DJ(" WARN "))),error:j9(kJ(DJ(" ERROR ")))},tF=new kA("stacks"),a0=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},DA=class extends a0{code="CONFIG_NOT_FOUND";constructor(w,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},GY=class extends a0{code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},gJ=class extends a0{code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},dJ=class extends a0{code="CONFIG_MERGE_ERROR";constructor(w,Y,A,X){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},xA=class extends a0{code="ENV_VAR_ERROR";constructor(w,Y,A,X){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:X})}},lJ=class extends a0{code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},nJ=class extends a0{code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},KY=class extends a0{code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},pJ=class extends a0{code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,X){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:X})}},rJ=class extends a0{code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Gw={configNotFound($,w,Y){return new DA($,w,Y)},configLoad($,w,Y){return new GY($,w,Y)},configValidation($,w,Y){return new gJ($,w,Y)},configMerge($,w,Y,A){return new dJ($,w,Y,A)},envVar($,w,Y,A){return new xA($,w,Y,A)},fileSystem($,w,Y){return new lJ($,w,Y)},typeGeneration($,w,Y){return new nJ($,w,Y)},schemaValidation($,w,Y){return new KY($,w,Y)},browserConfig($,w,Y,A){return new pJ($,w,Y,A)},plugin($,w,Y){return new rJ($,w,Y)}},S9={replace:"replace",concat:"concat",smart:"smart"},Z9=/^https?:\/\//,K$=new kA("bunfig",{showTags:!0}),c$=new AU,h9=c0(Zw.cwd(),"config"),k9=c0(Zw.cwd(),"src/generated")});eF=_A.env.CLARITY_LOG_DIR||P7(oF(),"logs"),D9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eF,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},PA={...D9},CV=(async()=>{try{let{loadConfig:$}=await sF().then(()=>T9),w=await $({name:"clarity",alias:"logging",defaultConfig:D9,cwd:_A.cwd()});if(w)Object.assign(PA,w)}catch{}return PA})();I0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=I0,QV=I0.red,wN=I0.green,yV=I0.yellow,YN=I0.blue,LV=I0.magenta,OV=I0.cyan,G9=I0.white,_V=I0.gray,AN=I0.bgRed,XN=I0.bgYellow,SV=I0.bgGray,K9=I0.bold,ZV=I0.dim,hV=I0.italic,kV=I0.underline,DV=I0.strikethrough,xV=I0.reset,xJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},JN={debug:"\uD83D\uDD0D",info:YN("ℹ"),success:wN("✓"),warning:XN(G9(K9(" WARN "))),error:AN(G9(K9(" ERROR ")))};PV=new mA("stacks");F$=class F$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};P9=class P9 extends F${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 "${$}"${X} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};bA=class bA extends F${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};b9=class b9 extends F${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};u9=class u9 extends F${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};XU=class XU extends F${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};v9=class v9 extends F${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};c9=class c9 extends F${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};uA=class uA extends F${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};i9=class i9 extends F${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};m9=class m9 extends F${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};U1={configNotFound($,w,Y){return new P9($,w,Y)},configLoad($,w,Y){return new bA($,w,Y)},configValidation($,w,Y){return new b9($,w,Y)},configMerge($,w,Y,A){return new u9($,w,Y,A)},envVar($,w,Y,A){return new XU($,w,Y,A)},fileSystem($,w,Y){return new v9($,w,Y)},typeGeneration($,w,Y){return new c9($,w,Y)},schemaValidation($,w,Y){return new uA($,w,Y)},browserConfig($,w,Y,A){return new i9($,w,Y,A)},plugin($,w,Y){return new m9($,w,Y)}};FN=/^https?:\/\//;C$=new mA("bunfig",{showTags:!0});bJ=new r9;iV=Y$(vA.cwd(),"config"),mV=Y$(vA.cwd(),"src/generated")});function B1($){return $.startsWith("*.")}function NY($,w){if(!B1(w))return!1;let Y=w.slice(1);return $.length>Y.length&&$.endsWith(Y)}function gA($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of $){if(!B1(J))continue;if(NY(w,J)){let B=J.length-1;if(B>X)X=B,A=U}}return A}var R;var i$=t(()=>{R={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as _N}from"node:module";import{Resolver as FU}from"node:dns/promises";import{createHash as ZN,sign as hN}from"node:crypto";import{createHash as kN}from"node:crypto";import{sign as DN}from"node:crypto";import{generateKeyPairSync as U2,X509Certificate as gN}from"node:crypto";import NU from"node:os";import qU from"node:path";import{existsSync as Az,statSync as Xz}from"fs";import{existsSync as lN,mkdirSync as G3,readdirSync as K3,readFileSync as nN,writeFileSync as F3}from"fs";import{homedir as z1}from"os";import{dirname as E3,resolve as U$}from"path";import SX from"process";import{existsSync as Jz,statSync as Uz}from"fs";import{existsSync as vU,mkdirSync as pN,readdirSync as rN,writeFileSync as tN}from"fs";import{homedir as G1}from"os";import{dirname as Wz,resolve as m0}from"path";import Dw from"process";import{join as aN,relative as sN,resolve as Bz}from"path";import FX from"process";import{existsSync as W2,mkdirSync as y3,readdirSync as L3,writeFileSync as O3}from"fs";import{homedir as EU}from"os";import{dirname as Z3,resolve as i0}from"path";import fY from"process";import{join as oN,relative as eN,resolve as jz}from"path";import NX from"process";import{existsSync as B2,mkdirSync as P3,readdirSync as b3,writeFileSync as u3}from"fs";import{dirname as c3,resolve as qX}from"path";import cU from"process";import{Buffer as Kw}from"buffer";import{createCipheriv as $q,createDecipheriv as wq,randomBytes as TU}from"crypto";import{closeSync as HU,createReadStream as zz,createWriteStream as Yq,existsSync as fU,fsyncSync as Gz,openSync as Kz,writeFileSync as Aq}from"fs";import{access as Xq,constants as Fz,mkdir as Jq,readdir as lA,rename as Nz,stat as K1,unlink as nA,writeFile as RU}from"fs/promises";import{join as F1}from"path";import _0 from"process";import{pipeline as Uq}from"stream/promises";import{createGzip as qz}from"zlib";import N1 from"process";import l$ from"process";import{Buffer as m$}from"buffer";import{createCipheriv as Wq,createDecipheriv as Bq,randomBytes as MU}from"crypto";import{closeSync as IU,createReadStream as Ez,createWriteStream as jq,existsSync as pA,fsyncSync as Tz,openSync as Hz,writeFileSync as zq}from"fs";import{access as Gq,constants as fz,mkdir as Kq,readdir as rA,rename as Rz,stat as q1,unlink as tA,writeFile as VU}from"fs/promises";import{isAbsolute as Fq,join as E1,resolve as Nq}from"path";import l from"process";import{pipeline as qq}from"stream/promises";import{createGzip as Mz}from"zlib";import T1 from"process";import n$ from"process";import aA from"process";import{existsSync as sA}from"fs";import{resolve as CU}from"path";import{existsSync as Eq}from"fs";import{existsSync as Tq,readdirSync as Hq}from"fs";import{extname as QU,resolve as Iz}from"path";import fq from"process";import{join as Rq,relative as Mq,resolve as Vz}from"path";import EX from"process";import{Buffer as g$}from"buffer";import{createCipheriv as Iq,createDecipheriv as Vq,randomBytes as yU}from"crypto";import{closeSync as LU,createReadStream as Cz,createWriteStream as Cq,existsSync as oA,fsyncSync as Qz,openSync as yz,writeFileSync as Qq}from"fs";import{access as yq,constants as Lz,mkdir as Lq,readdir as eA,rename as Oz,stat as H1,unlink as $X,writeFile as OU}from"fs/promises";import{isAbsolute as Oq,join as f1,resolve as _q}from"path";import n from"process";import{pipeline as Sq}from"stream/promises";import{createGzip as _z}from"zlib";import R1 from"process";import p$ from"process";import wX from"process";import{existsSync as YX}from"fs";import{resolve as _U}from"path";import{existsSync as Zq}from"fs";import{exec as eE}from"node:child_process";import sU from"node:fs";import $T from"node:os";import N$ from"node:path";import d2 from"node:process";import{promisify as wT}from"node:util";import C1 from"node:crypto";import r$ from"node:fs";import $W from"node:path";import CT from"node:crypto";import{execSync as LT}from"node:child_process";import OX from"node:os";async function pz($,w,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=$.split(".").slice(-2).join("."),U;try{let j=new FU,z=await j.resolveNs(J),G=(await Promise.all(z.map((K)=>j.resolve4(K).catch(()=>[])))).flat();if(G.length>0)U=new FU,U.setServers(G)}catch{}let B=Date.now()+A,W=U??new FU;for(;;){try{if((await W.resolveTxt($)).some((j)=>j.join("")===w))return!0}catch{}if(Date.now()>=B)return!1;await new Promise((j)=>setTimeout(j,X))}}class HY{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(HY.PATH_PREFIX);if(w===-1)return;let Y=$.slice(w+HY.PATH_PREFIX.length);return this.get(Y)}}function JX($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function xU($){return Buffer.from($,"base64url")}function rz($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function tz($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return ZN("sha256").update(w).digest("base64url")}function az($){let{protectedHeader:w,payload:Y,privateKey:A}=$,X=JX(JSON.stringify(w)),J=Y===""?"":JX(JSON.stringify(Y)),U=`${X}.${J}`,B=hN("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:JX(B)}}class KX{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=rz($.accountPublicKey),this.thumbprint=tz(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:Y,useJwk:A}=$,X={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=az({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)}),B=U.headers.get("replay-nonce");if(B)this.nonce=B;let W=U.headers.get("content-type")??"",j;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))j=await U.text();else{let z=await U.text();j=z?JSON.parse(z):{}}if(U.status>=400){let z=j??{};throw new GX(`ACME request to ${w} failed (HTTP ${U.status}): ${z.type??""} ${z.detail??""}`.trim(),z,U.status)}return{status:U.status,headers:U.headers,body:j,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),Y={termsOfServiceAgreed:!0};if($.email)Y.contact=[`mailto:${$.email}`];let A=await this.signedPost({url:w.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder($){let w=await this.directory(),Y={identifiers:$.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:w.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return kN("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization($);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((B)=>B.status==="invalid");throw new GX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await Yz(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder($);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 ${$} became invalid`);await Yz(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let Y=$.challenges.find((A)=>A.type===w);if(!Y)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return Y}}function ez($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=w[0];if(!Y)return{certPem:`${$.trim()}
63
+ `;return Y}}function BN($,w,Y={}){return d9($,w,Y,new WeakMap)}function d9($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return l9($,w,X,A);if(!X$(w)||!X$($))return w;return KN($,w,Y,A)}function l9($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return jN($,w);case"smart":return zN($,w,A);default:return w}return w}function jN($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>tJ(X,A)))Y.push(A);return Y}function zN($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(X$(w[0])&&X$($[0]))return GN($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function GN($,w,Y){let A=[...w];for(let X of $){if(!X$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>X$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function KN($,w,Y,A){let X=w;if(X$(X)&&A.has(X))return A.get(X);let J={...$};if(X$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(X$(B)&&X$(W))J[U]=d9(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=l9(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function n9($,w,Y="replace"){return BN($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function tJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!tJ($[Y],w[Y]))return!1;return!0}if(X$($)&&X$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!tJ($[X],w[X]))return!1}return!0}return!1}function X$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class p9{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:B=!1}=Y;if(X){let j=QA.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!HA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new bA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new bA($,Error("Configuration must export a valid object"),"unknown");let E={config:n9(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)QA.setWithFileCheck("file",E,$,J);return E}catch(j){throw j instanceof Error?W1.configLoad($,j):W1.configLoad($,Error(String(j)))}};if(U)return aJ.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(PJ(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return WN(async()=>{return HA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!HA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=PJ($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=PJ($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!HA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class r9{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await aJ.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!FN(w))throw new uA(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new uA(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:NN},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function qN($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class t9{fileLoader=new p9;envProcessor=new JU;validator=new r9;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)C$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw C$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||vA.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(Y$(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw W1.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${qN(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?fA($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)C$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)C$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?fA($,Y,X):Y,B=[Y$(tw(),".config",$),Y$(tw(),".config"),tw()];for(let W of B){if(X)C$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)C$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?fA($,A,J):A;try{let W=Y$(Y,"package.json");if(!B7(W))return null;let j={};try{j=JSON.parse(j7(W,"utf8"))}catch(K){if(J)C$.warn("Failed to parse package.json:",[K instanceof Error?K:Error(String(K))]);return null}let z=j[$],G=$;if(!z&&w){let K=Array.isArray(w)?w:[w];for(let F of K){if(!F)continue;if(j[F]){z=j[F],G=F;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)C$.success(`Configuration loaded from package.json: ${G}`);return{config:n9(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)C$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:fA($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 QA.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);QA.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,Y$($,"config"),Y$($,".config"),w?Y$($,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(Y$(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[Y$(tw(),".config",$),Y$(tw(),".config"),tw()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}async function UU($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await bJ.loadConfig($);else A=await bJ.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)C$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await bJ.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}function fA($,w,Y=!1){let A=new JU,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=vA.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}var QA,aJ,r7,t7=($)=>$,s7=($,w)=>{for(var Y in w)r7($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:a7.bind(w,Y)})},o7=($,w)=>()=>($&&(w=$($=0)),w),H9,L9,U1,FY,O9,QF,yF,Y9,MA,iJ,L0,a,LF,A9,OF,X9,_F,SF,ZJ,ZF,J9,U9,hJ,hF,DF,kF,xF,IA,_9,PF,O0,bF,uF,W9,VA,mJ,N0,u,vF,B9,cF,j9,iF,mF,DJ,gF,z9,G9,dF,kJ,lF,nF,pF,rF,tF,CA,S9,aF,sF="0.15.6",a0,kA,GY,gJ,dJ,xA,lJ,nJ,KY,pJ,rJ,Gw,Z9,h9,K$,c$,D9,k9,oF,$N,x9,PA,yV,I0,i,LV,YN,OV,AN,_V,SV,K9,ZV,XN,JN,hV,F9,DV,kV,xV,PV,bV,xJ,UN,uV,F$,b9,bA,u9,v9,XU,c9,i9,uA,m9,g9,W1,NN,C$,bJ,gV,dV;var WU=t(()=>{QA=new N9,aJ=new q9,r7=Object.defineProperty;H9={};s7(H9,{withErrorRecovery:()=>M9,tryLoadConfig:()=>MF,loadConfigWithResult:()=>fF,loadConfig:()=>y9,isRetryableError:()=>FF,isConfigNotFoundError:()=>KF,isBunfigError:()=>I9,globalPerformanceMonitor:()=>FY,globalCache:()=>U1,getEnvOrDefault:()=>NF,generateConfigTypes:()=>IF,defaultGeneratedDir:()=>k9,defaultConfigDir:()=>D9,deepMergeWithArrayStrategy:()=>wU,deepMerge:()=>V9,createLibraryConfig:()=>VF,config:()=>RF,bunfigPlugin:()=>CF,applyEnvVarsToConfig:()=>jY,TypeGenerationError:()=>nJ,SchemaValidationError:()=>KY,PluginError:()=>rJ,PerformanceMonitor:()=>oJ,FileSystemError:()=>lJ,ErrorFactory:()=>Gw,EnvVarError:()=>xA,EnvProcessor:()=>cA,ConfigValidator:()=>YU,ConfigValidationError:()=>gJ,ConfigNotFoundError:()=>kA,ConfigMergeError:()=>dJ,ConfigLoader:()=>AU,ConfigLoadError:()=>GY,ConfigFileLoader:()=>iA,ConfigCache:()=>sJ,CacheUtils:()=>O9,BunfigError:()=>a0,BrowserConfigError:()=>pJ,ArrayMergeStrategies:()=>Z9});oF=o7(async()=>{L9=import.meta.require,U1=new sJ,FY=new oJ,O9={createKey:e7,isEquivalent:$F,estimateMemoryUsage:wF},QF=OA(vJ.cwd(),"config"),yF=OA(vJ.cwd(),"src/generated"),Y9=LA.env.CLARITY_LOG_DIR||q7(XF(),"logs"),MA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Y9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},iJ=await JF(),L0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},a=L0,LF=L0.red,A9=L0.green,OF=L0.yellow,X9=L0.blue,_F=L0.magenta,SF=L0.cyan,ZJ=L0.white,ZF=L0.gray,J9=L0.bgRed,U9=L0.bgYellow,hJ=L0.bold,hF=L0.dim,DF=L0.italic,kF=L0.underline,xF=L0.reset,IA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},_9={debug:"\uD83D\uDD0D",info:X9("ℹ"),success:A9("✓"),warning:U9(ZJ(hJ(" WARN "))),error:J9(ZJ(hJ(" ERROR ")))},PF=new ZA("stacks"),O0=new ZA("bunfig",{showTags:!0}),bF=v0(zY.cwd(),"config"),uF=v0(zY.cwd(),"src/generated"),W9=yA.env.CLARITY_LOG_DIR||F7(jF(),"logs"),VA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:W9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},mJ=await zF(),N0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},u=N0,vF=N0.red,B9=N0.green,cF=N0.yellow,j9=N0.blue,iF=N0.magenta,mF=N0.cyan,DJ=N0.white,gF=N0.gray,z9=N0.bgRed,G9=N0.bgYellow,dF=N0.bgGray,kJ=N0.bold,lF=N0.dim,nF=N0.italic,pF=N0.underline,rF=N0.strikethrough,tF=N0.reset,CA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},S9={debug:"\uD83D\uDD0D",info:j9("ℹ"),success:B9("✓"),warning:G9(DJ(kJ(" WARN "))),error:z9(DJ(kJ(" ERROR ")))},aF=new DA("stacks"),a0=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},kA=class extends a0{code="CONFIG_NOT_FOUND";constructor(w,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},GY=class extends a0{code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},gJ=class extends a0{code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},dJ=class extends a0{code="CONFIG_MERGE_ERROR";constructor(w,Y,A,X){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},xA=class extends a0{code="ENV_VAR_ERROR";constructor(w,Y,A,X){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:X})}},lJ=class extends a0{code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},nJ=class extends a0{code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},KY=class extends a0{code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},pJ=class extends a0{code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,X){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:X})}},rJ=class extends a0{code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Gw={configNotFound($,w,Y){return new kA($,w,Y)},configLoad($,w,Y){return new GY($,w,Y)},configValidation($,w,Y){return new gJ($,w,Y)},configMerge($,w,Y,A){return new dJ($,w,Y,A)},envVar($,w,Y,A){return new xA($,w,Y,A)},fileSystem($,w,Y){return new lJ($,w,Y)},typeGeneration($,w,Y){return new nJ($,w,Y)},schemaValidation($,w,Y){return new KY($,w,Y)},browserConfig($,w,Y,A){return new pJ($,w,Y,A)},plugin($,w,Y){return new rJ($,w,Y)}},Z9={replace:"replace",concat:"concat",smart:"smart"},h9=/^https?:\/\//,K$=new DA("bunfig",{showTags:!0}),c$=new AU,D9=c0(Zw.cwd(),"config"),k9=c0(Zw.cwd(),"src/generated")});$N=_A.env.CLARITY_LOG_DIR||b7(eF(),"logs"),x9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$N,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},PA={...x9},yV=(async()=>{try{let{loadConfig:$}=await oF().then(()=>H9),w=await $({name:"clarity",alias:"logging",defaultConfig:x9,cwd:_A.cwd()});if(w)Object.assign(PA,w)}catch{}return PA})();I0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=I0,LV=I0.red,YN=I0.green,OV=I0.yellow,AN=I0.blue,_V=I0.magenta,SV=I0.cyan,K9=I0.white,ZV=I0.gray,XN=I0.bgRed,JN=I0.bgYellow,hV=I0.bgGray,F9=I0.bold,DV=I0.dim,kV=I0.italic,xV=I0.underline,PV=I0.strikethrough,bV=I0.reset,xJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},UN={debug:"\uD83D\uDD0D",info:AN("ℹ"),success:YN("✓"),warning:JN(K9(F9(" WARN "))),error:XN(K9(F9(" ERROR ")))};uV=new mA("stacks");F$=class F$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};b9=class b9 extends F${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 "${$}"${X} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};bA=class bA extends F${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};u9=class u9 extends F${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};v9=class v9 extends F${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};XU=class XU extends F${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};c9=class c9 extends F${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};i9=class i9 extends F${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};uA=class uA extends F${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};m9=class m9 extends F${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};g9=class g9 extends F${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};W1={configNotFound($,w,Y){return new b9($,w,Y)},configLoad($,w,Y){return new bA($,w,Y)},configValidation($,w,Y){return new u9($,w,Y)},configMerge($,w,Y,A){return new v9($,w,Y,A)},envVar($,w,Y,A){return new XU($,w,Y,A)},fileSystem($,w,Y){return new c9($,w,Y)},typeGeneration($,w,Y){return new i9($,w,Y)},schemaValidation($,w,Y){return new uA($,w,Y)},browserConfig($,w,Y,A){return new m9($,w,Y,A)},plugin($,w,Y){return new g9($,w,Y)}};NN=/^https?:\/\//;C$=new mA("bunfig",{showTags:!0});bJ=new t9;gV=Y$(vA.cwd(),"config"),dV=Y$(vA.cwd(),"src/generated")});function j1($){return $.startsWith("*.")}function NY($,w){if(!j1(w))return!1;let Y=w.slice(1);return $.length>Y.length&&$.endsWith(Y)}function gA($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of $){if(!j1(J))continue;if(NY(w,J)){let B=J.length-1;if(B>X)X=B,A=U}}return A}var R;var i$=t(()=>{R={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as SN}from"node:module";import{Resolver as FU}from"node:dns/promises";import{createHash as hN,sign as DN}from"node:crypto";import{createHash as kN}from"node:crypto";import{sign as xN}from"node:crypto";import{generateKeyPairSync as W2,X509Certificate as dN}from"node:crypto";import NU from"node:os";import qU from"node:path";import{existsSync as Xz,statSync as Jz}from"fs";import{existsSync as nN,mkdirSync as F3,readdirSync as N3,readFileSync as pN,writeFileSync as q3}from"fs";import{homedir as G1}from"os";import{dirname as H3,resolve as U$}from"path";import SX from"process";import{existsSync as Uz,statSync as Wz}from"fs";import{existsSync as vU,mkdirSync as rN,readdirSync as tN,writeFileSync as aN}from"fs";import{homedir as K1}from"os";import{dirname as Bz,resolve as m0}from"path";import kw from"process";import{join as sN,relative as oN,resolve as jz}from"path";import FX from"process";import{existsSync as B2,mkdirSync as O3,readdirSync as _3,writeFileSync as S3}from"fs";import{homedir as EU}from"os";import{dirname as D3,resolve as i0}from"path";import fY from"process";import{join as eN,relative as $q,resolve as zz}from"path";import NX from"process";import{existsSync as j2,mkdirSync as u3,readdirSync as v3,writeFileSync as c3}from"fs";import{dirname as m3,resolve as qX}from"path";import cU from"process";import{Buffer as Kw}from"buffer";import{createCipheriv as wq,createDecipheriv as Yq,randomBytes as TU}from"crypto";import{closeSync as HU,createReadStream as Gz,createWriteStream as Aq,existsSync as fU,fsyncSync as Kz,openSync as Fz,writeFileSync as Xq}from"fs";import{access as Jq,constants as Nz,mkdir as Uq,readdir as lA,rename as qz,stat as F1,unlink as nA,writeFile as RU}from"fs/promises";import{join as N1}from"path";import _0 from"process";import{pipeline as Wq}from"stream/promises";import{createGzip as Ez}from"zlib";import q1 from"process";import l$ from"process";import{Buffer as m$}from"buffer";import{createCipheriv as Bq,createDecipheriv as jq,randomBytes as MU}from"crypto";import{closeSync as IU,createReadStream as Tz,createWriteStream as zq,existsSync as pA,fsyncSync as Hz,openSync as fz,writeFileSync as Gq}from"fs";import{access as Kq,constants as Rz,mkdir as Fq,readdir as rA,rename as Mz,stat as E1,unlink as tA,writeFile as VU}from"fs/promises";import{isAbsolute as Nq,join as T1,resolve as qq}from"path";import l from"process";import{pipeline as Eq}from"stream/promises";import{createGzip as Iz}from"zlib";import H1 from"process";import n$ from"process";import aA from"process";import{existsSync as sA}from"fs";import{resolve as CU}from"path";import{existsSync as Tq}from"fs";import{existsSync as Hq,readdirSync as fq}from"fs";import{extname as QU,resolve as Vz}from"path";import Rq from"process";import{join as Mq,relative as Iq,resolve as Cz}from"path";import EX from"process";import{Buffer as g$}from"buffer";import{createCipheriv as Vq,createDecipheriv as Cq,randomBytes as yU}from"crypto";import{closeSync as LU,createReadStream as Qz,createWriteStream as Qq,existsSync as oA,fsyncSync as yz,openSync as Lz,writeFileSync as yq}from"fs";import{access as Lq,constants as Oz,mkdir as Oq,readdir as eA,rename as _z,stat as f1,unlink as $X,writeFile as OU}from"fs/promises";import{isAbsolute as _q,join as R1,resolve as Sq}from"path";import n from"process";import{pipeline as Zq}from"stream/promises";import{createGzip as Sz}from"zlib";import M1 from"process";import p$ from"process";import wX from"process";import{existsSync as YX}from"fs";import{resolve as _U}from"path";import{existsSync as hq}from"fs";import{exec as $T}from"node:child_process";import sU from"node:fs";import wT from"node:os";import N$ from"node:path";import l2 from"node:process";import{promisify as YT}from"node:util";import Q1 from"node:crypto";import r$ from"node:fs";import $W from"node:path";import QT from"node:crypto";import{execSync as OT}from"node:child_process";import OX from"node:os";async function rz($,w,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=$.split(".").slice(-2).join("."),U;try{let j=new FU,z=await j.resolveNs(J),G=(await Promise.all(z.map((K)=>j.resolve4(K).catch(()=>[])))).flat();if(G.length>0)U=new FU,U.setServers(G)}catch{}let B=Date.now()+A,W=U??new FU;for(;;){try{if((await W.resolveTxt($)).some((j)=>j.join("")===w))return!0}catch{}if(Date.now()>=B)return!1;await new Promise((j)=>setTimeout(j,X))}}class HY{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(HY.PATH_PREFIX);if(w===-1)return;let Y=$.slice(w+HY.PATH_PREFIX.length);return this.get(Y)}}function JX($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function xU($){return Buffer.from($,"base64url")}function tz($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function az($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return hN("sha256").update(w).digest("base64url")}function sz($){let{protectedHeader:w,payload:Y,privateKey:A}=$,X=JX(JSON.stringify(w)),J=Y===""?"":JX(JSON.stringify(Y)),U=`${X}.${J}`,B=DN("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:JX(B)}}class KX{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=tz($.accountPublicKey),this.thumbprint=az(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:Y,useJwk:A}=$,X={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=sz({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)}),B=U.headers.get("replay-nonce");if(B)this.nonce=B;let W=U.headers.get("content-type")??"",j;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))j=await U.text();else{let z=await U.text();j=z?JSON.parse(z):{}}if(U.status>=400){let z=j??{};throw new GX(`ACME request to ${w} failed (HTTP ${U.status}): ${z.type??""} ${z.detail??""}`.trim(),z,U.status)}return{status:U.status,headers:U.headers,body:j,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),Y={termsOfServiceAgreed:!0};if($.email)Y.contact=[`mailto:${$.email}`];let A=await this.signedPost({url:w.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder($){let w=await this.directory(),Y={identifiers:$.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:w.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return kN("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization($);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((B)=>B.status==="invalid");throw new GX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await Az(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder($);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 ${$} became invalid`);await Az(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let Y=$.challenges.find((A)=>A.type===w);if(!Y)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return Y}}function $2($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=w[0];if(!Y)return{certPem:`${$.trim()}
64
64
  `,chainPem:""};let A=`${Y.trim()}
65
65
  `,X=w.slice(1).map((J)=>J.trim()).join(`
66
66
  `);return{certPem:A,chainPem:X?`${X}
67
- `:""}}function $2($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function Yz($){return new Promise((w)=>setTimeout(w,$))}function xN($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function qw($,w){return Buffer.concat([Buffer.from([$]),xN(w.length),w])}function w2($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=[],A=$;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);w=Buffer.from(Y)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return qw(2,w)}function kw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let Y=[40*w[0]+w[1]];for(let A=2;A<w.length;A++){let X=w[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 qw(6,Buffer.from(Y))}function J$(...$){return qw(48,Buffer.concat($))}function PU(...$){return qw(49,Buffer.concat($))}function bU($){return qw(3,Buffer.concat([Buffer.from([0]),$]))}function Y2($){return qw(4,$)}function A2($){return qw(12,Buffer.from($,"utf8"))}function uU($,w,Y){let A=128|(Y?32:0)|$;return qw(A,w)}function mN($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let Y=xU(w.x),A=xU(w.y);if(Y.length!==32||A.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${Y.length} y=${A.length}`);return Buffer.concat([Buffer.from([4]),Y,A])}function X2($){let{domains:w,publicKey:Y,privateKey:A}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let X=J$(PU(J$(kw(vN),A2(w[0])))),J=J$(J$(kw(PN),kw(bN)),bU(mN(Y))),U=w.map((q)=>uU(2,Buffer.from(q,"ascii"),!1)),B=J$(...U),W=J$(kw(iN),Y2(B)),j=J$(W),z=J$(kw(cN),PU(j)),G=uU(0,z,!0),K=J$(w2(0),X,J,G),F=DN("sha256",K,A),T=J$(kw(uN));return J$(K,T,bU(F))}function J2($){return X2($).toString("base64url")}function dN($){if($){let{createPrivateKey:X,createPublicKey:J}=SN("node:crypto"),U=X($),B=J(U);return{privateKey:U,publicKey:B,pem:$}}let{privateKey:w,publicKey:Y}=U2("ec",{namedCurve:"P-256"}),A=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:Y,pem:A}}async function wW($){let{domains:w,method:Y}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((G)=>G.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=$.directoryUrl??($.staging===!1?oz:sz),X=dN($.accountKeyPem),J=new KX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey});await J.newAccount({email:$.email});let{order:U,orderUrl:B}=await J.newOrder(w),W=$.http01Store??_X,j=[],z=[];try{for(let H of U.authorizations){let I=await J.getAuthorization(H);if(I.status==="valid")continue;let O=KX.selectChallenge(I,Y);if(Y==="dns-01"){let Z=$2(I.identifier.value),P0=J.dns01TxtValue(O.token);await $.dnsProvider.setTxt(Z,P0),j.push({name:Z,value:P0}),await pz(Z,P0,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else W.add(O.token,J.keyAuthorization(O.token)),z.push(O.token);await J.notifyChallengeReady(O.url),await J.pollAuthorization(H,{timeoutMs:$.timeoutMs})}let{privateKey:G,publicKey:K}=U2("ec",{namedCurve:"P-256"}),F=J2({domains:w,publicKey:K,privateKey:G});await J.finalizeOrder(U.finalize,F);let T=await J.pollOrder(B,{timeoutMs:$.timeoutMs}),q=await J.downloadCertificate(T),{certPem:E,chainPem:f}=ez(q),M=f?`${E}${f}`:E,Q=G.export({format:"pem",type:"pkcs8"}).toString(),V=new Date(new gN(E).validTo);return{certPem:E,keyPem:Q,chainPem:f,fullChainPem:M,accountKeyPem:X.pem,notAfter:V}}finally{for(let{name:G,value:K}of j)await $.dnsProvider?.removeTxt(G,K).catch(()=>{});for(let G of z)W.remove(G)}}class j2{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!Az($))return!0;return Xz($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=Az(Y)?Xz(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class z2{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function Dq($,w){this[$]=kq.bind(null,w)}class AW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!Jz($))return!0;return Uz($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=Jz(Y)?Uz(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class XW{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function bq($,w={}){let Y=Object.keys(w).sort().map((A)=>`${A}:${w[A]}`).join("|");return Y?`${$}:${Y}`:$}function uq($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function vq($){return $.getStats().size*2}function JW($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&w0(w[0])&&"id"in w[0]&&w[0].id===3&&w0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(w0(w)&&w0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(w0($)&&"arr"in $&&Array.isArray($.arr)&&w0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&w0(w[0])&&w0($[0])){let A=[...w];for(let X of $)if(w0(X)&&"name"in X){if(!A.find((J)=>w0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(w0(X)&&"path"in X){if(!A.find((J)=>w0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>HX(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!w0(w)||!w0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(w0(X)&&w0(Y[A]))Y[A]=JW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&w0(X[0])&&w0(Y[A][0])){let J=[...X];for(let U of Y[A])if(w0(U)&&"name"in U){if(!J.find((B)=>w0(B)&&("name"in B)&&B.name===U.name))J.push(U)}else if(w0(U)&&"path"in U){if(!J.find((B)=>w0(B)&&("path"in B)&&B.path===U.path))J.push(U)}else if(!J.some((B)=>HX(B,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 HX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!HX($[Y],w[Y]))return!1;return!0}if(w0($)&&w0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!HX($[X],w[X]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function cq($,w){if(!B2($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return JW(w,A)}catch{return null}}catch{return null}}async function iq({name:$="",cwd:w,defaultConfig:Y}){let A=w||cU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=qX(A,`${U}${B}`),j=await cq(W,Y);if(j!==null)return j}try{let U=qX(A,"package.json");if(B2(U)){let B=(await import(U))[$];if(B&&typeof B==="object"&&!Array.isArray(B))try{return JW(Y,B)}catch{}}}catch{}return Y}function mq($,w={}){let Y=NX.cwd();while(Y.includes("storage"))Y=jz(Y,"..");let A=jz(Y,$||"");if(w?.relative)return eN(NX.cwd(),A);return A}async function gq(){try{let $=await iq({name:"clarity",defaultConfig:WX,cwd:NX.cwd(),endpoint:"",headers:{}});return{...WX,...$}}catch{return WX}}function W0(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function dq(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l$<"u"){let $=l$.type;if($==="renderer"||$==="worker")return!1;return!!(l$.versions&&(l$.versions.node||l$.versions.bun))}return!1}class K2{async format($){let w=await dq(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:N1.pid,hostname:w(),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 fX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...mU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new K2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...BX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...BX};return{...BX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:mU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Xq(this.config.logDirectory,Fz.F_OK|Fz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Jq(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 B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Kw.from($);try{if(!fU(this.currentLogFile))await RU(this.currentLogFile,"",{mode:420});if(A=Kz(this.currentLogFile,"a",420),Aq(A,B,{flag:"a"}),Gz(A),A!==void 0)HU(A),A=void 0;if((await K1(this.currentLogFile)).size===0){if(await RU(this.currentLogFile,B,{flag:"w",mode:420}),(await K1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((K)=>setTimeout(K,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{HU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return F1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return F1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return F1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.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 TU(16).toString("hex")}generateKey(){return TU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=TU(16),A=$q("aes-256-gcm",w,Y),X=Kw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Kw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=qz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Kw.from(Kw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(W0())return;let $=await K1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await lA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await K1(Y).catch(()=>null))try{if(await Nz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await nA(B)}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 RU(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 Nz(Y,J)}if(this.currentLogFile=A,w.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(w.maxFiles))await nA(F1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=zz($),A=Yq(w),X=qz();await Uq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),fU(this.currentLogFile))try{let $=Kz(this.currentLogFile,"r+");Gz($),HU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await lA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await nA(F1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?s.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=_0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${s.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.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,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!W0()){let j=I2[$],z=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:s.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:s.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let K=B.split(`
67
+ `:""}}function w2($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function Az($){return new Promise((w)=>setTimeout(w,$))}function PN($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function qw($,w){return Buffer.concat([Buffer.from([$]),PN(w.length),w])}function Y2($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=[],A=$;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);w=Buffer.from(Y)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return qw(2,w)}function Dw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let Y=[40*w[0]+w[1]];for(let A=2;A<w.length;A++){let X=w[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 qw(6,Buffer.from(Y))}function J$(...$){return qw(48,Buffer.concat($))}function PU(...$){return qw(49,Buffer.concat($))}function bU($){return qw(3,Buffer.concat([Buffer.from([0]),$]))}function A2($){return qw(4,$)}function X2($){return qw(12,Buffer.from($,"utf8"))}function uU($,w,Y){let A=128|(Y?32:0)|$;return qw(A,w)}function gN($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let Y=xU(w.x),A=xU(w.y);if(Y.length!==32||A.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${Y.length} y=${A.length}`);return Buffer.concat([Buffer.from([4]),Y,A])}function J2($){let{domains:w,publicKey:Y,privateKey:A}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let X=J$(PU(J$(Dw(cN),X2(w[0])))),J=J$(J$(Dw(bN),Dw(uN)),bU(gN(Y))),U=w.map((q)=>uU(2,Buffer.from(q,"ascii"),!1)),B=J$(...U),W=J$(Dw(mN),A2(B)),j=J$(W),z=J$(Dw(iN),PU(j)),G=uU(0,z,!0),K=J$(Y2(0),X,J,G),F=xN("sha256",K,A),T=J$(Dw(vN));return J$(K,T,bU(F))}function U2($){return J2($).toString("base64url")}function lN($){if($){let{createPrivateKey:X,createPublicKey:J}=ZN("node:crypto"),U=X($),B=J(U);return{privateKey:U,publicKey:B,pem:$}}let{privateKey:w,publicKey:Y}=W2("ec",{namedCurve:"P-256"}),A=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:Y,pem:A}}async function wW($){let{domains:w,method:Y}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((G)=>G.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=$.directoryUrl??($.staging===!1?ez:oz),X=lN($.accountKeyPem),J=new KX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey});await J.newAccount({email:$.email});let{order:U,orderUrl:B}=await J.newOrder(w),W=$.http01Store??_X,j=[],z=[];try{for(let H of U.authorizations){let I=await J.getAuthorization(H);if(I.status==="valid")continue;let O=KX.selectChallenge(I,Y);if(Y==="dns-01"){let Z=w2(I.identifier.value),P0=J.dns01TxtValue(O.token);await $.dnsProvider.setTxt(Z,P0),j.push({name:Z,value:P0}),await rz(Z,P0,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else W.add(O.token,J.keyAuthorization(O.token)),z.push(O.token);await J.notifyChallengeReady(O.url),await J.pollAuthorization(H,{timeoutMs:$.timeoutMs})}let{privateKey:G,publicKey:K}=W2("ec",{namedCurve:"P-256"}),F=U2({domains:w,publicKey:K,privateKey:G});await J.finalizeOrder(U.finalize,F);let T=await J.pollOrder(B,{timeoutMs:$.timeoutMs}),q=await J.downloadCertificate(T),{certPem:E,chainPem:f}=$2(q),M=f?`${E}${f}`:E,Q=G.export({format:"pem",type:"pkcs8"}).toString(),V=new Date(new dN(E).validTo);return{certPem:E,keyPem:Q,chainPem:f,fullChainPem:M,accountKeyPem:X.pem,notAfter:V}}finally{for(let{name:G,value:K}of j)await $.dnsProvider?.removeTxt(G,K).catch(()=>{});for(let G of z)W.remove(G)}}class z2{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!Xz($))return!0;return Jz($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=Xz(Y)?Jz(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class G2{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function xq($,w){this[$]=kq.bind(null,w)}class AW{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!Uz($))return!0;return Wz($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=Uz(Y)?Wz(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class XW{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function uq($,w={}){let Y=Object.keys(w).sort().map((A)=>`${A}:${w[A]}`).join("|");return Y?`${$}:${Y}`:$}function vq($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function cq($){return $.getStats().size*2}function JW($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&w0(w[0])&&"id"in w[0]&&w[0].id===3&&w0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(w0(w)&&w0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(w0($)&&"arr"in $&&Array.isArray($.arr)&&w0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&w0(w[0])&&w0($[0])){let A=[...w];for(let X of $)if(w0(X)&&"name"in X){if(!A.find((J)=>w0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(w0(X)&&"path"in X){if(!A.find((J)=>w0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>HX(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!w0(w)||!w0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(w0(X)&&w0(Y[A]))Y[A]=JW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&w0(X[0])&&w0(Y[A][0])){let J=[...X];for(let U of Y[A])if(w0(U)&&"name"in U){if(!J.find((B)=>w0(B)&&("name"in B)&&B.name===U.name))J.push(U)}else if(w0(U)&&"path"in U){if(!J.find((B)=>w0(B)&&("path"in B)&&B.path===U.path))J.push(U)}else if(!J.some((B)=>HX(B,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 HX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!HX($[Y],w[Y]))return!1;return!0}if(w0($)&&w0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!HX($[X],w[X]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function iq($,w){if(!j2($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return JW(w,A)}catch{return null}}catch{return null}}async function mq({name:$="",cwd:w,defaultConfig:Y}){let A=w||cU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=qX(A,`${U}${B}`),j=await iq(W,Y);if(j!==null)return j}try{let U=qX(A,"package.json");if(j2(U)){let B=(await import(U))[$];if(B&&typeof B==="object"&&!Array.isArray(B))try{return JW(Y,B)}catch{}}}catch{}return Y}function gq($,w={}){let Y=NX.cwd();while(Y.includes("storage"))Y=zz(Y,"..");let A=zz(Y,$||"");if(w?.relative)return $q(NX.cwd(),A);return A}async function dq(){try{let $=await mq({name:"clarity",defaultConfig:WX,cwd:NX.cwd(),endpoint:"",headers:{}});return{...WX,...$}}catch{return WX}}function W0(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function lq(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l$<"u"){let $=l$.type;if($==="renderer"||$==="worker")return!1;return!!(l$.versions&&(l$.versions.node||l$.versions.bun))}return!1}class F2{async format($){let w=await lq(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:q1.pid,hostname:w(),environment:q1.env.NODE_ENV||"development",platform:q1.platform,version:q1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:q1.env.NODE_ENV||q1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class fX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...mU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new F2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...BX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...BX};return{...BX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:mU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Jq(this.config.logDirectory,Nz.F_OK|Nz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Uq(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 B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Kw.from($);try{if(!fU(this.currentLogFile))await RU(this.currentLogFile,"",{mode:420});if(A=Fz(this.currentLogFile,"a",420),Xq(A,B,{flag:"a"}),Kz(A),A!==void 0)HU(A),A=void 0;if((await F1(this.currentLogFile)).size===0){if(await RU(this.currentLogFile,B,{flag:"w",mode:420}),(await F1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((K)=>setTimeout(K,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{HU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return N1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return N1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return N1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.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 TU(16).toString("hex")}generateKey(){return TU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=TU(16),A=wq("aes-256-gcm",w,Y),X=Kw.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Kw.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Ez(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Kw.from(Kw.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(W0())return;let $=await F1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let 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,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await F1(Y).catch(()=>null))try{if(await qz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await nA(B)}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 RU(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 qz(Y,J)}if(this.currentLogFile=A,w.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(w.maxFiles))await nA(N1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=Gz($),A=Aq(w),X=Ez();await Wq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),fU(this.currentLogFile))try{let $=Fz(this.currentLogFile,"r+");Kz($),HU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await lA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await nA(N1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?s.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=_0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${s.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.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,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!W0()){let j=V2[$],z=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:s.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:s.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let K=B.split(`
68
68
  `);for(let F of K)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:s.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!W0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let W=`${J} ${this.environment}.${$.toUpperCase()}: ${U}
69
69
  `;if(B)W+=`${B}
70
70
  `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time($){let w=performance.now();if(this.fancy&&!W0()){let Y=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:s.blue("◐"),tag:Y,message:`${s.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
71
- `,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!W0()){let j=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:s.green("✓"),tag:j,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 $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new fX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(W0())throw Error("createReadStream is not supported in browser environments");if(!fU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return zz(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Kw.isBuffer($)?$:Kw.from($,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),B=wq("aes-256-gcm",Y,X);return B.setAuthTag(J),Kw.concat([B.update(U),B.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!W0()){let J=$.split(`
71
+ `,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!W0()){let j=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:s.green("✓"),tag:j,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 $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new fX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(W0())throw Error("createReadStream is not supported in browser environments");if(!fU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Gz(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Kw.isBuffer($)?$:Kw.from($,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),B=Yq("aes-256-gcm",Y,X);return B.setAuthTag(J),Kw.concat([B.update(U),B.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!W0()){let J=$.split(`
72
72
  `),U=Math.max(...J.map((z)=>z.length))+2,B=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,j=J.map((z)=>{let G=" ".repeat(U-z.length-2);return`│ ${z}${G} │`});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(B)})),j.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(W),showTimestamp:!1}))}else if(!W0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let X=`${A} ${this.environment}.INFO: [BOX] ${$}
73
73
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(W0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${s.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();_0.stdin.removeListener("data",Y);try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!1)}catch{}_0.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!0)}catch{}_0.stdin.resume(),_0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let X=/%([sdijfo%])/g,J=0;if(Y=$.replace(X,(U,B)=>{if(B==="%")return"%";if(J>=w.length)return U;let W=w[J++];switch(B){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<w.length)Y+=` ${w.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?s.gray(this.formatTag(this.name)):"",J=s.blue("◐");console.error(`${J} ${X} ${s.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
74
74
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress($,w=""){if(!this.enabled||!this.fancy||W0()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,X)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,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;_0.stdout.write(`${"\r".padEnd(_0.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()||!_0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=s.green("━".repeat(A)),U=s.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=w||Y===100?s.green("✓"):s.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${s.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=_0.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,_0.stdout.write($.lastRenderedLine),w)_0.stdout.write(`
75
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||W0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await lA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=F1(this.config.logDirectory,A);if($.before)try{if((await K1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await nA(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(w){console.error("Error during log clearing process:",w)}}}function UX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let A=[...w];for(let X of $)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)=>RX(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!p(w)||!p($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(p(X)&&p(Y[A]))Y[A]=UX(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((B)=>p(B)&&("name"in B)&&B.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((B)=>p(B)&&("path"in B)&&B.path===U.path))J.push(U)}else if(!J.some((B)=>RX(B,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 UW($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:UX($,w);if(Array.isArray($))return Y==="replace"?w:UX($,w);if(!p(w)||!p($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[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]=UX(U,J);else if(p(J)&&p(U))A[X]=UW(U,J,Y);else A[X]=J}return A}function RX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!RX($[Y],w[Y]))return!1;return!0}if(p($)&&p(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!RX($[X],w[X]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function AX($,w,Y="replace"){if(!W2($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return UW(w,X,Y)}catch{return null}}catch{return null}}function lq($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${G.map(K).join("_")}`,T=`${A}_${G.map((q)=>q.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${F} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let q=fY.env[F]||fY.env[T];if(q!==void 0){if(Y)Z0.info(`Using environment variable ${q?F:T} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(q);else if(typeof z==="boolean")W[j]=q.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(q);if(Array.isArray(E))W[j]=E;else W[j]=q.split(",").map((f)=>f.trim())}catch{W[j]=q.split(",").map((E)=>E.trim())}else W[j]=q}}}return W}return J(X)}async function nq({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?lq($,X,J):X,j=Y||fY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)Z0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),K=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],q=Array.from(new Set([j,i0(j,"config"),i0(j,".config"),A?i0(j,A):void 0].filter(Boolean)));for(let E of q){if(J)Z0.info(`Searching for configuration in: ${E}`);let f=[i0(j,"config"),i0(j,".config")].concat(A?[i0(j,A)]:[]).includes(E)?[...G,...K,...F,...T]:[...K,...G,...T,...F];for(let M of f)for(let Q of z){let V=i0(E,`${M}${Q}`),H=await AX(V,W,B);if(H!==null){if(J)Z0.success(`Configuration loaded from: ${V}`);return H}}}if($){let E=i0(EU(),".config",$),f=["config",`${$}.config`];if(w)f.push(`${w}.config`);if(J)Z0.info(`Checking user config directory: ${E}`);for(let M of f)for(let Q of z){let V=i0(E,`${M}${Q}`),H=await AX(V,W,B);if(H!==null){if(J)Z0.success(`Configuration loaded from user config directory: ${V}`);return H}}}if($){let E=i0(EU(),".config"),f=[`.${$}.config`];if(w)f.push(`.${w}.config`);if(J)Z0.info(`Checking user config directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=i0(E,`${M}${Q}`),H=await AX(V,W,B);if(H!==null){if(J)Z0.success(`Configuration loaded from user config directory dotfile: ${V}`);return H}}}if($){let E=EU(),f=[`.${$}.config`,`.${$}`];if(w)f.push(`.${w}.config`),f.push(`.${w}`);if(J)Z0.info(`Checking user home directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=i0(E,`${M}${Q}`),H=await AX(V,W,B);if(H!==null){if(J)Z0.success(`Configuration loaded from user home directory: ${V}`);return H}}}try{let E=i0(j,"package.json");if(W2(E)){let f=await import(E),M=f[$];if(!M&&w){if(M=f[w],M&&J)Z0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)Z0.success(`Configuration loaded from package.json: ${M===f[$]?$:w}`);return UW(W,M,B)}catch(Q){if(J)Z0.warn("Failed to merge package.json config:",Q)}}}catch(E){if(J)Z0.warn("Failed to load package.json:",E)}if(J)Z0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function pq($,w={}){let Y=FX.cwd();while(Y.includes("storage"))Y=Bz(Y,"..");let A=Bz(Y,$||"");if(w?.relative)return sN(FX.cwd(),A);return A}async function rq(){try{let $=await nq({name:"clarity",alias:"logging",defaultConfig:jX,cwd:FX.cwd()});return{...jX,...$||{}}}catch{return jX}}function E0(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function tq(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n$<"u"){let $=n$.type;if($==="renderer"||$==="worker")return!1;return!!(n$.versions&&(n$.versions.node||n$.versions.bun))}return!1}class F2{async format($){let w=await tq(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:T1.pid,hostname:w(),environment:T1.env.NODE_ENV||"development",platform:T1.platform,version:T1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:T1.env.NODE_ENV||T1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class MX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...gU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new F2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...zX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...zX};return{...zX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:gU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Gq(this.config.logDirectory,fz.F_OK|fz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Kq(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 B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:m$.from($);try{if(!pA(this.currentLogFile))await VU(this.currentLogFile,"",{mode:420});if(A=Hz(this.currentLogFile,"a",420),zq(A,B,{flag:"a"}),Tz(A),A!==void 0)IU(A),A=void 0;if((await q1(this.currentLogFile)).size===0){if(await VU(this.currentLogFile,B,{flag:"w",mode:420}),(await q1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((K)=>setTimeout(K,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{IU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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 $=new Date().toISOString().split("T")[0];return E1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.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 MU(16).toString("hex")}generateKey(){return MU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=MU(16),A=Wq("aes-256-gcm",w,Y),X=m$.isBuffer($)?$:m$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=m$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Mz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(m$.from(m$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let $=await q1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await rA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await q1(Y).catch(()=>null))try{if(await Rz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await tA(B)}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 VU(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 q1(Y).catch(()=>null))await Rz(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await rA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await tA(E1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=Ez($),A=jq(w),X=Mz();await qq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),pA(this.currentLogFile))try{let $=Hz(this.currentLogFile,"r+");Tz($),IU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await rA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await tA(E1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?v.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let $=typeof l.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=l.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${v.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),w}supportsHyperlinks(){if(E0())return!1;let $=l.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=l.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(Fq(w)||w.startsWith("./")||w.startsWith("../"))w=Nq(w);else return null;return pA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":V2[$],K=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:v.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:v.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
75
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||W0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await lA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=N1(this.config.logDirectory,A);if($.before)try{if((await F1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await nA(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(w){console.error("Error during log clearing process:",w)}}}function UX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let A=[...w];for(let X of $)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)=>RX(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!p(w)||!p($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(p(X)&&p(Y[A]))Y[A]=UX(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((B)=>p(B)&&("name"in B)&&B.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((B)=>p(B)&&("path"in B)&&B.path===U.path))J.push(U)}else if(!J.some((B)=>RX(B,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 UW($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:UX($,w);if(Array.isArray($))return Y==="replace"?w:UX($,w);if(!p(w)||!p($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[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]=UX(U,J);else if(p(J)&&p(U))A[X]=UW(U,J,Y);else A[X]=J}return A}function RX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!RX($[Y],w[Y]))return!1;return!0}if(p($)&&p(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!RX($[X],w[X]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function AX($,w,Y="replace"){if(!B2($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return UW(w,X,Y)}catch{return null}}catch{return null}}function nq($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${G.map(K).join("_")}`,T=`${A}_${G.map((q)=>q.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${F} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let q=fY.env[F]||fY.env[T];if(q!==void 0){if(Y)Z0.info(`Using environment variable ${q?F:T} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(q);else if(typeof z==="boolean")W[j]=q.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(q);if(Array.isArray(E))W[j]=E;else W[j]=q.split(",").map((f)=>f.trim())}catch{W[j]=q.split(",").map((E)=>E.trim())}else W[j]=q}}}return W}return J(X)}async function pq({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?nq($,X,J):X,j=Y||fY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)Z0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),K=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],q=Array.from(new Set([j,i0(j,"config"),i0(j,".config"),A?i0(j,A):void 0].filter(Boolean)));for(let E of q){if(J)Z0.info(`Searching for configuration in: ${E}`);let f=[i0(j,"config"),i0(j,".config")].concat(A?[i0(j,A)]:[]).includes(E)?[...G,...K,...F,...T]:[...K,...G,...T,...F];for(let M of f)for(let Q of z){let V=i0(E,`${M}${Q}`),H=await AX(V,W,B);if(H!==null){if(J)Z0.success(`Configuration loaded from: ${V}`);return H}}}if($){let E=i0(EU(),".config",$),f=["config",`${$}.config`];if(w)f.push(`${w}.config`);if(J)Z0.info(`Checking user config directory: ${E}`);for(let M of f)for(let Q of z){let V=i0(E,`${M}${Q}`),H=await AX(V,W,B);if(H!==null){if(J)Z0.success(`Configuration loaded from user config directory: ${V}`);return H}}}if($){let E=i0(EU(),".config"),f=[`.${$}.config`];if(w)f.push(`.${w}.config`);if(J)Z0.info(`Checking user config directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=i0(E,`${M}${Q}`),H=await AX(V,W,B);if(H!==null){if(J)Z0.success(`Configuration loaded from user config directory dotfile: ${V}`);return H}}}if($){let E=EU(),f=[`.${$}.config`,`.${$}`];if(w)f.push(`.${w}.config`),f.push(`.${w}`);if(J)Z0.info(`Checking user home directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=i0(E,`${M}${Q}`),H=await AX(V,W,B);if(H!==null){if(J)Z0.success(`Configuration loaded from user home directory: ${V}`);return H}}}try{let E=i0(j,"package.json");if(B2(E)){let f=await import(E),M=f[$];if(!M&&w){if(M=f[w],M&&J)Z0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)Z0.success(`Configuration loaded from package.json: ${M===f[$]?$:w}`);return UW(W,M,B)}catch(Q){if(J)Z0.warn("Failed to merge package.json config:",Q)}}}catch(E){if(J)Z0.warn("Failed to load package.json:",E)}if(J)Z0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function rq($,w={}){let Y=FX.cwd();while(Y.includes("storage"))Y=jz(Y,"..");let A=jz(Y,$||"");if(w?.relative)return oN(FX.cwd(),A);return A}async function tq(){try{let $=await pq({name:"clarity",alias:"logging",defaultConfig:jX,cwd:FX.cwd()});return{...jX,...$||{}}}catch{return jX}}function E0(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function aq(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n$<"u"){let $=n$.type;if($==="renderer"||$==="worker")return!1;return!!(n$.versions&&(n$.versions.node||n$.versions.bun))}return!1}class N2{async format($){let w=await aq(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:H1.pid,hostname:w(),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 MX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...gU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new N2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...zX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...zX};return{...zX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:gU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Kq(this.config.logDirectory,Rz.F_OK|Rz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Fq(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 B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:m$.from($);try{if(!pA(this.currentLogFile))await VU(this.currentLogFile,"",{mode:420});if(A=fz(this.currentLogFile,"a",420),Gq(A,B,{flag:"a"}),Hz(A),A!==void 0)IU(A),A=void 0;if((await E1(this.currentLogFile)).size===0){if(await VU(this.currentLogFile,B,{flag:"w",mode:420}),(await E1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((K)=>setTimeout(K,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{IU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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 $=new Date().toISOString().split("T")[0];return T1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.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 MU(16).toString("hex")}generateKey(){return MU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=MU(16),A=Bq("aes-256-gcm",w,Y),X=m$.isBuffer($)?$:m$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=m$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Iz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(m$.from(m$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let $=await E1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await rA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await E1(Y).catch(()=>null))try{if(await Mz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await tA(B)}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 VU(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 E1(Y).catch(()=>null))await Mz(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await rA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await tA(T1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=Tz($),A=zq(w),X=Iz();await Eq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),pA(this.currentLogFile))try{let $=fz(this.currentLogFile,"r+");Hz($),IU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await rA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await tA(T1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?v.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let $=typeof l.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=l.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${v.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),w}supportsHyperlinks(){if(E0())return!1;let $=l.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=l.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(Nq(w)||w.startsWith("./")||w.startsWith("../"))w=qq(w);else return null;return pA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":C2[$],K=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:v.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:v.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
76
76
  `);for(let q of T)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:v.gray(` ${q}`),level:$,showTimestamp:!1}))}break}}else if(!E0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
77
77
  `;if(B)z+=`${B}
78
78
  `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}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,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!E0()&&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()&&!E0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!E0()&&l.stdout.isTTY)l.stdout.write(`
79
79
  `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!E0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=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($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
80
- `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":v.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E0())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 $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new MX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(E0())throw Error("createReadStream is not supported in browser environments");if(!pA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Ez(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=m$.isBuffer($)?$:m$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=Bq("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=m$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
80
+ `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":v.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E0())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 $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new MX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(E0())throw Error("createReadStream is not supported in browser environments");if(!pA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Tz(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=m$.isBuffer($)?$:m$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=jq("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=m$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
81
81
  `),W=Math.max(...B.map((K)=>K.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((K)=>{return this.formatConsoleMessage({timestamp:Y,message:v.cyan(K),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(j),showTimestamp:!1})),G.forEach((K)=>console.error(K)),console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(z),showTimestamp:!1}))}else if(!E0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
82
82
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(E0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${v.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,B=0;if(Y=$.replace(U,(W,j)=>{if(j==="%")return"%";if(B>=w.length)return W;let z=w[B++];switch(j){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return W}}),B<w.length)Y+=` ${w.slice(B).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?v.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${v.blue("◐")} `;console.error(`${B}${U} ${v.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
83
83
  `.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($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=v.green("━".repeat(A)),U=v.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?v.green("✓"):v.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=l.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,l.stdout.write($.lastRenderedLine),w)l.stdout.write(`
84
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||E0()||!l.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(E0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await rA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=E1(this.config.logDirectory,A);if($.before)try{if((await q1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await tA(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(w){console.error("Error during log clearing process:",w)}}}async function N2($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function q2($){return $ instanceof s0}function aq($){return $ instanceof IX}function sq($){if(q2($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}class ZX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return VY.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=aA.env[W]||(j?aA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=aA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof VX)throw G;throw Nw.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Nw.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(aA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
84
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||E0()||!l.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(E0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await rA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=T1(this.config.logDirectory,A);if($.before)try{if((await E1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await tA(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(w){console.error("Error during log clearing process:",w)}}}async function q2($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function E2($){return $ instanceof s0}function sq($){return $ instanceof IX}function oq($){if(E2($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}class ZX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return VY.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=aA.env[W]||(j?aA.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=aA.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof VX)throw G;throw Nw.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Nw.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(aA.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
85
85
 
86
86
  `;for(let A of $)Y+=`${A.key}
87
87
  `,Y+=` Type: ${A.type}
@@ -93,25 +93,25 @@ export type ConfigOf = Config
93
93
  `;Y+=`| Variable | Type | Description | Example |
94
94
  `,Y+=`|----------|------|-------------|----------|
95
95
  `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
96
- `;return Y}}function oq($,w){let Y=R2("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function E2($,w,Y={}){return T2($,w,Y,new WeakMap)}function T2($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return H2($,w,X,A);if(!W$(w)||!W$($))return w;return YE($,w,Y,A)}function H2($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return eq($,w);case"smart":return $E($,w,A);default:return w}return w}function eq($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>iU(X,A)))Y.push(A);return Y}function $E($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(W$(w[0])&&W$($[0]))return wE($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function wE($,w,Y){let A=[...w];for(let X of $){if(!W$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((W)=>W$(W)&&(B in W)&&W[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function YE($,w,Y,A){let X=w;if(W$(X)&&A.has(X))return A.get(X);let J={...$};if(W$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(W$(B)&&W$(W))J[U]=T2(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=H2(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function WW($,w,Y="replace"){return E2($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function iU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!iU($[Y],w[Y]))return!1;return!0}if(W$($)&&W$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!iU($[X],w[X]))return!1}return!0}return!1}function W$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class hX{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:B=!1}=Y;if(X){let j=I1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!sA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new RY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new RY($,Error("Configuration must export a valid object"),"unknown");let T={config:WW(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)I1.setWithFileCheck("file",T,$,J);return T}catch(j){throw j instanceof Error?Nw.configLoad($,j):Nw.configLoad($,Error(String(j)))}};if(U)return VY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(CU(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return N2(async()=>{return sA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!sA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=CU($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=CU($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!sA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class BW{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await VY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!Eq(w))throw new MY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new MY(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Q2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class jW{fileLoader=new hX;envProcessor=new ZX;validator=new BW;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)q$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw q$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||Dw.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(m0(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw Nw.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?EY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)q$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)q$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?EY($,Y,X):Y,B=[m0(G1(),".config",$),m0(G1(),".config"),G1()];for(let W of B){if(X)q$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)q$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?EY($,A,J):A;try{let W=m0(Y,"package.json");if(!vU(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)q$.success(`Configuration loaded from package.json: ${G}`);return{config:WW(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)q$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:EY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 Nw.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return I1.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);I1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,m0($,"config"),m0($,".config"),w?m0($,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(m0(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[m0(G1(),".config",$),m0(G1(),".config"),G1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function Sz($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||Y}async function AE($){return t$.loadConfig({...$,__strictErrorHandling:!0})}async function f2($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await t$.loadConfig($);else A=await t$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)q$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await t$.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function XE($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await t$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Sz(Y)))return(await t$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await t$.loadConfig({...$,cwd:$.cwd||Dw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&Sz(w)))return(await t$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function JE($,w,Y="replace"){let A=new hX;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function EY($,w,Y=!1){let A=new ZX,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=Dw.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function UE($){let w=m0(Dw.cwd(),$.configDir),Y=m0(Dw.cwd(),$.generatedDir),A=m0(Y,"config-types.ts");if(!vU(Wz(A)))pN(Wz(A),{recursive:!0,mode:511});let X=vU(w)?rN(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${xE}
96
+ `;return Y}}function eq($,w){let Y=M2("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function T2($,w,Y={}){return H2($,w,Y,new WeakMap)}function H2($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return f2($,w,X,A);if(!W$(w)||!W$($))return w;return AE($,w,Y,A)}function f2($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return $E($,w);case"smart":return wE($,w,A);default:return w}return w}function $E($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>iU(X,A)))Y.push(A);return Y}function wE($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(W$(w[0])&&W$($[0]))return YE($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function YE($,w,Y){let A=[...w];for(let X of $){if(!W$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((W)=>W$(W)&&(B in W)&&W[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function AE($,w,Y,A){let X=w;if(W$(X)&&A.has(X))return A.get(X);let J={...$};if(W$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(W$(B)&&W$(W))J[U]=H2(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=f2(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function WW($,w,Y="replace"){return T2($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function iU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!iU($[Y],w[Y]))return!1;return!0}if(W$($)&&W$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!iU($[X],w[X]))return!1}return!0}return!1}function W$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class hX{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:B=!1}=Y;if(X){let j=V1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!sA($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new RY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new RY($,Error("Configuration must export a valid object"),"unknown");let T={config:WW(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)V1.setWithFileCheck("file",T,$,J);return T}catch(j){throw j instanceof Error?Nw.configLoad($,j):Nw.configLoad($,Error(String(j)))}};if(U)return VY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(CU(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return q2(async()=>{return sA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!sA($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=CU($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=CU($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!sA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class BW{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await VY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!Tq(w))throw new MY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new MY(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:y2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class jW{fileLoader=new hX;envProcessor=new ZX;validator=new BW;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)q$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw q$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||kw.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(m0(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw Nw.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?EY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)q$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)q$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?EY($,Y,X):Y,B=[m0(K1(),".config",$),m0(K1(),".config"),K1()];for(let W of B){if(X)q$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)q$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?EY($,A,J):A;try{let W=m0(Y,"package.json");if(!vU(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)q$.success(`Configuration loaded from package.json: ${G}`);return{config:WW(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)q$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:EY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 Nw.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return V1.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);V1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,m0($,"config"),m0($,".config"),w?m0($,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(m0(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[m0(K1(),".config",$),m0(K1(),".config"),K1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function Zz($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||Y}async function XE($){return t$.loadConfig({...$,__strictErrorHandling:!0})}async function R2($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await t$.loadConfig($);else A=await t$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)q$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await t$.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function JE($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await t$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Zz(Y)))return(await t$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await t$.loadConfig({...$,cwd:$.cwd||kw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&Zz(w)))return(await t$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function UE($,w,Y="replace"){let A=new hX;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function EY($,w,Y=!1){let A=new ZX,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=kw.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function WE($){let w=m0(kw.cwd(),$.configDir),Y=m0(kw.cwd(),$.generatedDir),A=m0(Y,"config-types.ts");if(!vU(Bz(A)))rN(Bz(A),{recursive:!0,mode:511});let X=vU(w)?tN(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${PE}
97
97
  export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
98
- `;tN(A,J,{mode:438})}function WE($){let w=null,Y=null,A=()=>{if(!Y)Y=f2($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)q$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in $?$.defaultConfig:{};return w=X,A(),new Proxy({},{get(J,U){if(w)return w[U];let B=X[U];return A(),B},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,B){if(!w)w={...X};return w[U]=B,!0}})}function BE($){let w=Iz(fq.cwd(),$?.configDir||"./config");function Y(){if(!Tq(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=Hq(w).filter((W)=>X.has(QU(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:j}of U){let z=QU(j).toLowerCase(),G=B.get(W);if(!G){B.set(W,j);continue}let K=QU(G).toLowerCase();if(J.indexOf(z)<J.indexOf(K))B.set(W,j)}return Array.from(B.entries()).map(([W,j])=>({base:W,file:j})).sort((W,j)=>W.base.localeCompare(j.base))}function A(){let X=Y(),J=X.map((W)=>W.base),U=J.length?J.map((W)=>`'${W}'`).join(" | "):"string",B=X.length?`{
99
- ${X.map((W)=>{let j=Iz(w,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${j}').default`}).join(`,
98
+ `;aN(A,J,{mode:438})}function BE($){let w=null,Y=null,A=()=>{if(!Y)Y=R2($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)q$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in $?$.defaultConfig:{};return w=X,A(),new Proxy({},{get(J,U){if(w)return w[U];let B=X[U];return A(),B},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,B){if(!w)w={...X};return w[U]=B,!0}})}function jE($){let w=Vz(Rq.cwd(),$?.configDir||"./config");function Y(){if(!Hq(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=fq(w).filter((W)=>X.has(QU(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:j}of U){let z=QU(j).toLowerCase(),G=B.get(W);if(!G){B.set(W,j);continue}let K=QU(G).toLowerCase();if(J.indexOf(z)<J.indexOf(K))B.set(W,j)}return Array.from(B.entries()).map(([W,j])=>({base:W,file:j})).sort((W,j)=>W.base.localeCompare(j.base))}function A(){let X=Y(),J=X.map((W)=>W.base),U=J.length?J.map((W)=>`'${W}'`).join(" | "):"string",B=X.length?`{
99
+ ${X.map((W)=>{let j=Vz(w,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${j}').default`}).join(`,
100
100
  `)}
101
101
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
102
102
  export type ConfigByName = ${B}
103
103
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
104
104
  export type ConfigOf = Config
105
- `}return{name:"bunfig-plugin",setup(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 bE($,w={}){let Y=EX.cwd();while(Y.includes("storage"))Y=Vz(Y,"..");let A=Vz(Y,$||"");if(w?.relative)return Mq(EX.cwd(),A);return A}function H0(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vE(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p$<"u"){let $=p$.type;if($==="renderer"||$==="worker")return!1;return!!(p$.versions&&(p$.versions.node||p$.versions.bun))}return!1}class _2{async format($){let w=await vE(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:R1.pid,hostname:w(),environment:R1.env.NODE_ENV||"development",platform:R1.platform,version:R1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:R1.env.NODE_ENV||R1.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=$,this.config={...CX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new _2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...DU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...DU};return{...DU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:CX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await yq(this.config.logDirectory,Lz.F_OK|Lz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Lq(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 B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:g$.from($);try{if(!oA(this.currentLogFile))await OU(this.currentLogFile,"",{mode:420});if(A=yz(this.currentLogFile,"a",420),Qq(A,B,{flag:"a"}),Qz(A),A!==void 0)LU(A),A=void 0;if((await H1(this.currentLogFile)).size===0){if(await OU(this.currentLogFile,B,{flag:"w",mode:420}),(await H1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((K)=>setTimeout(K,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{LU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return f1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return f1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return f1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.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 yU(16).toString("hex")}generateKey(){return yU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=yU(16),A=Iq("aes-256-gcm",w,Y),X=g$.isBuffer($)?$:g$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=g$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=_z(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(g$.from(g$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let $=await H1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await eA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await H1(Y).catch(()=>null))try{if(await Oz(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await $X(B)}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 OU(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 Oz(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await eA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await $X(f1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=Cz($),A=Cq(w),X=_z();await Sq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),oA(this.currentLogFile))try{let $=yz(this.currentLogFile,"r+");Qz($),LU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await eA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await $X(f1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?m.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let $=typeof n.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=n.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${m.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),w}supportsHyperlinks(){if(H0())return!1;let $=n.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=n.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(Oq(w)||w.startsWith("./")||w.startsWith("../"))w=_q(w);else return null;return oA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":dE[$],K=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:m.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:m.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
105
+ `}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 uE($,w={}){let Y=EX.cwd();while(Y.includes("storage"))Y=Cz(Y,"..");let A=Cz(Y,$||"");if(w?.relative)return Iq(EX.cwd(),A);return A}function H0(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cE(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p$<"u"){let $=p$.type;if($==="renderer"||$==="worker")return!1;return!!(p$.versions&&(p$.versions.node||p$.versions.bun))}return!1}class S2{async format($){let w=await cE(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:M1.pid,hostname:w(),environment:M1.env.NODE_ENV||"development",platform:M1.platform,version:M1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:M1.env.NODE_ENV||M1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class DX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...CX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new S2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...kU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...kU};return{...kU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:CX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Lq(this.config.logDirectory,Oz.F_OK|Oz.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await Oq(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 B=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:g$.from($);try{if(!oA(this.currentLogFile))await OU(this.currentLogFile,"",{mode:420});if(A=Lz(this.currentLogFile,"a",420),yq(A,B,{flag:"a"}),yz(A),A!==void 0)LU(A),A=void 0;if((await f1(this.currentLogFile)).size===0){if(await OU(this.currentLogFile,B,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(W){let j=W;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=U*2**X;await new Promise((K)=>setTimeout(K,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(A!==void 0)try{LU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(B){if(X===J-1){let j=B,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),B}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return R1(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 R1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return R1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,B])=>B.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.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 yU(16).toString("hex")}generateKey(){return yU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=yU(16),A=Vq("aes-256-gcm",w,Y),X=g$.isBuffer($)?$:g$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=g$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Sz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(g$.from(g$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let $=await f1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await eA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await f1(Y).catch(()=>null))try{if(await _z(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await $X(B)}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 OU(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 _z(Y,J)}if(this.currentLogFile=A,w.maxFiles){let X=(await eA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await $X(R1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=Qz($),A=Qq(w),X=Sz();await Zq(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),oA(this.currentLogFile))try{let $=Lz(this.currentLogFile,"r+");yz($),LU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await eA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await $X(R1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?m.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let $=typeof n.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=n.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${m.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),w}supportsHyperlinks(){if(H0())return!1;let $=n.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=n.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(_q(w)||w.startsWith("./")||w.startsWith("../"))w=Sq(w);else return null;return oA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":lE[$],K=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:m.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:m.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
106
106
  `);for(let q of T)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:m.gray(` ${q}`),level:$,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
107
107
  `;if(B)z+=`${B}
108
108
  `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}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,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&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()&&!H0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!H0()&&n.stdout.isTTY)n.stdout.write(`
109
109
  `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=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($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
110
- `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":m.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!H0())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 $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new kX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(H0())throw Error("createReadStream is not supported in browser environments");if(!oA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Cz(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=g$.isBuffer($)?$:g$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=Vq("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=g$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
110
+ `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":m.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!H0())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 $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new DX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(H0())throw Error("createReadStream is not supported in browser environments");if(!oA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Qz(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=g$.isBuffer($)?$:g$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=Cq("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=g$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
111
111
  `),W=Math.max(...B.map((K)=>K.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((K)=>{return this.formatConsoleMessage({timestamp:Y,message:m.cyan(K),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(j),showTimestamp:!1})),G.forEach((K)=>console.error(K)),console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(z),showTimestamp:!1}))}else if(!H0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
112
112
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(H0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${m.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,B=0;if(Y=$.replace(U,(W,j)=>{if(j==="%")return"%";if(B>=w.length)return W;let z=w[B++];switch(j){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return W}}),B<w.length)Y+=` ${w.slice(B).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)):"",B=this.options.showIcons===!1?"":`${m.blue("◐")} `;console.error(`${B}${U} ${m.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
113
113
  `.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($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=m.green("━".repeat(A)),U=m.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?m.green("✓"):m.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=n.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,n.stdout.write($.lastRenderedLine),w)n.stdout.write(`
114
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||H0()||!n.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await eA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=f1(this.config.logDirectory,A);if($.before)try{if((await H1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await $X(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(w){console.error("Error during log clearing process:",w)}}}async function lE($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class GW{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return YW.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=wX.env[W]||(j?wX.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=wX.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof zW)throw G;throw V1.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw V1.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(wX.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
114
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||H0()||!n.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await eA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=R1(this.config.logDirectory,A);if($.before)try{if((await f1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await $X(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(w){console.error("Error during log clearing process:",w)}}}async function nE($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class GW{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return YW.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=wX.env[W]||(j?wX.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=wX.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof zW)throw G;throw C1.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw C1.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(wX.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
115
115
 
116
116
  `;for(let A of $)Y+=`${A.key}
117
117
  `,Y+=` Type: ${A.type}
@@ -123,32 +123,32 @@ export type ConfigOf = Config
123
123
  `;Y+=`| Variable | Type | Description | Example |
124
124
  `,Y+=`|----------|------|-------------|----------|
125
125
  `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
126
- `;return Y}}function nE($,w,Y={}){return b2($,w,Y,new WeakMap)}function b2($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return u2($,w,X,A);if(!B$(w)||!B$($))return w;return aE($,w,Y,A)}function u2($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return pE($,w);case"smart":return rE($,w,A);default:return w}return w}function pE($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>aU(X,A)))Y.push(A);return Y}function rE($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(B$(w[0])&&B$($[0]))return tE($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function tE($,w,Y){let A=[...w];for(let X of $){if(!B$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((W)=>B$(W)&&(B in W)&&W[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function aE($,w,Y,A){let X=w;if(B$(X)&&A.has(X))return A.get(X);let J={...$};if(B$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(B$(B)&&B$(W))J[U]=b2(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=u2(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function v2($,w,Y="replace"){return nE($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function aU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!aU($[Y],w[Y]))return!1;return!0}if(B$($)&&B$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!aU($[X],w[X]))return!1}return!0}return!1}function B$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class c2{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:B=!1}=Y;if(X){let j=TX.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!YX($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new QX($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new QX($,Error("Configuration must export a valid object"),"unknown");let T={config:v2(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)TX.setWithFileCheck("file",T,$,J);return T}catch(j){throw j instanceof Error?V1.configLoad($,j):V1.configLoad($,Error(String(j)))}};if(U)return YW.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(_U(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return lE(async()=>{return YX($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!YX($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=_U($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=_U($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!YX($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class i2{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await YW.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!Zq(w))throw new yX(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new yX(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:sE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function oE($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class m2{fileLoader=new c2;envProcessor=new GW;validator=new i2;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)d$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw d$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||SX.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(U$(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw V1.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${oE(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?XX($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)d$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)d$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?XX($,Y,X):Y,B=[U$(z1(),".config",$),U$(z1(),".config"),z1()];for(let W of B){if(X)d$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)d$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?XX($,A,J):A;try{let W=U$(Y,"package.json");if(!lN(W))return null;let j={};try{j=JSON.parse(nN(W,"utf8"))}catch(K){if(J)d$.warn("Failed to parse package.json:",[K instanceof Error?K:Error(String(K))]);return null}let z=j[$],G=$;if(!z&&w){let K=Array.isArray(w)?w:[w];for(let F of K){if(!F)continue;if(j[F]){z=j[F],G=F;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)d$.success(`Configuration loaded from package.json: ${G}`);return{config:v2(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)d$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:XX($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 V1.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return TX.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);TX.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,U$($,"config"),U$($,".config"),w?U$($,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(U$(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[U$(z1(),".config",$),U$(z1(),".config"),z1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function XX($,w,Y=!1){let A=new GW,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=SX.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function l2($){return sU.readFileSync($,"utf8")}function oU($,w){let Y=[];function A(X){let J;try{J=sU.readdirSync(X)}catch{return}for(let U of J){let B=N$.join(X,U);try{if(sU.statSync(B).isDirectory())A(B);else if(U===w)Y.push(X)}catch{continue}}}return A($),Y}function L($,w,Y){if(Y||z0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function n2(){return d2.env.SUDO_PASSWORD}function JT($){let w=$.toLowerCase();return AT.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function LX($){if(Array.isArray($))return $.map((Y)=>LX(Y));if(typeof $==="string")return XT.test($)?gz:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(JT(Y)){w[Y]=gz;continue}w[Y]=LX(A)}return w}function DX($){return JSON.stringify(LX($))}function UT($){let w=n2();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let Y=w.replace(/'/g,"'\\''"),A=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function Fw($,w={}){let Y=UT($);try{let{stdout:A,stderr:X}=await YT(Y,{cwd:w.cwd||d2.cwd(),timeout:w.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${$}
127
- Error: ${A.message}`);throw X.stack=A.stack,X}}function p2($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function KW($){let w=N$.join($T.homedir(),".stacks","ssl"),Y=$.basePath&&$.basePath.trim()!==""?$.basePath:z0.basePath&&z0.basePath.trim()!==""?z0.basePath:w,A=$.certPath?N$.isAbsolute($.certPath)?$.certPath:N$.join(Y,$.certPath):N$.join(Y,z0.certPath),X=$.keyPath?N$.isAbsolute($.keyPath)?$.keyPath:N$.join(Y,$.keyPath):N$.join(Y,z0.keyPath),J=$.caCertPath?N$.isAbsolute($.caCertPath)?$.caCertPath:N$.join(Y,$.caCertPath):N$.join(Y,z0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function r2($){let w=[],Y=new Set;if($.domain)Y.add($.domain);if($.domains?.length)$.domains.forEach((A)=>Y.add(A));for(let A of Y)w.push({type:2,value:A});if($.altNameIPs?.length)for(let A of $.altNameIPs)w.push({type:7,ip:A});if($.altNameURIs?.length)for(let A of $.altNameURIs)w.push({type:6,value:A});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return L(_.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function FW($){let w=$.notBeforeDays??E$.DEFAULT_NOT_BEFORE_DAYS,Y=$.validityDays??($.validityYears?$.validityYears*365:E$.DEFAULT_VALIDITY_DAYS);L(_.CERT,"Calculating certificate validity dates",$.verbose);let A=new Date(Date.now()-86400*w*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),L(_.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,$.verbose),{notBefore:A,notAfter:X}}function TY($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function e0($,w){let Y=TY(w.length);return Buffer.concat([Buffer.from([$]),Y,w])}function IY($){let w=$.split(".").map(Number),Y=[];Y.push(40*w[0]+w[1]);for(let A=2;A<w.length;A++){let X=w[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return e0(T$.OID,Buffer.from(Y))}function eU($){let w;if(typeof $==="bigint"){let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else w=$;if(w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return e0(T$.INTEGER,w)}function t2($,w=0){return e0(T$.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function a2($){return e0(T$.OCTET_STRING,$)}function o0(...$){return e0(T$.SEQUENCE,Buffer.concat($))}function WT(...$){return e0(T$.SET,Buffer.concat($))}function BT($){return e0(T$.PRINTABLE_STRING,Buffer.from($,"ascii"))}function jT($){return e0(T$.UTF8_STRING,Buffer.from($,"utf8"))}function zT(){return Buffer.from([T$.NULL,0])}function dz($,w,Y=!0){let A=160|$|(Y?0:0),X=TY(w.length);return Buffer.concat([Buffer.from([A]),X,w])}function lz($){let w=$.getUTCFullYear();if(w>=2050){let Y=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return e0(T$.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=(w%100).toString().padStart(2,"0"),A=($.getUTCMonth()+1).toString().padStart(2,"0"),X=$.getUTCDate().toString().padStart(2,"0"),J=$.getUTCHours().toString().padStart(2,"0"),U=$.getUTCMinutes().toString().padStart(2,"0"),B=$.getUTCSeconds().toString().padStart(2,"0"),W=`${Y}${A}${X}${J}${U}${B}Z`;return e0(T$.UTC_TIME,Buffer.from(W,"ascii"))}}function GT($,w){return o0(lz($),lz(w))}function nz($){let w=[];for(let Y of $){let A;switch(Y.shortName){case"CN":A=g0.COMMON_NAME;break;case"C":A=g0.COUNTRY;break;case"L":A=g0.LOCALITY;break;case"ST":A=g0.STATE;break;case"O":A=g0.ORGANIZATION;break;case"OU":A=g0.ORGANIZATIONAL_UNIT;break;default:continue}let X=Y.shortName==="C"?BT(Y.value):jT(Y.value),J=o0(IY(A),X);w.push(WT(J))}return o0(...w)}function s2($){return o0(IY($),zT())}function KT($){return $.export({type:"spki",format:"der"})}function FT($){if($.includes(":")){let w=$;if($.includes("::")){let X=$.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],B=8-J.length-U.length,W=Array.from({length:B},()=>"0");w=[...J,...W,...U].join(":")}let Y=w.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(w)}}function NT($){let w=[];for(let Y of $)if(Y.type===2&&Y.value){let A=TY(Y.value.length);w.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=FT(Y.ip),X=TY(A.length);w.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=TY(Y.value.length);w.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return o0(...w)}function qT($,w){if($){if(w!==void 0)return o0(e0(1,Buffer.from([255])),eU(w));return o0(e0(1,Buffer.from([255])))}return o0()}function ET($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let Y=0,A=w;while(A>0&&(A&1)===0)Y++,A>>=1;if(w===0)Y=7;return t2(Buffer.from([w]),Y)}function TT($){let w=[];if($.serverAuth)w.push(IY(g0.SERVER_AUTH));if($.clientAuth)w.push(IY(g0.CLIENT_AUTH));return o0(...w)}function qY($,w,Y){let A=[IY($)];if(w)A.push(e0(1,Buffer.from([255])));return A.push(a2(Y)),o0(...A)}function HT($){let w=[];if(w.push(dz(0,eU(2))),w.push(eU($.serialNumber)),w.push(s2(g0.SHA256_WITH_RSA)),w.push(nz($.issuer)),w.push(GT($.notBefore,$.notAfter)),w.push(nz($.subject)),w.push(KT($.publicKey)),$.extensions){let Y=[];if($.extensions.basicConstraints)Y.push(qY(g0.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,qT($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)Y.push(qY(g0.KEY_USAGE,$.extensions.keyUsage.critical??!0,ET($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)Y.push(qY(g0.EXTENDED_KEY_USAGE,!1,TT($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)Y.push(qY(g0.SUBJECT_ALT_NAME,!1,NT($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)Y.push(qY(g0.SUBJECT_KEY_IDENTIFIER,!1,a2($.extensions.subjectKeyIdentifier)));if(Y.length>0)w.push(dz(3,o0(...Y)))}return o0(...w)}function fT($,w){let Y=C1.createSign("SHA256");Y.update($);let A=Y.sign(w);return o0($,s2(g0.SHA256_WITH_RSA),t2(A))}function RT($,w){let Y=$.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${w}-----
126
+ `;return Y}}function pE($,w,Y={}){return u2($,w,Y,new WeakMap)}function u2($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return v2($,w,X,A);if(!B$(w)||!B$($))return w;return sE($,w,Y,A)}function v2($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return rE($,w);case"smart":return tE($,w,A);default:return w}return w}function rE($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>aU(X,A)))Y.push(A);return Y}function tE($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(B$(w[0])&&B$($[0]))return aE($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function aE($,w,Y){let A=[...w];for(let X of $){if(!B$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((W)=>B$(W)&&(B in W)&&W[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function sE($,w,Y,A){let X=w;if(B$(X)&&A.has(X))return A.get(X);let J={...$};if(B$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(B$(B)&&B$(W))J[U]=u2(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=v2(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function c2($,w,Y="replace"){return pE($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function aU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!aU($[Y],w[Y]))return!1;return!0}if(B$($)&&B$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!aU($[X],w[X]))return!1}return!0}return!1}function B$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class i2{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:B=!1}=Y;if(X){let j=TX.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!YX($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new QX($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new QX($,Error("Configuration must export a valid object"),"unknown");let T={config:c2(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)TX.setWithFileCheck("file",T,$,J);return T}catch(j){throw j instanceof Error?C1.configLoad($,j):C1.configLoad($,Error(String(j)))}};if(U)return YW.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(_U(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)Y.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return nE(async()=>{return YX($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!YX($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=_U($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=_U($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!YX($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class m2{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await YW.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!hq(w))throw new yX(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new yX(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:oE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function eE($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class g2{fileLoader=new i2;envProcessor=new GW;validator=new m2;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)d$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){if(B instanceof Error&&B.name==="ConfigNotFoundError")throw B;let W=Date.now()-w;throw d$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||SX.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(U$(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw C1.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${eE(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?XX($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)d$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)d$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?XX($,Y,X):Y,B=[U$(G1(),".config",$),U$(G1(),".config"),G1()];for(let W of B){if(X)d$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)d$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?XX($,A,J):A;try{let W=U$(Y,"package.json");if(!nN(W))return null;let j={};try{j=JSON.parse(pN(W,"utf8"))}catch(K){if(J)d$.warn("Failed to parse package.json:",[K instanceof Error?K:Error(String(K))]);return null}let z=j[$],G=$;if(!z&&w){let K=Array.isArray(w)?w:[w];for(let F of K){if(!F)continue;if(j[F]){z=j[F],G=F;break}}}if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)d$.success(`Configuration loaded from package.json: ${G}`);return{config:c2(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)d$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:XX($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 C1.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return TX.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);TX.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,U$($,"config"),U$($,".config"),w?U$($,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(U$(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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[U$(G1(),".config",$),U$(G1(),".config"),G1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function XX($,w,Y=!1){let A=new GW,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=SX.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function n2($){return sU.readFileSync($,"utf8")}function oU($,w){let Y=[];function A(X){let J;try{J=sU.readdirSync(X)}catch{return}for(let U of J){let B=N$.join(X,U);try{if(sU.statSync(B).isDirectory())A(B);else if(U===w)Y.push(X)}catch{continue}}}return A($),Y}function L($,w,Y){if(Y||z0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function p2(){return l2.env.SUDO_PASSWORD}function UT($){let w=$.toLowerCase();return XT.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function LX($){if(Array.isArray($))return $.map((Y)=>LX(Y));if(typeof $==="string")return JT.test($)?dz:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(UT(Y)){w[Y]=dz;continue}w[Y]=LX(A)}return w}function kX($){return JSON.stringify(LX($))}function WT($){let w=p2();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let Y=w.replace(/'/g,"'\\''"),A=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function Fw($,w={}){let Y=WT($);try{let{stdout:A,stderr:X}=await AT(Y,{cwd:w.cwd||l2.cwd(),timeout:w.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${$}
127
+ Error: ${A.message}`);throw X.stack=A.stack,X}}function r2($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function KW($){let w=N$.join(wT.homedir(),".stacks","ssl"),Y=$.basePath&&$.basePath.trim()!==""?$.basePath:z0.basePath&&z0.basePath.trim()!==""?z0.basePath:w,A=$.certPath?N$.isAbsolute($.certPath)?$.certPath:N$.join(Y,$.certPath):N$.join(Y,z0.certPath),X=$.keyPath?N$.isAbsolute($.keyPath)?$.keyPath:N$.join(Y,$.keyPath):N$.join(Y,z0.keyPath),J=$.caCertPath?N$.isAbsolute($.caCertPath)?$.caCertPath:N$.join(Y,$.caCertPath):N$.join(Y,z0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function t2($){let w=[],Y=new Set;if($.domain)Y.add($.domain);if($.domains?.length)$.domains.forEach((A)=>Y.add(A));for(let A of Y)w.push({type:2,value:A});if($.altNameIPs?.length)for(let A of $.altNameIPs)w.push({type:7,ip:A});if($.altNameURIs?.length)for(let A of $.altNameURIs)w.push({type:6,value:A});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return L(_.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function FW($){let w=$.notBeforeDays??E$.DEFAULT_NOT_BEFORE_DAYS,Y=$.validityDays??($.validityYears?$.validityYears*365:E$.DEFAULT_VALIDITY_DAYS);L(_.CERT,"Calculating certificate validity dates",$.verbose);let A=new Date(Date.now()-86400*w*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),L(_.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,$.verbose),{notBefore:A,notAfter:X}}function TY($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function e0($,w){let Y=TY(w.length);return Buffer.concat([Buffer.from([$]),Y,w])}function IY($){let w=$.split(".").map(Number),Y=[];Y.push(40*w[0]+w[1]);for(let A=2;A<w.length;A++){let X=w[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return e0(T$.OID,Buffer.from(Y))}function eU($){let w;if(typeof $==="bigint"){let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else w=$;if(w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return e0(T$.INTEGER,w)}function a2($,w=0){return e0(T$.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function s2($){return e0(T$.OCTET_STRING,$)}function o0(...$){return e0(T$.SEQUENCE,Buffer.concat($))}function BT(...$){return e0(T$.SET,Buffer.concat($))}function jT($){return e0(T$.PRINTABLE_STRING,Buffer.from($,"ascii"))}function zT($){return e0(T$.UTF8_STRING,Buffer.from($,"utf8"))}function GT(){return Buffer.from([T$.NULL,0])}function lz($,w,Y=!0){let A=160|$|(Y?0:0),X=TY(w.length);return Buffer.concat([Buffer.from([A]),X,w])}function nz($){let w=$.getUTCFullYear();if(w>=2050){let Y=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return e0(T$.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=(w%100).toString().padStart(2,"0"),A=($.getUTCMonth()+1).toString().padStart(2,"0"),X=$.getUTCDate().toString().padStart(2,"0"),J=$.getUTCHours().toString().padStart(2,"0"),U=$.getUTCMinutes().toString().padStart(2,"0"),B=$.getUTCSeconds().toString().padStart(2,"0"),W=`${Y}${A}${X}${J}${U}${B}Z`;return e0(T$.UTC_TIME,Buffer.from(W,"ascii"))}}function KT($,w){return o0(nz($),nz(w))}function pz($){let w=[];for(let Y of $){let A;switch(Y.shortName){case"CN":A=g0.COMMON_NAME;break;case"C":A=g0.COUNTRY;break;case"L":A=g0.LOCALITY;break;case"ST":A=g0.STATE;break;case"O":A=g0.ORGANIZATION;break;case"OU":A=g0.ORGANIZATIONAL_UNIT;break;default:continue}let X=Y.shortName==="C"?jT(Y.value):zT(Y.value),J=o0(IY(A),X);w.push(BT(J))}return o0(...w)}function o2($){return o0(IY($),GT())}function FT($){return $.export({type:"spki",format:"der"})}function NT($){if($.includes(":")){let w=$;if($.includes("::")){let X=$.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],B=8-J.length-U.length,W=Array.from({length:B},()=>"0");w=[...J,...W,...U].join(":")}let Y=w.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(w)}}function qT($){let w=[];for(let Y of $)if(Y.type===2&&Y.value){let A=TY(Y.value.length);w.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=NT(Y.ip),X=TY(A.length);w.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=TY(Y.value.length);w.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return o0(...w)}function ET($,w){if($){if(w!==void 0)return o0(e0(1,Buffer.from([255])),eU(w));return o0(e0(1,Buffer.from([255])))}return o0()}function TT($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let Y=0,A=w;while(A>0&&(A&1)===0)Y++,A>>=1;if(w===0)Y=7;return a2(Buffer.from([w]),Y)}function HT($){let w=[];if($.serverAuth)w.push(IY(g0.SERVER_AUTH));if($.clientAuth)w.push(IY(g0.CLIENT_AUTH));return o0(...w)}function qY($,w,Y){let A=[IY($)];if(w)A.push(e0(1,Buffer.from([255])));return A.push(s2(Y)),o0(...A)}function fT($){let w=[];if(w.push(lz(0,eU(2))),w.push(eU($.serialNumber)),w.push(o2(g0.SHA256_WITH_RSA)),w.push(pz($.issuer)),w.push(KT($.notBefore,$.notAfter)),w.push(pz($.subject)),w.push(FT($.publicKey)),$.extensions){let Y=[];if($.extensions.basicConstraints)Y.push(qY(g0.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,ET($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)Y.push(qY(g0.KEY_USAGE,$.extensions.keyUsage.critical??!0,TT($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)Y.push(qY(g0.EXTENDED_KEY_USAGE,!1,HT($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)Y.push(qY(g0.SUBJECT_ALT_NAME,!1,qT($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)Y.push(qY(g0.SUBJECT_KEY_IDENTIFIER,!1,s2($.extensions.subjectKeyIdentifier)));if(Y.length>0)w.push(lz(3,o0(...Y)))}return o0(...w)}function RT($,w){let Y=Q1.createSign("SHA256");Y.update($);let A=Y.sign(w);return o0($,o2(g0.SHA256_WITH_RSA),a2(A))}function MT($,w){let Y=$.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${w}-----
128
128
  ${A.join(`
129
129
  `)}
130
130
  -----END ${w}-----
131
- `}function NW(){let $=C1.randomBytes(20);return $[0]=$[0]&127||1,$}function o2($=2048){let{privateKey:w,publicKey:Y}=C1.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:Y}}function MT($){let w=$.export({type:"spki",format:"der"});return C1.createHash("sha1").update(w).digest()}function e2($){let w={serialNumber:$.serialNumber||NW(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:MT($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let Y=HT(w),A=fT(Y,$.signingKey);return{certificate:RT(A,"CERTIFICATE"),certificateDer:A}}function $G($){return $.export({type:"pkcs8",format:"pem"})}function IT($){return C1.createPrivateKey($)}function VT($){let w=new C1.X509Certificate($),Y=w.publicKey,A=[],X=w.subject.split(`
132
- `);for(let J of X){let[U,...B]=J.split("="),W=B.join("=");if(U&&W)A.push({shortName:U.trim(),value:W.trim()})}return{publicKey:Y,subject:A}}async function qW($={}){L("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||E$.DEFAULT_KEY_SIZE;L("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:Y,publicKey:A}=o2(w),X=[{shortName:"C",value:$.countryName||z0.countryName},{shortName:"ST",value:$.stateName||z0.stateName},{shortName:"L",value:$.localityName||z0.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=FW({validityYears:$.validityYears||E$.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:B}=e2({serialNumber:NW(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:B,privateKey:$G(Y),notBefore:J,notAfter:U}}async function EW($){if(L("ca","Generating new certificate",$.verbose),L("ca",`Options: ${DX($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=VT($.rootCA.certificate),Y=IT($.rootCA.privateKey);L("ca",`Generating ${E$.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let A=E$.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=o2(A),U=$.commonName||p2($),B=$.certificateAttributes||[{shortName:"C",value:$.countryName||z0.countryName},{shortName:"ST",value:$.stateName||z0.stateName},{shortName:"L",value:$.localityName||z0.localityName},{shortName:"O",value:$.organizationName||z0.organizationName},{shortName:"CN",value:U}],{notBefore:W,notAfter:j}=FW({validityDays:$.validityDays||E$.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),z=r2($),G=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},K=$.extKeyUsage||{serverAuth:!0},{certificate:F}=e2({serialNumber:NW(),notBefore:W,notAfter:j,subject:B,issuer:w,publicKey:J,signingKey:Y,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:G,extendedKeyUsage:K,subjectAltName:z});return{certificate:F,privateKey:$G(X),notBefore:W,notAfter:j}}function wG($,w){L(_.STORAGE,`Storing certificate and private key with options: ${DX(w)}`,w?.verbose);let{certPath:Y,keyPath:A}=KW({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});L(_.STORAGE,`Certificate path: ${Y}`,w?.verbose),L(_.STORAGE,`Private key path: ${A}`,w?.verbose);let X=$W.dirname(Y);if(!r$.existsSync(X))L(_.STORAGE,`Creating certificate directory: ${X}`,w?.verbose),r$.mkdirSync(X,{recursive:!0});L(_.STORAGE,"Writing certificate file",w?.verbose),r$.writeFileSync(Y,$.certificate);let J=$W.dirname(A);if(!r$.existsSync(J))L(_.STORAGE,`Creating private key directory: ${J}`,w?.verbose),r$.mkdirSync(J,{recursive:!0});return L(_.STORAGE,"Writing private key file",w?.verbose),r$.writeFileSync(A,$.privateKey),L(_.STORAGE,"Certificate and private key stored successfully",w?.verbose),Y}function YG($,w){L(_.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:Y}=KW({basePath:w?.basePath,caCertPath:w?.caCertPath});L(_.STORAGE,`CA certificate path: ${Y}`,w?.verbose);let A=$W.dirname(Y);if(!r$.existsSync(A))L(_.STORAGE,`Creating CA certificate directory: ${A}`,w?.verbose),r$.mkdirSync(A,{recursive:!0});return L(_.STORAGE,"Writing CA certificate file",w?.verbose),r$.writeFileSync(Y,$),L(_.STORAGE,"CA certificate stored successfully",w?.verbose),Y}function xX($){let w;if($.startsWith("-----BEGIN CERTIFICATE-----"))w=$;else w=l2($);return new CT.X509Certificate(w)}function PX($){return xX($).fingerprint256.replace(/:/g,"").toUpperCase()}function TW($){return AG(xX($).subject)}function QT($){let w=[],Y=$.split(`
133
- `);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)w.push({shortName:X.trim(),value:U.trim()})}return w}function AG($){return QT($).find((w)=>w.shortName==="CN")?.value||""}function yT($){let w=[],Y=AG($.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))w.push(Y);let A=$.subjectAltName;if(A){let X=A.split(", ");for(let J of X)if(J.startsWith("DNS:"))w.push(J.slice(4))}return[...new Set(w)]}function HW($,w){let Y=xX($),A=yT(Y);for(let X of A){if(X===w)return!0;if(X.startsWith("*.")){let J=X.slice(2);if(w.endsWith(J)&&w.indexOf(".")===w.lastIndexOf("."))return!0}}return!1}async function OT($,w){if(OX.platform()!=="darwin")return!1;try{let Y=PX($);if(!Y)return L(_.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(LT("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
134
- `).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return L(_.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return L(_.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(Y){return L(_.TRUST,`Error checking certificate trust: ${Y}`,w),!1}}async function fW($,w,Y){L(_.TRUST,`Adding certificate to system trust store with options: ${DX(Y)}`,Y?.verbose),L(_.TRUST,"Storing certificate and private key",Y?.verbose);let A=wG($,Y);L(_.TRUST,"Storing CA certificate",Y?.verbose);let X=YG(w,Y),J=OX.platform();L(_.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=hT[J];if(!U){let B=`Unsupported platform: ${J}`;throw L(_.TRUST,`Error: ${B}`,Y?.verbose),Error(B)}return await U.addCertificate(X,Y),L(_.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var SN,_X,sz="https://acme-staging-v02.api.letsencrypt.org/directory",oz="https://acme-v02.api.letsencrypt.org/directory",GX,PN="1.2.840.10045.2.1",bN="1.2.840.10045.3.1.7",uN="1.2.840.10045.4.3.2",vN="2.5.4.3",cN="1.2.840.113549.1.9.14",iN="2.5.29.17",TX,YW,hq,kq=($)=>$,xq=($,w)=>{for(var Y in w)hq($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:Dq.bind(w,Y)})},Pq=($,w)=>()=>($&&(w=$($=0)),w),G2,R2,I1,VY,M2,jE,zE,Zz,WX,mU,S0,s,GE,hz,KE,kz,FE,NE,SU,qE,Dz,xz,ZU,EE,TE,HE,fE,BX,I2,RE,Z0,ME,IE,Pz,jX,gU,T0,v,VE,bz,CE,uz,QE,yE,hU,LE,vz,cz,OE,kU,_E,SE,ZE,hE,kE,zX,V2,DE,xE="0.15.6",s0,IX,RY,dU,lU,VX,nU,pU,MY,rU,tU,Nw,C2,Q2,q$,t$,y2,L2,PE,uE,O2,CX,ZC,V0,m,hC,cE,kC,iE,DC,xC,iz,PC,mE,gE,bC,mz,uC,vC,cC,iC,mC,DU,dE,gC,H$,S2,QX,Z2,h2,zW,k2,D2,yX,x2,P2,V1,sE,d$,dC,lC,nC,g2,z0,E$,_,M1,YT,gz="[redacted]",AT,XT,T$,g0,_T,ST,ZT,hT;var XG=t(()=>{SN=_N(import.meta.url);_X=new HY;GX=class GX extends Error{problem;httpStatus;constructor($,w,Y){super($);this.name="AcmeError",this.problem=w,this.httpStatus=Y}};TX=new j2,YW=new z2,hq=Object.defineProperty;G2={};xq(G2,{withErrorRecovery:()=>N2,tryLoadConfig:()=>JE,loadConfigWithResult:()=>AE,loadConfig:()=>f2,isRetryableError:()=>sq,isConfigNotFoundError:()=>aq,isBunfigError:()=>q2,globalPerformanceMonitor:()=>VY,globalCache:()=>I1,getEnvOrDefault:()=>oq,generateConfigTypes:()=>UE,defaultGeneratedDir:()=>L2,defaultConfigDir:()=>y2,deepMergeWithArrayStrategy:()=>WW,deepMerge:()=>E2,createLibraryConfig:()=>WE,config:()=>XE,bunfigPlugin:()=>BE,applyEnvVarsToConfig:()=>EY,TypeGenerationError:()=>pU,SchemaValidationError:()=>MY,PluginError:()=>tU,PerformanceMonitor:()=>XW,FileSystemError:()=>nU,ErrorFactory:()=>Nw,EnvVarError:()=>VX,EnvProcessor:()=>ZX,ConfigValidator:()=>BW,ConfigValidationError:()=>dU,ConfigNotFoundError:()=>IX,ConfigMergeError:()=>lU,ConfigLoader:()=>jW,ConfigLoadError:()=>RY,ConfigFileLoader:()=>hX,ConfigCache:()=>AW,CacheUtils:()=>M2,BunfigError:()=>s0,BrowserConfigError:()=>rU,ArrayMergeStrategies:()=>C2});PE=Pq(async()=>{R2=import.meta.require,I1=new AW,VY=new XW,M2={createKey:bq,isEquivalent:uq,estimateMemoryUsage:vq},jE=qX(cU.cwd(),"config"),zE=qX(cU.cwd(),"src/generated"),Zz=NX.env.CLARITY_LOG_DIR||oN(mq(),"logs"),WX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Zz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},mU=await gq(),S0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},s=S0,GE=S0.red,hz=S0.green,KE=S0.yellow,kz=S0.blue,FE=S0.magenta,NE=S0.cyan,SU=S0.white,qE=S0.gray,Dz=S0.bgRed,xz=S0.bgYellow,ZU=S0.bold,EE=S0.dim,TE=S0.italic,HE=S0.underline,fE=S0.reset,BX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},I2={debug:"\uD83D\uDD0D",info:kz("ℹ"),success:hz("✓"),warning:xz(SU(ZU(" WARN "))),error:Dz(SU(ZU(" ERROR ")))},RE=new fX("stacks"),Z0=new fX("bunfig",{showTags:!0}),ME=i0(fY.cwd(),"config"),IE=i0(fY.cwd(),"src/generated"),Pz=FX.env.CLARITY_LOG_DIR||aN(pq(),"logs"),jX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Pz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},gU=await rq(),T0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},v=T0,VE=T0.red,bz=T0.green,CE=T0.yellow,uz=T0.blue,QE=T0.magenta,yE=T0.cyan,hU=T0.white,LE=T0.gray,vz=T0.bgRed,cz=T0.bgYellow,OE=T0.bgGray,kU=T0.bold,_E=T0.dim,SE=T0.italic,ZE=T0.underline,hE=T0.strikethrough,kE=T0.reset,zX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},V2={debug:"\uD83D\uDD0D",info:uz("ℹ"),success:bz("✓"),warning:cz(hU(kU(" WARN "))),error:vz(hU(kU(" ERROR ")))},DE=new MX("stacks"),s0=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},IX=class extends s0{code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${A} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}},RY=class extends s0{code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}},dU=class extends s0{code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},lU=class extends s0{code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},VX=class extends s0{code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}},nU=class extends s0{code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},pU=class extends s0{code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},MY=class extends s0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},rU=class extends s0{code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}},tU=class extends s0{code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Nw={configNotFound($,w,Y){return new IX($,w,Y)},configLoad($,w,Y){return new RY($,w,Y)},configValidation($,w,Y){return new dU($,w,Y)},configMerge($,w,Y,A){return new lU($,w,Y,A)},envVar($,w,Y,A){return new VX($,w,Y,A)},fileSystem($,w,Y){return new nU($,w,Y)},typeGeneration($,w,Y){return new pU($,w,Y)},schemaValidation($,w,Y){return new MY($,w,Y)},browserConfig($,w,Y,A){return new rU($,w,Y,A)},plugin($,w,Y){return new tU($,w,Y)}},C2={replace:"replace",concat:"concat",smart:"smart"},Q2=/^https?:\/\//,q$=new MX("bunfig",{showTags:!0}),t$=new jW,y2=m0(Dw.cwd(),"config"),L2=m0(Dw.cwd(),"src/generated")});uE=EX.env.CLARITY_LOG_DIR||Rq(bE(),"logs"),O2={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uE,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},CX={...O2},ZC=(async()=>{try{let{loadConfig:$}=await PE().then(()=>G2),w=await $({name:"clarity",alias:"logging",defaultConfig:O2,cwd:EX.cwd()});if(w)Object.assign(CX,w)}catch{}return CX})();V0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},m=V0,hC=V0.red,cE=V0.green,kC=V0.yellow,iE=V0.blue,DC=V0.magenta,xC=V0.cyan,iz=V0.white,PC=V0.gray,mE=V0.bgRed,gE=V0.bgYellow,bC=V0.bgGray,mz=V0.bold,uC=V0.dim,vC=V0.italic,cC=V0.underline,iC=V0.strikethrough,mC=V0.reset,DU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},dE={debug:"\uD83D\uDD0D",info:iE("ℹ"),success:cE("✓"),warning:gE(iz(mz(" WARN "))),error:mE(iz(mz(" ERROR ")))};gC=new kX("stacks");H$=class H$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};S2=class S2 extends H${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 "${$}"${X} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};QX=class QX extends H${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};Z2=class Z2 extends H${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};h2=class h2 extends H${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};zW=class zW extends H${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};k2=class k2 extends H${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};D2=class D2 extends H${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};yX=class yX extends H${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};x2=class x2 extends H${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};P2=class P2 extends H${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};V1={configNotFound($,w,Y){return new S2($,w,Y)},configLoad($,w,Y){return new QX($,w,Y)},configValidation($,w,Y){return new Z2($,w,Y)},configMerge($,w,Y,A){return new h2($,w,Y,A)},envVar($,w,Y,A){return new zW($,w,Y,A)},fileSystem($,w,Y){return new k2($,w,Y)},typeGeneration($,w,Y){return new D2($,w,Y)},schemaValidation($,w,Y){return new yX($,w,Y)},browserConfig($,w,Y,A){return new x2($,w,Y,A)},plugin($,w,Y){return new P2($,w,Y)}};sE=/^https?:\/\//;d$=new kX("bunfig",{showTags:!0});dC=new m2;lC=U$(SX.cwd(),"config"),nC=U$(SX.cwd(),"src/generated"),g2={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(NU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:qU.join(NU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:qU.join(NU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},z0=g2,E$={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"},_={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},M1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};YT=wT(eE);AT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),XT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;T$={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},g0={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"};_T={platform:"darwin",async addCertificate($,w){if(await OT($,w?.verbose)){L(_.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),M1.success("Certificate is already trusted in system keychain");return}L(_.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Fw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from macOS keychain`,w?.verbose);try{await Fw(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),L(_.TRUST,`Removed certificate ${A} from macOS keychain`,w?.verbose)}catch(X){throw L(_.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},ST={platform:"win32",async addCertificate($,w){L(_.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Fw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from Windows certificate store`,w?.verbose);try{await Fw(`certutil -delstore -enterprise Root "${A}"`),L(_.TRUST,`Removed certificate ${A} from Windows certificate store`,w?.verbose)}catch(X){throw L(_.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},ZT={platform:"linux",async addCertificate($,w){L(_.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let Y=OX.homedir(),A=E$.LINUX_CERT_DB_FILENAME,X=E$.LINUX_TRUST_ARGS;L(_.TRUST,`Searching for certificate databases in ${Y}`,w?.verbose);let J=oU(Y,A);if(J.length===0){M1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){L(_.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{L(_.TRUST,`Attempting to delete existing cert for ${z0.commonName}`,w?.verbose),await Fw(`certutil -d sql:${U} -D -n ${z0.commonName}`)}catch(B){L(_.TRUST,`Warning: Error deleting existing cert: ${B}`,w?.verbose),console.warn(`Error deleting existing cert: ${B}`)}L(_.TRUST,`Adding new certificate to ${U}`,w?.verbose),await Fw(`certutil -d sql:${U} -A -t ${X} -n ${z0.commonName} -i ${$}`),M1.info(`Cert added to ${U}`)}},async removeCertificate($,w,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from Linux certificate store`,w?.verbose);let X=OX.homedir(),J=E$.LINUX_CERT_DB_FILENAME;L(_.TRUST,`Searching for certificate databases in ${X}`,w?.verbose);let U=oU(X,J);if(U.length===0){M1.warn("No certificate databases found. Cannot remove certificate.");return}for(let B of U){L(_.TRUST,`Processing certificate database in ${B}`,w?.verbose);try{await Fw(`certutil -d sql:${B} -D -n "${A}"`),M1.info(`Cert removed from ${B}`)}catch(W){L(_.TRUST,`Error removing cert from ${B}: ${W}`,w?.verbose),console.warn(`Error removing cert from ${B}: ${W}`)}}}},hT={darwin:_T,win32:ST,linux:ZT}});var bX=t(()=>{XG()});import{homedir as RW}from"node:os";import{join as MW,resolve as iQ}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",DT,IW;var VW=t(()=>{WU();DT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:MW(RW(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:MW(RW(),".stacks","ssl","stacks.localhost.crt"),keyPath:MW(RW(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},IW=DT});function xw($){try{return PX($)}catch{return null}}function CW($){try{return TW($)||null}catch{return null}}function uX($,w){try{return w.every((Y)=>HW($,Y))}catch{return!1}}var vX=t(()=>{bX()});import{existsSync as JG,statSync as UG}from"fs";import{existsSync as gW,mkdirSync as cT,readdirSync as iT,writeFileSync as mT}from"fs";import{homedir as Q1}from"os";import{dirname as WG,resolve as l0}from"path";import Pw from"process";import{join as gT,relative as dT,resolve as BG}from"path";import Y8 from"process";import{existsSync as dG,mkdirSync as $y,readdirSync as wy,writeFileSync as Yy}from"fs";import{homedir as QW}from"os";import{dirname as Jy,resolve as d0}from"path";import QY from"process";import{join as lT,relative as nT,resolve as jG}from"path";import A8 from"process";import{existsSync as lG,mkdirSync as zy,readdirSync as Gy,writeFileSync as Ky}from"fs";import{dirname as Ny,resolve as X8}from"path";import dW from"process";import{Buffer as Ew}from"buffer";import{createCipheriv as pT,createDecipheriv as rT,randomBytes as yW}from"crypto";import{closeSync as LW,createReadStream as zG,createWriteStream as tT,existsSync as OW,fsyncSync as GG,openSync as KG,writeFileSync as aT}from"fs";import{access as sT,constants as FG,mkdir as oT,readdir as cX,rename as NG,stat as y1,unlink as iX,writeFile as _W}from"fs/promises";import{join as L1}from"path";import h0 from"process";import{pipeline as eT}from"stream/promises";import{createGzip as qG}from"zlib";import O1 from"process";import o$ from"process";import{Buffer as a$}from"buffer";import{createCipheriv as $H,createDecipheriv as wH,randomBytes as SW}from"crypto";import{closeSync as ZW,createReadStream as EG,createWriteStream as YH,existsSync as mX,fsyncSync as TG,openSync as HG,writeFileSync as AH}from"fs";import{access as XH,constants as fG,mkdir as JH,readdir as gX,rename as RG,stat as _1,unlink as dX,writeFile as hW}from"fs/promises";import{isAbsolute as UH,join as S1,resolve as WH}from"path";import x from"process";import{pipeline as BH}from"stream/promises";import{createGzip as MG}from"zlib";import Z1 from"process";import e$ from"process";import lX from"process";import{existsSync as nX}from"fs";import{resolve as kW}from"path";import{existsSync as jH}from"fs";import{existsSync as zH,readdirSync as GH}from"fs";import{extname as DW,resolve as IG}from"path";import KH from"process";import{join as Ff,relative as Nf,resolve as DG}from"path";import G8 from"process";import{Buffer as s$}from"buffer";import{createCipheriv as Tf,createDecipheriv as Hf,randomBytes as vW}from"crypto";import{closeSync as cW,createReadStream as xG,createWriteStream as ff,existsSync as rX,fsyncSync as PG,openSync as bG,writeFileSync as Rf}from"fs";import{access as Mf,constants as uG,mkdir as If,readdir as tX,rename as vG,stat as h1,unlink as aX,writeFile as iW}from"fs/promises";import{isAbsolute as Vf,join as k1,resolve as Cf}from"path";import P from"process";import{pipeline as Qf}from"stream/promises";import{createGzip as cG}from"zlib";import D1 from"process";import $w from"process";function bT($,w){this[$]=PT.bind(null,w)}class $B{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!JG($))return!0;return UG($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=JG(Y)?UG(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class wB{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function FH($,w={}){let A=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return A?`${$}:${A}`:$}function NH($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function qH($){return $.getStats().size*2}function YB($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&Y0(w[0])&&"id"in w[0]&&w[0].id===3&&Y0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(Y0(w)&&Y0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(Y0($)&&"arr"in $&&Array.isArray($.arr)&&Y0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&Y0(w[0])&&Y0($[0])){let A=[...w];for(let X of $)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)=>J8(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!Y0(w)||!Y0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=YB(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((B)=>J8(B,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 J8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!J8($[Y],w[Y]))return!1;return!0}if(Y0($)&&Y0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!J8($[X],w[X]))return!1}return!0}return!1}function Y0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function EH($,w){if(!lG($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return YB(w,A)}catch{return null}}catch{return null}}async function TH({name:$="",cwd:w,defaultConfig:Y}){let A=w||dW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=X8(A,`${U}${B}`),j=await EH(W,Y);if(j!==null)return j}try{let U=X8(A,"package.json");if(lG(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return YB(Y,W)}catch{}}}catch{}return Y}function HH($,w={}){let Y=A8.cwd();while(Y.includes("storage"))Y=jG(Y,"..");let A=jG(Y,$||"");if(w?.relative)return nT(A8.cwd(),A);return A}async function fH(){try{let $=await TH({name:"clarity",defaultConfig:oX,cwd:A8.cwd(),endpoint:"",headers:{}});return{...oX,...$}}catch{return oX}}function B0(){if(o$.env.NODE_ENV==="test"||o$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function RH(){if(o$.env.NODE_ENV==="test"||o$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o$<"u"){let $=o$.type;if($==="renderer"||$==="worker")return!1;return!!(o$.versions&&(o$.versions.node||o$.versions.bun))}return!1}class nG{async format($){let w=await RH(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:O1.pid,hostname:w(),environment:O1.env.NODE_ENV||"development",platform:O1.platform,version:O1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:O1.env.NODE_ENV||O1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class U8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...nW},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new nG,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??h0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...eX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...eX};return{...eX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:nW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await sT(this.config.logDirectory,FG.F_OK|FG.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await oT(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Ew.from($);try{if(!OW(this.currentLogFile))await _W(this.currentLogFile,"",{mode:420});if(X=KG(this.currentLogFile,"a",420),aT(X,W,{flag:"a"}),GG(X),X!==void 0)LW(X),X=void 0;if((await y1(this.currentLogFile)).size===0){if(await _W(this.currentLogFile,W,{flag:"w",mode:420}),(await y1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{LW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 $=new Date().toISOString().split("T")[0];return L1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(B0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return yW(16).toString("hex")}generateKey(){return yW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=yW(16),A=pT("aes-256-gcm",w,Y),X=Ew.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Ew.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=qG(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Ew.from(Ew.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(B0())return;let $=await y1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await cX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await y1(Y).catch(()=>null))try{if(await NG(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await iX(B)}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 _W(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 y1(Y).catch(()=>null))await NG(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await cX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await iX(L1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=zG($),A=tT(w),X=qG();await eT(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),OW(this.currentLogFile))try{let $=KG(this.currentLogFile,"r+");GG($),LW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!B0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await cX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await iX(L1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?o.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=h0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${o.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.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,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!B0()){let j=Y5[$],z=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:o.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:o.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let K=B.split(`
131
+ `}function NW(){let $=Q1.randomBytes(20);return $[0]=$[0]&127||1,$}function e2($=2048){let{privateKey:w,publicKey:Y}=Q1.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:Y}}function IT($){let w=$.export({type:"spki",format:"der"});return Q1.createHash("sha1").update(w).digest()}function $G($){let w={serialNumber:$.serialNumber||NW(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:IT($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let Y=fT(w),A=RT(Y,$.signingKey);return{certificate:MT(A,"CERTIFICATE"),certificateDer:A}}function wG($){return $.export({type:"pkcs8",format:"pem"})}function VT($){return Q1.createPrivateKey($)}function CT($){let w=new Q1.X509Certificate($),Y=w.publicKey,A=[],X=w.subject.split(`
132
+ `);for(let J of X){let[U,...B]=J.split("="),W=B.join("=");if(U&&W)A.push({shortName:U.trim(),value:W.trim()})}return{publicKey:Y,subject:A}}async function qW($={}){L("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||E$.DEFAULT_KEY_SIZE;L("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:Y,publicKey:A}=e2(w),X=[{shortName:"C",value:$.countryName||z0.countryName},{shortName:"ST",value:$.stateName||z0.stateName},{shortName:"L",value:$.localityName||z0.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=FW({validityYears:$.validityYears||E$.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:B}=$G({serialNumber:NW(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:B,privateKey:wG(Y),notBefore:J,notAfter:U}}async function EW($){if(L("ca","Generating new certificate",$.verbose),L("ca",`Options: ${kX($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=CT($.rootCA.certificate),Y=VT($.rootCA.privateKey);L("ca",`Generating ${E$.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let A=E$.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=e2(A),U=$.commonName||r2($),B=$.certificateAttributes||[{shortName:"C",value:$.countryName||z0.countryName},{shortName:"ST",value:$.stateName||z0.stateName},{shortName:"L",value:$.localityName||z0.localityName},{shortName:"O",value:$.organizationName||z0.organizationName},{shortName:"CN",value:U}],{notBefore:W,notAfter:j}=FW({validityDays:$.validityDays||E$.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),z=t2($),G=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},K=$.extKeyUsage||{serverAuth:!0},{certificate:F}=$G({serialNumber:NW(),notBefore:W,notAfter:j,subject:B,issuer:w,publicKey:J,signingKey:Y,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:G,extendedKeyUsage:K,subjectAltName:z});return{certificate:F,privateKey:wG(X),notBefore:W,notAfter:j}}function YG($,w){L(_.STORAGE,`Storing certificate and private key with options: ${kX(w)}`,w?.verbose);let{certPath:Y,keyPath:A}=KW({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});L(_.STORAGE,`Certificate path: ${Y}`,w?.verbose),L(_.STORAGE,`Private key path: ${A}`,w?.verbose);let X=$W.dirname(Y);if(!r$.existsSync(X))L(_.STORAGE,`Creating certificate directory: ${X}`,w?.verbose),r$.mkdirSync(X,{recursive:!0});L(_.STORAGE,"Writing certificate file",w?.verbose),r$.writeFileSync(Y,$.certificate);let J=$W.dirname(A);if(!r$.existsSync(J))L(_.STORAGE,`Creating private key directory: ${J}`,w?.verbose),r$.mkdirSync(J,{recursive:!0});return L(_.STORAGE,"Writing private key file",w?.verbose),r$.writeFileSync(A,$.privateKey),L(_.STORAGE,"Certificate and private key stored successfully",w?.verbose),Y}function AG($,w){L(_.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:Y}=KW({basePath:w?.basePath,caCertPath:w?.caCertPath});L(_.STORAGE,`CA certificate path: ${Y}`,w?.verbose);let A=$W.dirname(Y);if(!r$.existsSync(A))L(_.STORAGE,`Creating CA certificate directory: ${A}`,w?.verbose),r$.mkdirSync(A,{recursive:!0});return L(_.STORAGE,"Writing CA certificate file",w?.verbose),r$.writeFileSync(Y,$),L(_.STORAGE,"CA certificate stored successfully",w?.verbose),Y}function xX($){let w;if($.startsWith("-----BEGIN CERTIFICATE-----"))w=$;else w=n2($);return new QT.X509Certificate(w)}function PX($){return xX($).fingerprint256.replace(/:/g,"").toUpperCase()}function TW($){return XG(xX($).subject)}function yT($){let w=[],Y=$.split(`
133
+ `);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)w.push({shortName:X.trim(),value:U.trim()})}return w}function XG($){return yT($).find((w)=>w.shortName==="CN")?.value||""}function LT($){let w=[],Y=XG($.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))w.push(Y);let A=$.subjectAltName;if(A){let X=A.split(", ");for(let J of X)if(J.startsWith("DNS:"))w.push(J.slice(4))}return[...new Set(w)]}function HW($,w){let Y=xX($),A=LT(Y);for(let X of A){if(X===w)return!0;if(X.startsWith("*.")){let J=X.slice(2);if(w.endsWith(J)&&w.indexOf(".")===w.lastIndexOf("."))return!0}}return!1}async function _T($,w){if(OX.platform()!=="darwin")return!1;try{let Y=PX($);if(!Y)return L(_.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(OT("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
134
+ `).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return L(_.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return L(_.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(Y){return L(_.TRUST,`Error checking certificate trust: ${Y}`,w),!1}}async function fW($,w,Y){L(_.TRUST,`Adding certificate to system trust store with options: ${kX(Y)}`,Y?.verbose),L(_.TRUST,"Storing certificate and private key",Y?.verbose);let A=YG($,Y);L(_.TRUST,"Storing CA certificate",Y?.verbose);let X=AG(w,Y),J=OX.platform();L(_.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=DT[J];if(!U){let B=`Unsupported platform: ${J}`;throw L(_.TRUST,`Error: ${B}`,Y?.verbose),Error(B)}return await U.addCertificate(X,Y),L(_.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var ZN,_X,oz="https://acme-staging-v02.api.letsencrypt.org/directory",ez="https://acme-v02.api.letsencrypt.org/directory",GX,bN="1.2.840.10045.2.1",uN="1.2.840.10045.3.1.7",vN="1.2.840.10045.4.3.2",cN="2.5.4.3",iN="1.2.840.113549.1.9.14",mN="2.5.29.17",TX,YW,Dq,kq=($)=>$,Pq=($,w)=>{for(var Y in w)Dq($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:xq.bind(w,Y)})},bq=($,w)=>()=>($&&(w=$($=0)),w),K2,M2,V1,VY,I2,zE,GE,hz,WX,mU,S0,s,KE,Dz,FE,kz,NE,qE,SU,EE,xz,Pz,ZU,TE,HE,fE,RE,BX,V2,ME,Z0,IE,VE,bz,jX,gU,T0,v,CE,uz,QE,vz,yE,LE,hU,OE,cz,iz,_E,DU,SE,ZE,hE,DE,kE,zX,C2,xE,PE="0.15.6",s0,IX,RY,dU,lU,VX,nU,pU,MY,rU,tU,Nw,Q2,y2,q$,t$,L2,O2,bE,vE,_2,CX,DC,V0,m,kC,iE,xC,mE,PC,bC,mz,uC,gE,dE,vC,gz,cC,iC,mC,gC,dC,kU,lE,lC,H$,Z2,QX,h2,D2,zW,k2,x2,yX,P2,b2,C1,oE,d$,nC,pC,rC,d2,z0,E$,_,I1,AT,dz="[redacted]",XT,JT,T$,g0,ST,ZT,hT,DT;var JG=t(()=>{ZN=SN(import.meta.url);_X=new HY;GX=class GX extends Error{problem;httpStatus;constructor($,w,Y){super($);this.name="AcmeError",this.problem=w,this.httpStatus=Y}};TX=new z2,YW=new G2,Dq=Object.defineProperty;K2={};Pq(K2,{withErrorRecovery:()=>q2,tryLoadConfig:()=>UE,loadConfigWithResult:()=>XE,loadConfig:()=>R2,isRetryableError:()=>oq,isConfigNotFoundError:()=>sq,isBunfigError:()=>E2,globalPerformanceMonitor:()=>VY,globalCache:()=>V1,getEnvOrDefault:()=>eq,generateConfigTypes:()=>WE,defaultGeneratedDir:()=>O2,defaultConfigDir:()=>L2,deepMergeWithArrayStrategy:()=>WW,deepMerge:()=>T2,createLibraryConfig:()=>BE,config:()=>JE,bunfigPlugin:()=>jE,applyEnvVarsToConfig:()=>EY,TypeGenerationError:()=>pU,SchemaValidationError:()=>MY,PluginError:()=>tU,PerformanceMonitor:()=>XW,FileSystemError:()=>nU,ErrorFactory:()=>Nw,EnvVarError:()=>VX,EnvProcessor:()=>ZX,ConfigValidator:()=>BW,ConfigValidationError:()=>dU,ConfigNotFoundError:()=>IX,ConfigMergeError:()=>lU,ConfigLoader:()=>jW,ConfigLoadError:()=>RY,ConfigFileLoader:()=>hX,ConfigCache:()=>AW,CacheUtils:()=>I2,BunfigError:()=>s0,BrowserConfigError:()=>rU,ArrayMergeStrategies:()=>Q2});bE=bq(async()=>{M2=import.meta.require,V1=new AW,VY=new XW,I2={createKey:uq,isEquivalent:vq,estimateMemoryUsage:cq},zE=qX(cU.cwd(),"config"),GE=qX(cU.cwd(),"src/generated"),hz=NX.env.CLARITY_LOG_DIR||eN(gq(),"logs"),WX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:hz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},mU=await dq(),S0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},s=S0,KE=S0.red,Dz=S0.green,FE=S0.yellow,kz=S0.blue,NE=S0.magenta,qE=S0.cyan,SU=S0.white,EE=S0.gray,xz=S0.bgRed,Pz=S0.bgYellow,ZU=S0.bold,TE=S0.dim,HE=S0.italic,fE=S0.underline,RE=S0.reset,BX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},V2={debug:"\uD83D\uDD0D",info:kz("ℹ"),success:Dz("✓"),warning:Pz(SU(ZU(" WARN "))),error:xz(SU(ZU(" ERROR ")))},ME=new fX("stacks"),Z0=new fX("bunfig",{showTags:!0}),IE=i0(fY.cwd(),"config"),VE=i0(fY.cwd(),"src/generated"),bz=FX.env.CLARITY_LOG_DIR||sN(rq(),"logs"),jX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},gU=await tq(),T0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},v=T0,CE=T0.red,uz=T0.green,QE=T0.yellow,vz=T0.blue,yE=T0.magenta,LE=T0.cyan,hU=T0.white,OE=T0.gray,cz=T0.bgRed,iz=T0.bgYellow,_E=T0.bgGray,DU=T0.bold,SE=T0.dim,ZE=T0.italic,hE=T0.underline,DE=T0.strikethrough,kE=T0.reset,zX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},C2={debug:"\uD83D\uDD0D",info:vz("ℹ"),success:uz("✓"),warning:iz(hU(DU(" WARN "))),error:cz(hU(DU(" ERROR ")))},xE=new MX("stacks"),s0=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},IX=class extends s0{code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${A} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}},RY=class extends s0{code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}},dU=class extends s0{code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},lU=class extends s0{code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},VX=class extends s0{code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}},nU=class extends s0{code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},pU=class extends s0{code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},MY=class extends s0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},rU=class extends s0{code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}},tU=class extends s0{code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Nw={configNotFound($,w,Y){return new IX($,w,Y)},configLoad($,w,Y){return new RY($,w,Y)},configValidation($,w,Y){return new dU($,w,Y)},configMerge($,w,Y,A){return new lU($,w,Y,A)},envVar($,w,Y,A){return new VX($,w,Y,A)},fileSystem($,w,Y){return new nU($,w,Y)},typeGeneration($,w,Y){return new pU($,w,Y)},schemaValidation($,w,Y){return new MY($,w,Y)},browserConfig($,w,Y,A){return new rU($,w,Y,A)},plugin($,w,Y){return new tU($,w,Y)}},Q2={replace:"replace",concat:"concat",smart:"smart"},y2=/^https?:\/\//,q$=new MX("bunfig",{showTags:!0}),t$=new jW,L2=m0(kw.cwd(),"config"),O2=m0(kw.cwd(),"src/generated")});vE=EX.env.CLARITY_LOG_DIR||Mq(uE(),"logs"),_2={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},CX={..._2},DC=(async()=>{try{let{loadConfig:$}=await bE().then(()=>K2),w=await $({name:"clarity",alias:"logging",defaultConfig:_2,cwd:EX.cwd()});if(w)Object.assign(CX,w)}catch{}return CX})();V0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},m=V0,kC=V0.red,iE=V0.green,xC=V0.yellow,mE=V0.blue,PC=V0.magenta,bC=V0.cyan,mz=V0.white,uC=V0.gray,gE=V0.bgRed,dE=V0.bgYellow,vC=V0.bgGray,gz=V0.bold,cC=V0.dim,iC=V0.italic,mC=V0.underline,gC=V0.strikethrough,dC=V0.reset,kU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lE={debug:"\uD83D\uDD0D",info:mE("ℹ"),success:iE("✓"),warning:dE(mz(gz(" WARN "))),error:gE(mz(gz(" ERROR ")))};lC=new DX("stacks");H$=class H$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};Z2=class Z2 extends H${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 "${$}"${X} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};QX=class QX extends H${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};h2=class h2 extends H${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};D2=class D2 extends H${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};zW=class zW extends H${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};k2=class k2 extends H${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};x2=class x2 extends H${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};yX=class yX extends H${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};P2=class P2 extends H${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};b2=class b2 extends H${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};C1={configNotFound($,w,Y){return new Z2($,w,Y)},configLoad($,w,Y){return new QX($,w,Y)},configValidation($,w,Y){return new h2($,w,Y)},configMerge($,w,Y,A){return new D2($,w,Y,A)},envVar($,w,Y,A){return new zW($,w,Y,A)},fileSystem($,w,Y){return new k2($,w,Y)},typeGeneration($,w,Y){return new x2($,w,Y)},schemaValidation($,w,Y){return new yX($,w,Y)},browserConfig($,w,Y,A){return new P2($,w,Y,A)},plugin($,w,Y){return new b2($,w,Y)}};oE=/^https?:\/\//;d$=new DX("bunfig",{showTags:!0});nC=new g2;pC=U$(SX.cwd(),"config"),rC=U$(SX.cwd(),"src/generated"),d2={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(NU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:qU.join(NU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:qU.join(NU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},z0=d2,E$={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"},_={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},I1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};AT=YT($T);XT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),JT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;T$={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},g0={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"};ST={platform:"darwin",async addCertificate($,w){if(await _T($,w?.verbose)){L(_.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),I1.success("Certificate is already trusted in system keychain");return}L(_.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Fw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from macOS keychain`,w?.verbose);try{await Fw(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),L(_.TRUST,`Removed certificate ${A} from macOS keychain`,w?.verbose)}catch(X){throw L(_.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},ZT={platform:"win32",async addCertificate($,w){L(_.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Fw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from Windows certificate store`,w?.verbose);try{await Fw(`certutil -delstore -enterprise Root "${A}"`),L(_.TRUST,`Removed certificate ${A} from Windows certificate store`,w?.verbose)}catch(X){throw L(_.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},hT={platform:"linux",async addCertificate($,w){L(_.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let Y=OX.homedir(),A=E$.LINUX_CERT_DB_FILENAME,X=E$.LINUX_TRUST_ARGS;L(_.TRUST,`Searching for certificate databases in ${Y}`,w?.verbose);let J=oU(Y,A);if(J.length===0){I1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){L(_.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{L(_.TRUST,`Attempting to delete existing cert for ${z0.commonName}`,w?.verbose),await Fw(`certutil -d sql:${U} -D -n ${z0.commonName}`)}catch(B){L(_.TRUST,`Warning: Error deleting existing cert: ${B}`,w?.verbose),console.warn(`Error deleting existing cert: ${B}`)}L(_.TRUST,`Adding new certificate to ${U}`,w?.verbose),await Fw(`certutil -d sql:${U} -A -t ${X} -n ${z0.commonName} -i ${$}`),I1.info(`Cert added to ${U}`)}},async removeCertificate($,w,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from Linux certificate store`,w?.verbose);let X=OX.homedir(),J=E$.LINUX_CERT_DB_FILENAME;L(_.TRUST,`Searching for certificate databases in ${X}`,w?.verbose);let U=oU(X,J);if(U.length===0){I1.warn("No certificate databases found. Cannot remove certificate.");return}for(let B of U){L(_.TRUST,`Processing certificate database in ${B}`,w?.verbose);try{await Fw(`certutil -d sql:${B} -D -n "${A}"`),I1.info(`Cert removed from ${B}`)}catch(W){L(_.TRUST,`Error removing cert from ${B}: ${W}`,w?.verbose),console.warn(`Error removing cert from ${B}: ${W}`)}}}},DT={darwin:ST,win32:ZT,linux:hT}});var bX=t(()=>{JG()});import{homedir as RW}from"node:os";import{join as MW,resolve as gQ}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",xT,IW;var VW=t(()=>{WU();xT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:MW(RW(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:MW(RW(),".stacks","ssl","stacks.localhost.crt"),keyPath:MW(RW(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},IW=xT});function xw($){try{return PX($)}catch{return null}}function CW($){try{return TW($)||null}catch{return null}}function uX($,w){try{return w.every((Y)=>HW($,Y))}catch{return!1}}var vX=t(()=>{bX()});import{existsSync as UG,statSync as WG}from"fs";import{existsSync as gW,mkdirSync as iT,readdirSync as mT,writeFileSync as gT}from"fs";import{homedir as y1}from"os";import{dirname as BG,resolve as l0}from"path";import Pw from"process";import{join as dT,relative as lT,resolve as jG}from"path";import Y8 from"process";import{existsSync as lG,mkdirSync as Yy,readdirSync as Ay,writeFileSync as Xy}from"fs";import{homedir as QW}from"os";import{dirname as Wy,resolve as d0}from"path";import QY from"process";import{join as nT,relative as pT,resolve as zG}from"path";import A8 from"process";import{existsSync as nG,mkdirSync as Ky,readdirSync as Fy,writeFileSync as Ny}from"fs";import{dirname as Ey,resolve as X8}from"path";import dW from"process";import{Buffer as Ew}from"buffer";import{createCipheriv as rT,createDecipheriv as tT,randomBytes as yW}from"crypto";import{closeSync as LW,createReadStream as GG,createWriteStream as aT,existsSync as OW,fsyncSync as KG,openSync as FG,writeFileSync as sT}from"fs";import{access as oT,constants as NG,mkdir as eT,readdir as cX,rename as qG,stat as L1,unlink as iX,writeFile as _W}from"fs/promises";import{join as O1}from"path";import h0 from"process";import{pipeline as $H}from"stream/promises";import{createGzip as EG}from"zlib";import _1 from"process";import o$ from"process";import{Buffer as a$}from"buffer";import{createCipheriv as wH,createDecipheriv as YH,randomBytes as SW}from"crypto";import{closeSync as ZW,createReadStream as TG,createWriteStream as AH,existsSync as mX,fsyncSync as HG,openSync as fG,writeFileSync as XH}from"fs";import{access as JH,constants as RG,mkdir as UH,readdir as gX,rename as MG,stat as S1,unlink as dX,writeFile as hW}from"fs/promises";import{isAbsolute as WH,join as Z1,resolve as BH}from"path";import x from"process";import{pipeline as jH}from"stream/promises";import{createGzip as IG}from"zlib";import h1 from"process";import e$ from"process";import lX from"process";import{existsSync as nX}from"fs";import{resolve as DW}from"path";import{existsSync as zH}from"fs";import{existsSync as GH,readdirSync as KH}from"fs";import{extname as kW,resolve as VG}from"path";import FH from"process";import{join as Nf,relative as qf,resolve as xG}from"path";import G8 from"process";import{Buffer as s$}from"buffer";import{createCipheriv as Hf,createDecipheriv as ff,randomBytes as vW}from"crypto";import{closeSync as cW,createReadStream as PG,createWriteStream as Rf,existsSync as rX,fsyncSync as bG,openSync as uG,writeFileSync as Mf}from"fs";import{access as If,constants as vG,mkdir as Vf,readdir as tX,rename as cG,stat as D1,unlink as aX,writeFile as iW}from"fs/promises";import{isAbsolute as Cf,join as k1,resolve as Qf}from"path";import P from"process";import{pipeline as yf}from"stream/promises";import{createGzip as iG}from"zlib";import x1 from"process";import $w from"process";function uT($,w){this[$]=bT.bind(null,w)}class $B{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let X=this.generateKey($,Y),J=A??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,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(!UG($))return!0;return WG($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let X=UG(Y)?WG(Y):null,J=X?X.mtime:new Date;this.set($,{value:w,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 $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,X)=>A+X.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class wB{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-A;return this.recordMetric({operation:$,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function NH($,w={}){let A=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return A?`${$}:${A}`:$}function qH($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function EH($){return $.getStats().size*2}function YB($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&Y0(w[0])&&"id"in w[0]&&w[0].id===3&&Y0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(Y0(w)&&Y0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(Y0($)&&"arr"in $&&Array.isArray($.arr)&&Y0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&Y0(w[0])&&Y0($[0])){let A=[...w];for(let X of $)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)=>J8(J,X)))A.push(X);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!Y0(w)||!Y0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=YB(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((B)=>J8(B,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 J8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!J8($[Y],w[Y]))return!1;return!0}if(Y0($)&&Y0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!J8($[X],w[X]))return!1}return!0}return!1}function Y0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function TH($,w){if(!nG($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return YB(w,A)}catch{return null}}catch{return null}}async function HH({name:$="",cwd:w,defaultConfig:Y}){let A=w||dW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let B of X){let W=X8(A,`${U}${B}`),j=await TH(W,Y);if(j!==null)return j}try{let U=X8(A,"package.json");if(nG(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return YB(Y,W)}catch{}}}catch{}return Y}function fH($,w={}){let Y=A8.cwd();while(Y.includes("storage"))Y=zG(Y,"..");let A=zG(Y,$||"");if(w?.relative)return pT(A8.cwd(),A);return A}async function RH(){try{let $=await HH({name:"clarity",defaultConfig:oX,cwd:A8.cwd(),endpoint:"",headers:{}});return{...oX,...$}}catch{return oX}}function B0(){if(o$.env.NODE_ENV==="test"||o$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function MH(){if(o$.env.NODE_ENV==="test"||o$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof o$<"u"){let $=o$.type;if($==="renderer"||$==="worker")return!1;return!!(o$.versions&&(o$.versions.node||o$.versions.bun))}return!1}class pG{async format($){let w=await MH(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:_1.pid,hostname:w(),environment:_1.env.NODE_ENV||"development",platform:_1.platform,version:_1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_1.env.NODE_ENV||_1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class U8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...nW},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new pG,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??h0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...eX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...eX};return{...eX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:nW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await oT(this.config.logDirectory,NG.F_OK|NG.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await eT(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Ew.from($);try{if(!OW(this.currentLogFile))await _W(this.currentLogFile,"",{mode:420});if(X=FG(this.currentLogFile,"a",420),sT(X,W,{flag:"a"}),KG(X),X!==void 0)LW(X),X=void 0;if((await L1(this.currentLogFile)).size===0){if(await _W(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(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{LW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 $=new Date().toISOString().split("T")[0];return O1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(B0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return yW(16).toString("hex")}generateKey(){return yW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=yW(16),A=rT("aes-256-gcm",w,Y),X=Ew.concat([A.update($,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:Ew.concat([Y,X,J]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=EG(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(Ew.from(Ew.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(B0())return;let $=await L1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await cX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await L1(Y).catch(()=>null))try{if(await qG(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await iX(B)}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 _W(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 qG(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await cX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await iX(O1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=GG($),A=aT(w),X=EG();await $H(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),OW(this.currentLogFile))try{let $=FG(this.currentLogFile,"r+");KG($),LW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!B0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await cX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await iX(O1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?o.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=h0.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${o.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.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,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);if(this.fancy&&!B0()){let j=A5[$],z=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",G;switch($){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:o.gray(U),level:$}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:o.green(U),level:$}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:j,tag:z,message:U,level:$}),console.error(G),B){let K=B.split(`
135
135
  `);for(let F of K)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:o.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!B0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let W=`${J} ${this.environment}.${$.toUpperCase()}: ${U}
136
136
  `;if(B)W+=`${B}
137
137
  `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time($){let w=performance.now();if(this.fancy&&!B0()){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($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
138
- `,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!B0()){let z=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:o.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!B0())console.error(j.trim());await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new U8(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(B0())throw Error("createReadStream is not supported in browser environments");if(!OW(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return zG(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Ew.isBuffer($)?$:Ew.from($,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),B=rT("aes-256-gcm",Y,X);return B.setAuthTag(J),Ew.concat([B.update(U),B.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 B0()}isServerMode(){return!B0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!B0()){let J=$.split(`
138
+ `,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!B0()){let z=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:o.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!B0())console.error(j.trim());await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new U8(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(B0())throw Error("createReadStream is not supported in browser environments");if(!OW(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return GG(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Ew.isBuffer($)?$:Ew.from($,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),B=tT("aes-256-gcm",Y,X);return B.setAuthTag(J),Ew.concat([B.update(U),B.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 B0()}isServerMode(){return!B0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!B0()){let J=$.split(`
139
139
  `),U=Math.max(...J.map((z)=>z.length))+2,B=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,j=J.map((z)=>{let G=" ".repeat(U-z.length-2);return`│ ${z}${G} │`});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(B)})),j.forEach((z)=>console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(z),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(W),showTimestamp:!1}))}else if(!B0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let X=`${A} ${this.environment}.INFO: [BOX] ${$}
140
140
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(B0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${o.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();h0.stdin.removeListener("data",Y);try{if(typeof h0.stdin.setRawMode==="function")h0.stdin.setRawMode(!1)}catch{}h0.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof h0.stdin.setRawMode==="function")h0.stdin.setRawMode(!0)}catch{}h0.stdin.resume(),h0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,B=0;if(Y=$.replace(U,(W,j)=>{if(j==="%")return"%";if(B>=w.length)return W;let z=w[B++];switch(j){case"s":return String(z);case"d":case"i":return Number(z).toString();case"j":case"o":return JSON.stringify(z,null,2);default:return W}}),B<w.length)Y+=` ${w.slice(B).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!B0()){let U=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",B=o.blue("◐");console.error(`${B} ${U} ${o.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
141
141
  `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||B0()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,B)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),B!==void 0)this.activeProgressBar.message=B;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B0())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,B="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B0())return;h0.stdout.write(`${"\r".padEnd(h0.stdout.columns||80)}\r`),this.log(B,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||B0()||!h0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=o.green("━".repeat(A)),U=o.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=w||Y===100?o.green("✓"):o.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${o.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=h0.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,h0.stdout.write($.lastRenderedLine),w)h0.stdout.write(`
142
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||B0()||!h0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(B0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await cX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=L1(this.config.logDirectory,A);if($.before)try{if((await y1(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}function sX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&r(w[0])&&"id"in w[0]&&w[0].id===3&&r(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(r(w)&&r($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(r($)&&"arr"in $&&Array.isArray($.arr)&&r(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&r(w[0])&&r($[0])){let A=[...w];for(let X of $)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(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!r(w)||!r($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(r(X)&&r(Y[A]))Y[A]=sX(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((B)=>W8(B,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 AB($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:sX($,w);if(Array.isArray($))return Y==="replace"?w:sX($,w);if(!r(w)||!r($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[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]=sX(U,J);else if(r(J)&&r(U))A[X]=AB(U,J,Y);else A[X]=J}return A}function W8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!W8($[Y],w[Y]))return!1;return!0}if(r($)&&r(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!W8($[X],w[X]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function pX($,w,Y="replace"){if(!dG($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return AB(w,X,Y)}catch{return null}}catch{return null}}function MH($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${G.map(K).join("_")}`,T=`${A}_${G.map((q)=>q.toUpperCase()).join("_")}`;if(Y)D0.info(`Checking environment variable ${F} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let q=QY.env[F]||QY.env[T];if(q!==void 0){if(Y)D0.info(`Using environment variable ${q?F:T} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(q);else if(typeof z==="boolean")W[j]=q.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(q);if(Array.isArray(E))W[j]=E;else W[j]=q.split(",").map((f)=>f.trim())}catch{W[j]=q.split(",").map((E)=>E.trim())}else W[j]=q}}}return W}return J(X)}async function IH({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?MH($,X,J):X,j=Y||QY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),K=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],q=Array.from(new Set([j,d0(j,"config"),d0(j,".config"),A?d0(j,A):void 0].filter(Boolean)));for(let E of q){if(J)D0.info(`Searching for configuration in: ${E}`);let M=[d0(j,"config"),d0(j,".config")].concat(A?[d0(j,A)]:[]).includes(E)?[...G,...K,...F,...T]:[...K,...G,...T,...F];for(let Q of M)for(let V of z){let H=d0(E,`${Q}${V}`),I=await pX(H,W,B);if(I!==null){if(J)D0.success(`Configuration loaded from: ${H}`);return I}}}if($){let E=d0(QW(),".config",$),f=["config",`${$}.config`];if(w)f.push(`${w}.config`);if(J)D0.info(`Checking user config directory: ${E}`);for(let M of f)for(let Q of z){let V=d0(E,`${M}${Q}`),H=await pX(V,W,B);if(H!==null){if(J)D0.success(`Configuration loaded from user config directory: ${V}`);return H}}}if($){let E=d0(QW(),".config"),f=[`.${$}.config`];if(w)f.push(`.${w}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=d0(E,`${M}${Q}`),H=await pX(V,W,B);if(H!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${V}`);return H}}}if($){let E=QW(),f=[`.${$}.config`,`.${$}`];if(w)f.push(`.${w}.config`),f.push(`.${w}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=d0(E,`${M}${Q}`),H=await pX(V,W,B);if(H!==null){if(J)D0.success(`Configuration loaded from user home directory: ${V}`);return H}}}try{let E=d0(j,"package.json");if(dG(E)){let f=await import(E),M=f[$];if(!M&&w){if(M=f[w],M&&J)D0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)D0.success(`Configuration loaded from package.json: ${M===f[$]?$:w}`);return AB(W,M,B)}catch(Q){if(J)D0.warn("Failed to merge package.json config:",Q)}}}catch(E){if(J)D0.warn("Failed to load package.json:",E)}if(J)D0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function VH($,w={}){let Y=Y8.cwd();while(Y.includes("storage"))Y=BG(Y,"..");let A=BG(Y,$||"");if(w?.relative)return dT(Y8.cwd(),A);return A}async function CH(){try{let $=await IH({name:"clarity",alias:"logging",defaultConfig:$8,cwd:Y8.cwd()});return{...$8,...$||{}}}catch{return $8}}function f0(){if(e$.env.NODE_ENV==="test"||e$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function QH(){if(e$.env.NODE_ENV==="test"||e$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof e$<"u"){let $=e$.type;if($==="renderer"||$==="worker")return!1;return!!(e$.versions&&(e$.versions.node||e$.versions.bun))}return!1}class pG{async format($){let w=await QH(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Z1.pid,hostname:w(),environment:Z1.env.NODE_ENV||"development",platform:Z1.platform,version:Z1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Z1.env.NODE_ENV||Z1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class B8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...pW},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new pG,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...w8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...w8};return{...w8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:pW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!f0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await XH(this.config.logDirectory,fG.F_OK|fG.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await JH(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:a$.from($);try{if(!mX(this.currentLogFile))await hW(this.currentLogFile,"",{mode:420});if(X=HG(this.currentLogFile,"a",420),AH(X,W,{flag:"a"}),TG(X),X!==void 0)ZW(X),X=void 0;if((await _1(this.currentLogFile)).size===0){if(await hW(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(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{ZW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 $=new Date().toISOString().split("T")[0];return S1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(f0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return SW(16).toString("hex")}generateKey(){return SW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=SW(16),A=$H("aes-256-gcm",w,Y),X=a$.isBuffer($)?$:a$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=a$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=MG(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(a$.from(a$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(f0())return;if(!this.shouldWriteToFile())return;let $=await _1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await gX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await _1(Y).catch(()=>null))try{if(await RG(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await dX(B)}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 _1(Y).catch(()=>null))await RG(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await gX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await dX(S1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=EG($),A=YH(w),X=MG();await BH(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),mX(this.currentLogFile))try{let $=HG(this.currentLogFile,"r+");TG($),ZW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!f0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await gX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await dX(S1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||f0())return!1;let $=typeof x.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=x.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${c.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),w}supportsHyperlinks(){if(f0())return!1;let $=x.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=x.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(UH(w)||w.startsWith("./")||w.startsWith("../"))w=WH(w);else return null;return mX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":A5[$],K=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:c.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:c.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
142
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||B0()||!h0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(B0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await cX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=O1(this.config.logDirectory,A);if($.before)try{if((await L1(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}function sX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&r(w[0])&&"id"in w[0]&&w[0].id===3&&r(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(r(w)&&r($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(r($)&&"arr"in $&&Array.isArray($.arr)&&r(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&r(w[0])&&r($[0])){let A=[...w];for(let X of $)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(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}if(!r(w)||!r($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let X=w[A];if(X===null||X===void 0)continue;else if(r(X)&&r(Y[A]))Y[A]=sX(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((B)=>W8(B,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 AB($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:sX($,w);if(Array.isArray($))return Y==="replace"?w:sX($,w);if(!r(w)||!r($))return w;let A={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[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]=sX(U,J);else if(r(J)&&r(U))A[X]=AB(U,J,Y);else A[X]=J}return A}function W8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!W8($[Y],w[Y]))return!1;return!0}if(r($)&&r(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!W8($[X],w[X]))return!1}return!0}return!1}function r($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function pX($,w,Y="replace"){if(!lG($))return null;try{let A=await import($),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return AB(w,X,Y)}catch{return null}}catch{return null}}function IH($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${G.map(K).join("_")}`,T=`${A}_${G.map((q)=>q.toUpperCase()).join("_")}`;if(Y)k0.info(`Checking environment variable ${F} for config ${$}.${G.join(".")}`);if(typeof z==="object"&&z!==null&&!Array.isArray(z))W[j]=J(z,G);else{let q=QY.env[F]||QY.env[T];if(q!==void 0){if(Y)k0.info(`Using environment variable ${q?F:T} for config ${$}.${G.join(".")}`);if(typeof z==="number")W[j]=Number(q);else if(typeof z==="boolean")W[j]=q.toLowerCase()==="true";else if(Array.isArray(z))try{let E=JSON.parse(q);if(Array.isArray(E))W[j]=E;else W[j]=q.split(",").map((f)=>f.trim())}catch{W[j]=q.split(",").map((E)=>E.trim())}else W[j]=q}}}return W}return J(X)}async function VH({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:B="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?IH($,X,J):X,j=Y||QY.cwd(),z=[".ts",".js",".mjs",".cjs",".json"];if(J)k0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${j}`);let G=[$,`.${$}`].filter(Boolean),K=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],q=Array.from(new Set([j,d0(j,"config"),d0(j,".config"),A?d0(j,A):void 0].filter(Boolean)));for(let E of q){if(J)k0.info(`Searching for configuration in: ${E}`);let M=[d0(j,"config"),d0(j,".config")].concat(A?[d0(j,A)]:[]).includes(E)?[...G,...K,...F,...T]:[...K,...G,...T,...F];for(let Q of M)for(let V of z){let H=d0(E,`${Q}${V}`),I=await pX(H,W,B);if(I!==null){if(J)k0.success(`Configuration loaded from: ${H}`);return I}}}if($){let E=d0(QW(),".config",$),f=["config",`${$}.config`];if(w)f.push(`${w}.config`);if(J)k0.info(`Checking user config directory: ${E}`);for(let M of f)for(let Q of z){let V=d0(E,`${M}${Q}`),H=await pX(V,W,B);if(H!==null){if(J)k0.success(`Configuration loaded from user config directory: ${V}`);return H}}}if($){let E=d0(QW(),".config"),f=[`.${$}.config`];if(w)f.push(`.${w}.config`);if(J)k0.info(`Checking user config directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=d0(E,`${M}${Q}`),H=await pX(V,W,B);if(H!==null){if(J)k0.success(`Configuration loaded from user config directory dotfile: ${V}`);return H}}}if($){let E=QW(),f=[`.${$}.config`,`.${$}`];if(w)f.push(`.${w}.config`),f.push(`.${w}`);if(J)k0.info(`Checking user home directory for dotfile configs: ${E}`);for(let M of f)for(let Q of z){let V=d0(E,`${M}${Q}`),H=await pX(V,W,B);if(H!==null){if(J)k0.success(`Configuration loaded from user home directory: ${V}`);return H}}}try{let E=d0(j,"package.json");if(lG(E)){let f=await import(E),M=f[$];if(!M&&w){if(M=f[w],M&&J)k0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(J)k0.success(`Configuration loaded from package.json: ${M===f[$]?$:w}`);return AB(W,M,B)}catch(Q){if(J)k0.warn("Failed to merge package.json config:",Q)}}}catch(E){if(J)k0.warn("Failed to load package.json:",E)}if(J)k0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return W}function CH($,w={}){let Y=Y8.cwd();while(Y.includes("storage"))Y=jG(Y,"..");let A=jG(Y,$||"");if(w?.relative)return lT(Y8.cwd(),A);return A}async function QH(){try{let $=await VH({name:"clarity",alias:"logging",defaultConfig:$8,cwd:Y8.cwd()});return{...$8,...$||{}}}catch{return $8}}function f0(){if(e$.env.NODE_ENV==="test"||e$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function yH(){if(e$.env.NODE_ENV==="test"||e$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof e$<"u"){let $=e$.type;if($==="renderer"||$==="worker")return!1;return!!(e$.versions&&(e$.versions.node||e$.versions.bun))}return!1}class rG{async format($){let w=await yH(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:h1.pid,hostname:w(),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 B8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...pW},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new rG,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...w8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...w8};return{...w8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:pW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!f0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await JH(this.config.logDirectory,RG.F_OK|RG.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await UH(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:a$.from($);try{if(!mX(this.currentLogFile))await hW(this.currentLogFile,"",{mode:420});if(X=fG(this.currentLogFile,"a",420),XH(X,W,{flag:"a"}),HG(X),X!==void 0)ZW(X),X=void 0;if((await S1(this.currentLogFile)).size===0){if(await hW(this.currentLogFile,W,{flag:"w",mode:420}),(await S1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{ZW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 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 $=new Date().toISOString().split("T")[0];return Z1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(f0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.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 w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return SW(16).toString("hex")}generateKey(){return SW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=SW(16),A=wH("aes-256-gcm",w,Y),X=a$.isBuffer($)?$:a$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=a$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=IG(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(a$.from(a$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(f0())return;if(!this.shouldWriteToFile())return;let $=await S1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await gX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await S1(Y).catch(()=>null))try{if(await MG(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await dX(B)}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 S1(Y).catch(()=>null))await MG(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await gX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await dX(Z1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=TG($),A=AH(w),X=IG();await jH(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),mX(this.currentLogFile))try{let $=fG(this.currentLogFile,"r+");HG($),ZW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!f0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await gX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await dX(Z1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||f0())return!1;let $=typeof x.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=x.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${c.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),w}supportsHyperlinks(){if(f0())return!1;let $=x.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=x.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(WH(w)||w.startsWith("./")||w.startsWith("../"))w=BH(w);else return null;return mX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":X5[$],K=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:c.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:c.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
143
143
  `);for(let q of T)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:c.gray(` ${q}`),level:$,showTimestamp:!1}))}break}}else if(!f0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}if(!this.shouldLog($))return;let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
144
144
  `;if(B)z+=`${B}
145
145
  `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!f0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!f0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!f0()&&x.stdout.isTTY)x.stdout.write(`
146
146
  `);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!f0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":c.blue("◐"),tag:Y,message:`${c.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
147
- `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":c.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!f0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new B8(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(f0())throw Error("createReadStream is not supported in browser environments");if(!mX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return EG(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=a$.isBuffer($)?$:a$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=wH("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=a$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
147
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":c.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!f0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new B8(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(f0())throw Error("createReadStream is not supported in browser environments");if(!mX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return TG(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=a$.isBuffer($)?$:a$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=YH("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=a$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.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=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
148
148
  `),W=Math.max(...B.map((K)=>K.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((K)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(K),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(j),showTimestamp:!1})),G.forEach((K)=>console.error(K)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(z),showTimestamp:!1}))}else if(!f0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
149
149
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(f0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${c.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let K=w[j++];switch(G){case"s":return String(K);case"d":case"i":return Number(K).toString();case"j":case"o":return JSON.stringify(K,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).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)):"",j=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${j}${W} ${c.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
150
150
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!x.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=c.green("━".repeat(A)),U=c.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?c.green("✓"):c.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=x.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,x.stdout.write($.lastRenderedLine),w)x.stdout.write(`
151
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||f0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(f0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await gX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=S1(this.config.logDirectory,A);if($.before)try{if((await _1(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}async function rG($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function tG($){return $ instanceof $$}function yH($){return $ instanceof j8}function LH($){if(tG($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class F8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return OY.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=lX.env[W]||(j?lX.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=lX.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof z8)throw G;throw Tw.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Tw.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(lX.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
151
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||f0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(f0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await gX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=Z1(this.config.logDirectory,A);if($.before)try{if((await S1(J)).mtime>=$.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(w){console.error("Error during log clearing process:",w)}}}async function tG($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let B=0;B<=Y;B++)try{return await $()}catch(W){if(U=W instanceof Error?W:Error(String(W)),B===Y||!X(U))break;if(A>0)await new Promise((j)=>setTimeout(j,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function aG($){return $ instanceof $$}function LH($){return $ instanceof j8}function OH($){if(aG($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class F8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:B=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let z=A||this.generateEnvPrefix($),G={...w};return this.processObject(G,[],z,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:B,configName:$}),{config:G,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return OY.track("applyEnvironmentVariables",j,{configName:$});return j()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=U.map((z)=>this.formatEnvKey(z,A.useCamelCase)),W=`${Y}_${B.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((z)=>z.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let z=lX.env[W]||(j?lX.env[j]:void 0);if(z!==void 0){if(A.verbose){let G=lX.env[W]?W:j}try{$[X]=this.parseEnvironmentValue(z,typeof J,W,A.customParsers,A.configName)}catch(G){if(G instanceof z8)throw G;throw Tw.envVar(W,z,typeof J,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,X){for(let[J,U]of Object.entries(A))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Tw.envVar(Y,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,X]of Object.entries(lX.env))if(A.startsWith(Y)&&X!==void 0)w[A]=X;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(X){A.push(`Cannot parse value "${w}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,Y,A){for(let[X,J]of Object.entries($)){let U=[...w,X],B=`${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:B,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
152
152
 
153
153
  `;for(let A of $)Y+=`${A.key}
154
154
  `,Y+=` Type: ${A.type}
@@ -160,34 +160,34 @@ ${A.join(`
160
160
  `;Y+=`| Variable | Type | Description | Example |
161
161
  `,Y+=`|----------|------|-------------|----------|
162
162
  `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
163
- `;return Y}}function OH($,w){let Y=$5("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function aG($,w,Y={}){return sG($,w,Y,new WeakMap)}function sG($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return oG($,w,X,A);if(!j$(w)||!j$($))return w;return hH($,w,Y,A)}function oG($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return _H($,w);case"smart":return SH($,w,A);default:return w}return w}function _H($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>lW(X,A)))Y.push(A);return Y}function SH($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(j$(w[0])&&j$($[0]))return ZH($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function ZH($,w,Y){let A=[...w];for(let X of $){if(!j$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>j$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function hH($,w,Y,A){let X=w;if(j$(X)&&A.has(X))return A.get(X);let J={...$};if(j$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(j$(B)&&j$(W))J[U]=sG(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=oG(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function XB($,w,Y="replace"){return aG($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function lW($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!lW($[Y],w[Y]))return!1;return!0}if(j$($)&&j$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!lW($[X],w[X]))return!1}return!0}return!1}function j$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class N8{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:B=!1}=Y;if(X){let j=x1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!nX($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new yY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new yY($,Error("Configuration must export a valid object"),"unknown");let E={config:XB(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)x1.setWithFileCheck("file",E,$,J);return E}catch(j){throw j instanceof Error?Tw.configLoad($,j):Tw.configLoad($,Error(String(j)))}};if(U)return OY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(kW(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return rG(async()=>{return nX($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!nX($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=kW($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=kW($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!nX($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class JB{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await OY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!jH(w))throw new LY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new LY(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:J5},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class UB{fileLoader=new N8;envProcessor=new F8;validator=new JB;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)f$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw f$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||Pw.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(l0(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw Tw.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?CY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)f$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)f$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?CY($,Y,X):Y,B=[l0(Q1(),".config",$),l0(Q1(),".config"),Q1()];for(let W of B){if(X)f$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)f$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?CY($,A,J):A;try{let W=l0(Y,"package.json");if(!gW(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)f$.success(`Configuration loaded from package.json: ${G}`);return{config:XB(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)f$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:CY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 Tw.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($,A);x1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,l0($,"config"),l0($,".config"),w?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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[l0(Q1(),".config",$),l0(Q1(),".config"),Q1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function VG($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function kH($){return ww.loadConfig({...$,__strictErrorHandling:!0})}async function eG($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await ww.loadConfig($);else A=await ww.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)f$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await ww.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function DH($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await ww.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&VG(Y)))return(await ww.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await ww.loadConfig({...$,cwd:$.cwd||Pw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&VG(w)))return(await ww.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function xH($,w,Y="replace"){let A=new N8;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function CY($,w,Y=!1){let A=new F8,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=Pw.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function PH($){let w=l0(Pw.cwd(),$.configDir),Y=l0(Pw.cwd(),$.generatedDir),A=l0(Y,"config-types.ts");if(!gW(WG(A)))cT(WG(A),{recursive:!0,mode:511});let X=gW(w)?iT(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${Gf}
163
+ `;return Y}}function _H($,w){let Y=w5("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function sG($,w,Y={}){return oG($,w,Y,new WeakMap)}function oG($,w,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if(w===null||w===void 0)return J?$:w;if(U){let B=U($,w);if(B!==void 0)return B}if(Array.isArray(w)||Array.isArray($))return eG($,w,X,A);if(!j$(w)||!j$($))return w;return DH($,w,Y,A)}function eG($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return SH($,w);case"smart":return ZH($,w,A);default:return w}return w}function SH($,w){let Y=[...w];for(let A of $)if(!Y.some((X)=>lW(X,A)))Y.push(A);return Y}function ZH($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(j$(w[0])&&j$($[0]))return hH($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let X of $)if(!A.includes(X))A.push(X);return A}return w}function hH($,w,Y){let A=[...w];for(let X of $){if(!j$(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let B of J)if(B in X){if(A.find((j)=>j$(j)&&(B in j)&&j[B]===X[B])){U=!0;break}}if(!U)A.push(X)}return A}function DH($,w,Y,A){let X=w;if(j$(X)&&A.has(X))return A.get(X);let J={...$};if(j$(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let B=X[U],W=J[U];if(Y.skipNullish&&(B===null||B===void 0))continue;if(B===null||B===void 0){J[U]=B;continue}if(j$(B)&&j$(W))J[U]=oG(W,B,Y,A);else if(Array.isArray(B)||Array.isArray(W))J[U]=eG(W,B,Y.arrayMergeMode||"smart",A);else J[U]=B}return J}function XB($,w,Y="replace"){return sG($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function lW($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!lW($[Y],w[Y]))return!1;return!0}if(j$($)&&j$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!lW($[X],w[X]))return!1}return!0}return!1}function j$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class N8{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:B=!1}=Y;if(X){let j=P1.getWithFileCheck("file",$);if(j){if(B)console.log(`Configuration loaded from cache: ${$}`);return j}}let W=async()=>{if(!nX($))return null;try{let j=`?t=${Date.now()}`,z=await import($+j),G=z.default||z,K="default"in z,F=Object.keys(z).length>0;if(!K&&!F)throw new yY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof G!=="object"||G===null||Array.isArray(G))throw new yY($,Error("Configuration must export a valid object"),"unknown");let E={config:XB(w,G,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)P1.setWithFileCheck("file",E,$,J);return E}catch(j){throw j instanceof Error?Tw.configLoad($,j):Tw.configLoad($,Error(String(j)))}};if(U)return OY.track("loadFromPath",W,{path:$});return W()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let X=await this.loadFromPath(A,w,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($,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(DW(w,`${J}${U}`));return X}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return tG(async()=>{return nX($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!nX($))return A;if(w||Y){let X=this.generateNamePatterns(w||"",Y);for(let J of X)for(let U of this.extensions){let B=DW($,`${J}${U}`);if(await this.checkFileAccess(B))A.push(B)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let B=DW($,U);if(await this.checkFileAccess(B))A.push(B)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!nX($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let X=await this.loadFromPath(A,{},w);if(X)Y.set(A,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class JB{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:B=!0,verbose:W=!1}=Y,j=async()=>{let z=[],G=[],K={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:B,verbose:W};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,K);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],K);else return this.validateWithJSONSchema($,w,K)}catch(F){return z.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:z,warnings:G}}};if(B)return await OY.track("validateConfiguration",j);return j()}async validateWithSchemaFile($,w,Y){try{if(!zH(w))throw new LY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),X=A.default||A;if(Array.isArray(X))return this.validateWithRules($,X,Y);else return this.validateWithJSONSchema($,X,Y)}catch(A){throw new LY(w,[{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&&w.type){let U=Array.isArray($)?"array":typeof $,B=Array.isArray(w.type)?w.type:[w.type];if(!B.includes(U)){if(A.push({path:Y,message:`Expected type ${B.join(" or ")}, got ${U}`,expected:B.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let B=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,B,A,X,J),J.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let B of w.required)if(!(B in U)){if(A.push({path:Y?`${Y}.${B}`:B,message:`Missing required property '${B}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[B,W]of Object.entries(w.properties))if(B in U){let j=Y?`${Y}.${B}`:B;if(this.validateObjectAgainstSchema(U[B],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let B=new Set(Object.keys(w.properties||{}));for(let W of Object.keys(U))if(!B.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 w)try{let U=this.getValueByPath($,J.path),B=this.validateWithRule(U,J,J.path);if(A.push(...B),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(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)A.push({path:Y,message:w.message||X,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:U5},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class UB{fileLoader=new N8;envProcessor=new F8;validator=new JB;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=$;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let B;try{B=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;B={...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 z=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),G=!z&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),K=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(K||z))throw W;if(G&&(!j||!K))B={...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(!j)B={...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 B={...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(B.config,X,J,U.name);if(Y?.enabled&&B)this.cacheResult(U.name||"",B,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)f$.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);B.metrics=W}return B}catch(B){let W=Date.now()-w;throw f$.error(`Configuration loading failed after ${W}ms:`,[B instanceof Error?B:Error(String(B))]),B}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:B,checkEnv:W=!0,arrayStrategy:j="replace",verbose:z=!1}=$,G=J||Pw.cwd(),K=[],F=await this.loadLocalConfiguration(A,X,G,U,B,j,z,W,Y);if(F)return K.push(...this.getLocalSearchPaths(A,X,G,U)),this.finalizeResult(F,K,W,A,z);let T=await this.loadHomeConfiguration(A,X,B,j,z,W);if(T)return K.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,K,W,A,z);let q=await this.loadPackageJsonConfiguration(A,X,G,B,j,z,W);if(q)return K.push(l0(G,"package.json")),this.finalizeResult(q,K,W,A,z);if(K.push(...this.getAllSearchPaths(A,X,G,U)),w)throw Tw.configNotFound(A,K,X);return{...await this.applyEnvironmentVariables(A,B,W,z),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,X,J,U,B,W){let j=B?CY($,X,U):X,z=this.getLocalDirectories(Y,A);for(let G of z){if(U)f$.info(`Searching for configuration in: ${G}`);let K=this.fileLoader.generateConfigPaths($,G,w),F=await this.fileLoader.tryLoadFromPaths(K,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(F){if(U)f$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,X,J){if(!$)return null;let U=J?CY($,Y,X):Y,B=[l0(y1(),".config",$),l0(y1(),".config"),y1()];for(let W of B){if(X)f$.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths($,W,w),z=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(z){if(X)f$.success(`Configuration loaded from home directory: ${z.source.path}`);return z}}return null}async loadPackageJsonConfiguration($,w,Y,A,X,J,U){let B=U?CY($,A,J):A;try{let W=l0(Y,"package.json");if(!gW(W))return null;let j=await import(W),z=j[$],G=$;if(!z&&w)z=j[w],G=w;if(z&&typeof z==="object"&&!Array.isArray(z)){if(J)f$.success(`Configuration loaded from package.json: ${G}`);return{config:XB(B,z,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)f$.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:CY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let X=[];if(Y){let J=Y($);if(J)X.push(...J)}if(w){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 Tw.configValidation(A||"unknown",X,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return P1.get(Y)||null}cacheResult($,w,Y,A){let X=this.generateCacheKey($,A);P1.set(X,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,l0($,"config"),l0($,".config"),w?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($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let Y=[l0(y1(),".config",$),l0(y1(),".config"),y1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths($,X,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function CG($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function kH($){return ww.loadConfig({...$,__strictErrorHandling:!0})}async function $5($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await ww.loadConfig($);else A=await ww.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}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"))&&$.verbose)f$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let B=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await ww.applyEnvironmentVariables(B.name||"",w,!0,B.verbose||!1))?.config??w;return w}}async function xH($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await ww.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&CG(Y)))return(await ww.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await ww.loadConfig({...$,cwd:$.cwd||Pw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&CG(w)))return(await ww.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function PH($,w,Y="replace"){let A=new N8;try{let X=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function CY($,w,Y=!1){let A=new F8,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,B=[]){let W={...U};for(let[j,z]of Object.entries(U)){let G=[...B,j],K=[`${X}_${G.join("_").toUpperCase()}`,`${X}_${G.map((q)=>q.toUpperCase()).join("")}`,`${X}_${G.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let q of K)if(F=Pw.env[q],F!==void 0){T=q;break}if(F!==void 0&&T)if(typeof z==="boolean")W[j]=["true","1","yes"].includes(F.toLowerCase());else if(typeof z==="number"){let q=Number(F);if(!Number.isNaN(q))W[j]=q}else if(Array.isArray(z))try{W[j]=JSON.parse(F)}catch{W[j]=F.split(",").map((q)=>q.trim())}else W[j]=F;else if(z&&typeof z==="object"&&!Array.isArray(z))W[j]=J(z,G)}return W}return J(w)}function bH($){let w=l0(Pw.cwd(),$.configDir),Y=l0(Pw.cwd(),$.generatedDir),A=l0(Y,"config-types.ts");if(!gW(BG(A)))iT(BG(A),{recursive:!0,mode:511});let X=gW(w)?mT(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${Kf}
164
164
  export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
165
- `;mT(A,J,{mode:438})}function bH($){let w=null,Y=null,A=()=>{if(!Y)Y=eG($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)f$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in $?$.defaultConfig:{};return w=X,A(),new Proxy({},{get(J,U){if(w)return w[U];let B=X[U];return A(),B},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,B){if(!w)w={...X};return w[U]=B,!0}})}function uH($){let w=IG(KH.cwd(),$?.configDir||"./config");function Y(){if(!zH(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=GH(w).filter((W)=>X.has(DW(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:j}of U){let z=DW(j).toLowerCase(),G=B.get(W);if(!G){B.set(W,j);continue}let K=DW(G).toLowerCase();if(J.indexOf(z)<J.indexOf(K))B.set(W,j)}return Array.from(B.entries()).map(([W,j])=>({base:W,file:j})).sort((W,j)=>W.base.localeCompare(j.base))}function A(){let X=Y(),J=X.map((j)=>j.base),U=J.length?J.map((j)=>`'${j}'`).join(" | "):"string",B=X.length?`{
166
- ${X.map((j)=>{let z=IG(w,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${z}').default`}).join(`,
165
+ `;gT(A,J,{mode:438})}function uH($){let w=null,Y=null,A=()=>{if(!Y)Y=$5($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)f$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in $?$.defaultConfig:{};return w=X,A(),new Proxy({},{get(J,U){if(w)return w[U];let B=X[U];return A(),B},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,B){if(!w)w={...X};return w[U]=B,!0}})}function vH($){let w=VG(FH.cwd(),$?.configDir||"./config");function Y(){if(!GH(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=KH(w).filter((W)=>X.has(kW(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),B=new Map;for(let{base:W,file:j}of U){let z=kW(j).toLowerCase(),G=B.get(W);if(!G){B.set(W,j);continue}let K=kW(G).toLowerCase();if(J.indexOf(z)<J.indexOf(K))B.set(W,j)}return Array.from(B.entries()).map(([W,j])=>({base:W,file:j})).sort((W,j)=>W.base.localeCompare(j.base))}function A(){let X=Y(),J=X.map((j)=>j.base),U=J.length?J.map((j)=>`'${j}'`).join(" | "):"string",B=X.length?`{
166
+ ${X.map((j)=>{let z=VG(w,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${z}').default`}).join(`,
167
167
  `)}
168
168
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
169
169
  export type ConfigByName = ${B}
170
170
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
171
171
  export type ConfigOf = Config
172
- `}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 qf($,w={}){let Y=G8.cwd();while(Y.includes("storage"))Y=DG(Y,"..");let A=DG(Y,$||"");if(w?.relative)return Nf(G8.cwd(),A);return A}function M0(){if($w.env.NODE_ENV==="test"||$w.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function yf(){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.type;if($==="renderer"||$==="worker")return!1;return!!($w.versions&&($w.versions.node||$w.versions.bun))}return!1}class j5{async format($){let w=await yf(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:D1.pid,hostname:w(),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 bw{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...K8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new j5,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...mW,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...mW};return{...mW,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:K8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await Mf(this.config.logDirectory,uG.F_OK|uG.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await If(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:s$.from($);try{if(!rX(this.currentLogFile))await iW(this.currentLogFile,"",{mode:420});if(X=bG(this.currentLogFile,"a",420),Rf(X,W,{flag:"a"}),PG(X),X!==void 0)cW(X),X=void 0;if((await h1(this.currentLogFile)).size===0){if(await iW(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(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{cW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 k1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return k1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return k1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return vW(16).toString("hex")}generateKey(){return vW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=vW(16),A=Tf("aes-256-gcm",w,Y),X=s$.isBuffer($)?$:s$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=s$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=cG(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(s$.from(s$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let $=await h1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await tX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await h1(Y).catch(()=>null))try{if(await vG(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await aX(B)}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 h1(Y).catch(()=>null))await vG(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await tX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await aX(k1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=xG($),A=ff(w),X=cG();await Qf(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),rX(this.currentLogFile))try{let $=bG(this.currentLogFile,"r+");PG($),cW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await tX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await aX(k1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let $=typeof P.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=P.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${g.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),w}supportsHyperlinks(){if(M0())return!1;let $=P.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=P.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(Vf(w)||w.startsWith("./")||w.startsWith("../"))w=Cf(w);else return null;return rX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":Zf[$],K=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:g.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:g.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
172
+ `}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 Ef($,w={}){let Y=G8.cwd();while(Y.includes("storage"))Y=xG(Y,"..");let A=xG(Y,$||"");if(w?.relative)return qf(G8.cwd(),A);return A}function M0(){if($w.env.NODE_ENV==="test"||$w.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Lf(){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.type;if($==="renderer"||$==="worker")return!1;return!!($w.versions&&($w.versions.node||$w.versions.bun))}return!1}class z5{async format($){let w=await Lf(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:x1.pid,hostname:w(),environment:x1.env.NODE_ENV||"development",platform:x1.platform,version:x1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:x1.env.NODE_ENV||x1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class bw{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...K8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new z5,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let 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($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...mW,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...mW};return{...mW,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:K8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let X,J=0,U=3,B=1000;while(J<U)try{try{try{await If(this.config.logDirectory,vG.F_OK|vG.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await Vf(this.config.logDirectory,{recursive:!0,mode:493});else if(j.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw j;else throw j}}catch(j){throw console.error("Debug: [writeToFile] Failed to create log directory:",j),j}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:s$.from($);try{if(!rX(this.currentLogFile))await iW(this.currentLogFile,"",{mode:420});if(X=uG(this.currentLogFile,"a",420),Mf(X,W,{flag:"a"}),bG(X),X!==void 0)cW(X),X=void 0;if((await D1(this.currentLogFile)).size===0){if(await iW(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(j){let z=j;if(z.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(z.code)){if(J<U-1){let G=typeof z.message==="string"?z.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,G);let K=B*2**J;await new Promise((F)=>setTimeout(F,K)),J++;continue}}if(z?.code&&["ENOSPC","EDQUOT"].includes(z.code))throw Error(`Disk quota exceeded or no space left on device: ${z.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",z),z}finally{if(X!==void 0)try{cW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let z=W,G=typeof z.message==="string"?z.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",G),W}J++;let j=B*2**(J-1);await new Promise((z)=>setTimeout(z,j))}})();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 k1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return k1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return k1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,B],[,W])=>W.createdAt.getTime()-B.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[B]of X.slice(U))this.encryptionKeys.delete(B),this.keys.delete(B)}generateKeyId(){return vW(16).toString("hex")}generateKey(){return vW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=vW(16),A=Hf("aes-256-gcm",w,Y),X=s$.isBuffer($)?$:s$.from($,"utf8"),J=A.update(X),U=A.final(),B=J.length+U.length,W=A.getAuthTag(),j=s$.allocUnsafe(16+B+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+B),{encrypted:j,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=iG(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>w(s$.from(s$.concat(X)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let $=await D1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await tX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let z=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-z}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,B=`${Y}.${U}`;if(await D1(Y).catch(()=>null))try{if(await cG(Y,B),w.compress)try{let W=`${B}.gz`;await this.compressLogFile(B,W),await aX(B)}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 D1(Y).catch(()=>null))await cG(Y,J)}if(this.currentLogFile=A,w.maxFiles){let J=(await tX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,B)=>B.localeCompare(U));for(let U of J.slice(w.maxFiles))await aX(k1(this.config.logDirectory,U))}}}async compressLogFile($,w){let Y=PG($),A=Rf(w),X=iG();await yf(Y,X,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),rX(this.currentLogFile))try{let $=uG(this.currentLogFile,"r+");bG($),cW($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await tX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await aX(k1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?g.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let $=typeof P.env.NO_COLOR<"u",w=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($){let{timestamp:w,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=$,B=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let W=P.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${g.cyan(X)}`;if(!U)return j.trim();let z=B(j).trim().length,G=B(w).length,K=Math.max(1,W-2-z-G);return`${j.trim()}${" ".repeat(K)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let B=Number.parseInt(U,10);return B<w[0].length?String(w[0][B]):J});let Y=/%([sdijfo%])/g,A=0,X=$.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=w.length)return J;let B=w[A++];switch(U){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 J}});if(A<w.length)X+=` ${w.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let B=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${B}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),w=w.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),w}supportsHyperlinks(){if(M0())return!1;let $=P.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=P.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(Cf(w)||w.startsWith("./")||w.startsWith("../"))w=Qf(w);else return null;return rX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,B;if(w instanceof Error)U=w.message,B=w.stack;else U=this.formatMessage(w,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let G=this.options.showIcons===!1?"":hf[$],K=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:g.gray(W),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:g.green(W),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:G,tag:K,message:W,level:$}),console.error(F),B){let T=B.split(`
173
173
  `);for(let q of T)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:g.gray(` ${q}`),level:$,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),B)console.error(B)}let z=`${J} ${this.environment}.${$.toUpperCase()}: ${j}
174
174
  `;if(B)z+=`${B}
175
175
  `;if(z=z.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(z)}progress($,w=""){let Y={update:(B,W)=>{},finish:(B)=>{},interrupt:(B,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(B,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,B),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(B)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,B)},interrupt:(B,W="info")=>{if(!M0()&&P.stdout.isTTY)P.stdout.write(`
176
176
  `);if(this[W==="warning"?"warn":W](B),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=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($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-w),J=`${$} completed in ${X}ms`,U=new Date,B=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
177
- `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":g.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new bw(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!rX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return xG(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=s$.isBuffer($)?$:s$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=Hf("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=s$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
177
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let z=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:B,icon:this.options.showIcons===!1?"":g.green("✓"),tag:z,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(j.trim());if(this.shouldWriteToFile())await this.writeToFile(j)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new bw(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!rX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return PG(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=s$.isBuffer($)?$:s$.from($,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),B=ff("aes-256-gcm",Y,X);B.setAuthTag(J);let W=B.update(U),j=B.final(),z=W.length+j.length,G=s$.allocUnsafe(z);return W.copy(G,0),j.copy(G,W.length),G.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let B=X.split(`
178
178
  `),W=Math.max(...B.map((K)=>K.length))+2,j=`┌${"─".repeat(W)}┐`,z=`└${"─".repeat(W)}┘`,G=B.map((K)=>{return this.formatConsoleMessage({timestamp:Y,message:g.cyan(K),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(j),showTimestamp:!1})),G.forEach((K)=>console.error(K)),console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(z),showTimestamp:!1}))}else if(!M0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
179
179
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(M0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${g.cyan("?")} ${$} (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(""),w(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($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=$.replace(W,(z,G)=>{if(G==="%")return"%";if(j>=w.length)return z;let K=w[j++];switch(G){case"s":return String(K);case"d":case"i":return Number(K).toString();case"j":case"o":return JSON.stringify(K,null,2);default:return z}}),j<w.length)Y+=` ${w.slice(j).map((z)=>typeof z==="object"?JSON.stringify(z,null,2):String(z)).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)):"",j=this.options.showIcons===!1?"":`${g.blue("◐")} `;console.error(`${j}${W} ${g.cyan(A)}`)}let B=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
180
180
  `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(B)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!P.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),X=$.barLength-A,J=g.green("━".repeat(A)),U=g.gray("━".repeat(X)),B=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=$.message?` ${$.message}`:"",z=this.options.showIcons===!1?"":w||Y===100?g.green("✓"):g.blue("▶"),G=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",K=`\r${z}${G} ${B} ${W}${j}`,F=P.stdout.columns||80,T=" ".repeat(Math.max(0,F-K.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${K}${T}`,P.stdout.write($.lastRenderedLine),w)P.stdout.write(`
181
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await tX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=k1(this.config.logDirectory,A);if($.before)try{if((await h1(J)).mtime>=$.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 aX(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(w){console.error("Error during log clearing process:",w)}}}var xT,PT=($)=>$,uT=($,w)=>{for(var Y in w)xT($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:bT.bind(w,Y)})},vT=($,w)=>()=>($&&(w=$($=0)),w),gG,$5,x1,OY,w5,vH,cH,CG,oX,nW,k0,o,iH,QG,mH,yG,gH,dH,xW,lH,LG,OG,PW,nH,pH,rH,tH,eX,Y5,aH,D0,sH,oH,_G,$8,pW,R0,c,eH,SG,$f,ZG,wf,Yf,bW,Af,hG,kG,Xf,uW,Jf,Uf,Wf,Bf,jf,w8,A5,zf,Gf="0.15.6",$$,j8,yY,rW,tW,z8,aW,sW,LY,oW,eW,Tw,X5,J5,f$,ww,U5,W5,Kf,Ef,B5,K8,ly,C0,g,YL,Lf,AL,Of,XL,JL,iG,UL,_f,Sf,WL,mG,BL,jL,zL,GL,KL,mW,Zf,FL;var WB=t(()=>{xT=Object.defineProperty;gG={};uT(gG,{withErrorRecovery:()=>rG,tryLoadConfig:()=>xH,loadConfigWithResult:()=>kH,loadConfig:()=>eG,isRetryableError:()=>LH,isConfigNotFoundError:()=>yH,isBunfigError:()=>tG,globalPerformanceMonitor:()=>OY,globalCache:()=>x1,getEnvOrDefault:()=>OH,generateConfigTypes:()=>PH,defaultGeneratedDir:()=>W5,defaultConfigDir:()=>U5,deepMergeWithArrayStrategy:()=>XB,deepMerge:()=>aG,createLibraryConfig:()=>bH,config:()=>DH,bunfigPlugin:()=>uH,applyEnvVarsToConfig:()=>CY,TypeGenerationError:()=>sW,SchemaValidationError:()=>LY,PluginError:()=>eW,PerformanceMonitor:()=>wB,FileSystemError:()=>aW,ErrorFactory:()=>Tw,EnvVarError:()=>z8,EnvProcessor:()=>F8,ConfigValidator:()=>JB,ConfigValidationError:()=>rW,ConfigNotFoundError:()=>j8,ConfigMergeError:()=>tW,ConfigLoader:()=>UB,ConfigLoadError:()=>yY,ConfigFileLoader:()=>N8,ConfigCache:()=>$B,CacheUtils:()=>w5,BunfigError:()=>$$,BrowserConfigError:()=>oW,ArrayMergeStrategies:()=>X5});Kf=vT(async()=>{$5=import.meta.require,x1=new $B,OY=new wB,w5={createKey:FH,isEquivalent:NH,estimateMemoryUsage:qH},vH=X8(dW.cwd(),"config"),cH=X8(dW.cwd(),"src/generated"),CG=A8.env.CLARITY_LOG_DIR||lT(HH(),"logs"),oX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:CG,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},nW=await fH(),k0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},o=k0,iH=k0.red,QG=k0.green,mH=k0.yellow,yG=k0.blue,gH=k0.magenta,dH=k0.cyan,xW=k0.white,lH=k0.gray,LG=k0.bgRed,OG=k0.bgYellow,PW=k0.bold,nH=k0.dim,pH=k0.italic,rH=k0.underline,tH=k0.reset,eX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Y5={debug:"\uD83D\uDD0D",info:yG("ℹ"),success:QG("✓"),warning:OG(xW(PW(" WARN "))),error:LG(xW(PW(" ERROR ")))},aH=new U8("stacks"),D0=new U8("bunfig",{showTags:!0}),sH=d0(QY.cwd(),"config"),oH=d0(QY.cwd(),"src/generated"),_G=Y8.env.CLARITY_LOG_DIR||gT(VH(),"logs"),$8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_G,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},pW=await CH(),R0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},c=R0,eH=R0.red,SG=R0.green,$f=R0.yellow,ZG=R0.blue,wf=R0.magenta,Yf=R0.cyan,bW=R0.white,Af=R0.gray,hG=R0.bgRed,kG=R0.bgYellow,Xf=R0.bgGray,uW=R0.bold,Jf=R0.dim,Uf=R0.italic,Wf=R0.underline,Bf=R0.strikethrough,jf=R0.reset,w8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},A5={debug:"\uD83D\uDD0D",info:ZG("ℹ"),success:SG("✓"),warning:kG(bW(uW(" WARN "))),error:hG(bW(uW(" ERROR ")))},zf=new B8("stacks"),$$=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},j8=class extends $${code="CONFIG_NOT_FOUND";constructor(w,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},yY=class extends $${code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},rW=class extends $${code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},tW=class extends $${code="CONFIG_MERGE_ERROR";constructor(w,Y,A,X){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},z8=class extends $${code="ENV_VAR_ERROR";constructor(w,Y,A,X){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:X})}},aW=class extends $${code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},sW=class extends $${code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},LY=class extends $${code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},oW=class extends $${code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,X){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:X})}},eW=class extends $${code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Tw={configNotFound($,w,Y){return new j8($,w,Y)},configLoad($,w,Y){return new yY($,w,Y)},configValidation($,w,Y){return new rW($,w,Y)},configMerge($,w,Y,A){return new tW($,w,Y,A)},envVar($,w,Y,A){return new z8($,w,Y,A)},fileSystem($,w,Y){return new aW($,w,Y)},typeGeneration($,w,Y){return new sW($,w,Y)},schemaValidation($,w,Y){return new LY($,w,Y)},browserConfig($,w,Y,A){return new oW($,w,Y,A)},plugin($,w,Y){return new eW($,w,Y)}},X5={replace:"replace",concat:"concat",smart:"smart"},J5=/^https?:\/\//,f$=new B8("bunfig",{showTags:!0}),ww=new UB,U5=l0(Pw.cwd(),"config"),W5=l0(Pw.cwd(),"src/generated")});Ef=G8.env.CLARITY_LOG_DIR||Ff(qf(),"logs"),B5={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ef,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},K8={...B5},ly=(async()=>{try{let{loadConfig:$}=await Kf().then(()=>gG),w=await $({name:"clarity",alias:"logging",defaultConfig:B5,cwd:G8.cwd()});if(w)Object.assign(K8,w)}catch{}return K8})();C0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},g=C0,YL=C0.red,Lf=C0.green,AL=C0.yellow,Of=C0.blue,XL=C0.magenta,JL=C0.cyan,iG=C0.white,UL=C0.gray,_f=C0.bgRed,Sf=C0.bgYellow,WL=C0.bgGray,mG=C0.bold,BL=C0.dim,jL=C0.italic,zL=C0.underline,GL=C0.strikethrough,KL=C0.reset,mW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Zf={debug:"\uD83D\uDD0D",info:Of("ℹ"),success:Lf("✓"),warning:Sf(iG(mG(" WARN "))),error:_f(iG(mG(" ERROR ")))};FL=new bw("stacks")});var b1={};Gj(b1,{shouldReusePort:()=>P1,safeStringify:()=>R$,safeDeleteFile:()=>GB,resolvePathRewrite:()=>zB,redactSensitive:()=>q8,isValidRootCA:()=>jB,isSingleProxyOptions:()=>SY,isSingleProxyConfig:()=>bf,isProcessElevated:()=>E8,isMultiProxyOptions:()=>vw,isMultiProxyConfig:()=>K5,getSudoPassword:()=>uw,getPrimaryDomain:()=>T8,extractHostname:()=>Pf,execSudoSync:()=>_Y,debugLog:()=>N});import{execSync as BB}from"node:child_process";import*as G5 from"node:fs/promises";function uw(){return process.env.SUDO_PASSWORD}function E8(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function _Y($){if(E8())return BB($,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let w=uw(),Y=$.replace(/'/g,"'\\''");if(w)return BB(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return BB(`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 N($,w,Y){if(Y)hf.debug(`[rpx:${$}] ${w}`)}function P1(){let $=process.env.RPX_REUSE_PORT;return $==="1"||$==="true"}function xf($){let w=$.toLowerCase();return kf.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function q8($){if(Array.isArray($))return $.map((Y)=>q8(Y));if(typeof $==="string")return Df.test($)?z5:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(xf(Y)){w[Y]=z5;continue}w[Y]=q8(A)}return w}function R$($,w){return JSON.stringify(q8($),null,w)}function Pf($){if(vw($))return $.proxies.map((w)=>{let Y=w.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(SY($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function jB($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function T8($){if(!$)return"stacks.localhost";if(vw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(SY($))return $.to||"stacks.localhost";return"stacks.localhost"}function K5($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function vw($){return"proxies"in $&&Array.isArray($.proxies)}function SY($){return"to"in $&&typeof $.to==="string"}function bf($){return!!($&&("to"in $)&&!("proxies"in $))}function zB($,w){if(!w||w.length===0)return null;for(let Y of w)if($===Y.from||$.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?$.slice(Y.from.length)||"/":$;return{targetHost:A,targetPath:X}}return null}async function GB($,w){try{await G5.unlink($),N("certificates",`Successfully deleted: ${$}`,w)}catch(Y){if(Y.code!=="ENOENT")N("certificates",`Warning: Could not delete ${$}: ${Y}`,w)}}var hf,z5="[redacted]",kf,Df;var X0=t(()=>{WB();hf=new bw("rpx",{showTags:!1});kf=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),Df=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as H8}from"node:child_process";import{homedir as uf}from"node:os";import{join as vf}from"node:path";function f8(){return vf(uf(),"Library/Keychains/login.keychain-db")}function FB(){return[v1,f8()]}function F5($,w=KB){let Y=H8(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
182
- `)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function NB($){if(process.platform!=="darwin")return;let w=xw($.caPath);if(!w)return;let Y=$.commonName??KB,A=$.keychains??FB();for(let X of A)for(let J of F5(X,Y)){if(J===w)continue;try{if(X.startsWith("/Library"))_Y(`security delete-certificate -Z ${J} "${X}"`);else H8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});N("ssl",`Removed stale Root CA ${J} from ${X}`,$.verbose)}catch{}}}function qB($,w,Y){if(process.platform!=="darwin")return R8($,Y);try{let X=H8(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return N("ssl",`verify-cert ${w}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function R8($,w){let Y=xw($);if(!Y)return!1;for(let A of FB())try{let X=H8(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let J of X.split(`
183
- `))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return N("ssl",`Root CA fingerprint found in ${A}`,w?.verbose),!0}}catch{}return!1}var u1="-d -r trustRoot -p ssl -p basic",v1="/Library/Keychains/System.keychain",KB="rpx.localhost";var EB=t(()=>{vX();X0()});import{execSync as TB}from"node:child_process";import G0 from"node:fs/promises";import*as HB from"node:os";import{homedir as c1}from"node:os";import*as E5 from"node:path";import{join as K0}from"node:path";import*as Hw from"node:process";function fB($,w){return[...new Set($.filter(Boolean))].map((Y)=>({serverName:Y,cert:w.cert,key:w.key}))}function RB($,w,Y){let A=K0(c1(),".stacks","ssl"),X=[...new Set([w,...$,"rpx.localhost"])];return{https:{certPath:M8,keyPath:K0(A,"rpx.localhost.key"),caCertPath:K0(A,"rpx.localhost.ca.crt"),commonName:w},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function T5($){return{caCertPath:K0($,mf),caKeyPath:K0($,gf)}}async function df($,w){try{let[Y,A]=await Promise.all([G0.readFile($.caCertPath,"utf8"),G0.readFile($.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return N("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:Y,privateKey:A}}catch(Y){return N("ssl",`No existing Root CA at ${$.caCertPath} (${Y.code||Y}), will create one`,w),null}}function N5($){let w=new Set;w.add($);let Y=$.split(".");if(Y.length>=2)w.add(`*.${Y.slice(1).join(".")}`);return Array.from(w)}function H5($){let Y=T8($).replace(/\*/g,"wildcard"),A=K0(c1(),".stacks","ssl"),X=A;if(typeof $?.https==="object")return X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:A,{caCertPath:$.https.caCertPath||K0(X,`${Y}.ca.crt`),certPath:$.https.certPath||K0(X,`${Y}.crt`),keyPath:$.https.keyPath||K0(X,`${Y}.key`)};return{caCertPath:K0(X,`${Y}.ca.crt`),certPath:K0(X,`${Y}.crt`),keyPath:K0(X,`${Y}.key`)}}function q5($){let w=new Set;if(vw($))$.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";N5(A).forEach((X)=>w.add(X))});else if(SY($)){let Y=$.to||"rpx.localhost";N5(Y).forEach((A)=>w.add(A))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function i1($){if(fw&&!$.forceRegenerate){N("ssl","Using cached SSL configuration",$.verbose);return}I8();let w=vw($)?$.proxies.map((z)=>z.to):[$.to];N("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let Y=ZY($,$.verbose),A=Y.basePath||K0(c1(),".stacks","ssl");await G0.mkdir(A,{recursive:!0});let X=T5(A),J=await df(X,$.verbose),U=!1;if(!J){if($.verbose)R.info("Generating Root CA certificate (one-time)...");J=await qW(Y);try{await Promise.all([G0.writeFile(X.caCertPath,J.certificate),G0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,N("ssl",`Persisted Root CA at ${X.caCertPath}`,$.verbose)}catch(z){throw N("ssl",`Error saving Root CA files: ${z}`,$.verbose),Error(`Failed to save Root CA files: ${z}`)}}else N("ssl",`Reusing existing Root CA from ${X.caCertPath}`,$.verbose);if($.verbose)R.info(`Generating host certificate for: ${w.join(", ")}`);let B=await EW({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([G0.writeFile(Y.certPath,B.certificate),G0.writeFile(Y.keyPath,B.privateKey),G0.writeFile(Y.caCertPath,J.certificate)]),N("ssl","Certificate files saved successfully",$.verbose)}catch(z){throw N("ssl",`Error saving certificate files: ${z}`,$.verbose),Error(`Failed to save certificate files: ${z}`)}if(U?!1:await R5(X.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(N("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)R.success("Root CA is already trusted in system trust store");if(fw={key:B.privateKey,cert:B.certificate,ca:J.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)R.info("Adding certificate to system trust store (may require sudo permission)...");let j=!1;if(Hw.platform==="darwin")try{NB({caPath:X.caCertPath,verbose:$.verbose});let z=f8();try{TB(`security add-trusted-cert ${u1} -k "${z}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(_Y(`security add-trusted-cert ${u1} -k ${v1} "${X.caCertPath}"`),$.verbose)R.success("Successfully added Root CA to system trust store");j=!0;let G=K0(A,"trust-rpx-cert.sh"),K=`#!/bin/bash
181
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await tX(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=k1(this.config.logDirectory,A);if($.before)try{if((await D1(J)).mtime>=$.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 aX(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(w){console.error("Error during log clearing process:",w)}}}var PT,bT=($)=>$,vT=($,w)=>{for(var Y in w)PT($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:uT.bind(w,Y)})},cT=($,w)=>()=>($&&(w=$($=0)),w),dG,w5,P1,OY,Y5,cH,iH,QG,oX,nW,D0,o,mH,yG,gH,LG,dH,lH,xW,nH,OG,_G,PW,pH,rH,tH,aH,eX,A5,sH,k0,oH,eH,SG,$8,pW,R0,c,$f,ZG,wf,hG,Yf,Af,bW,Xf,DG,kG,Jf,uW,Uf,Wf,Bf,jf,zf,w8,X5,Gf,Kf="0.15.6",$$,j8,yY,rW,tW,z8,aW,sW,LY,oW,eW,Tw,J5,U5,f$,ww,W5,B5,Ff,Tf,j5,K8,py,C0,g,XL,Of,JL,_f,UL,WL,mG,BL,Sf,Zf,jL,gG,zL,GL,KL,FL,NL,mW,hf,qL;var WB=t(()=>{PT=Object.defineProperty;dG={};vT(dG,{withErrorRecovery:()=>tG,tryLoadConfig:()=>PH,loadConfigWithResult:()=>kH,loadConfig:()=>$5,isRetryableError:()=>OH,isConfigNotFoundError:()=>LH,isBunfigError:()=>aG,globalPerformanceMonitor:()=>OY,globalCache:()=>P1,getEnvOrDefault:()=>_H,generateConfigTypes:()=>bH,defaultGeneratedDir:()=>B5,defaultConfigDir:()=>W5,deepMergeWithArrayStrategy:()=>XB,deepMerge:()=>sG,createLibraryConfig:()=>uH,config:()=>xH,bunfigPlugin:()=>vH,applyEnvVarsToConfig:()=>CY,TypeGenerationError:()=>sW,SchemaValidationError:()=>LY,PluginError:()=>eW,PerformanceMonitor:()=>wB,FileSystemError:()=>aW,ErrorFactory:()=>Tw,EnvVarError:()=>z8,EnvProcessor:()=>F8,ConfigValidator:()=>JB,ConfigValidationError:()=>rW,ConfigNotFoundError:()=>j8,ConfigMergeError:()=>tW,ConfigLoader:()=>UB,ConfigLoadError:()=>yY,ConfigFileLoader:()=>N8,ConfigCache:()=>$B,CacheUtils:()=>Y5,BunfigError:()=>$$,BrowserConfigError:()=>oW,ArrayMergeStrategies:()=>J5});Ff=cT(async()=>{w5=import.meta.require,P1=new $B,OY=new wB,Y5={createKey:NH,isEquivalent:qH,estimateMemoryUsage:EH},cH=X8(dW.cwd(),"config"),iH=X8(dW.cwd(),"src/generated"),QG=A8.env.CLARITY_LOG_DIR||nT(fH(),"logs"),oX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:QG,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},nW=await RH(),D0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},o=D0,mH=D0.red,yG=D0.green,gH=D0.yellow,LG=D0.blue,dH=D0.magenta,lH=D0.cyan,xW=D0.white,nH=D0.gray,OG=D0.bgRed,_G=D0.bgYellow,PW=D0.bold,pH=D0.dim,rH=D0.italic,tH=D0.underline,aH=D0.reset,eX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},A5={debug:"\uD83D\uDD0D",info:LG("ℹ"),success:yG("✓"),warning:_G(xW(PW(" WARN "))),error:OG(xW(PW(" ERROR ")))},sH=new U8("stacks"),k0=new U8("bunfig",{showTags:!0}),oH=d0(QY.cwd(),"config"),eH=d0(QY.cwd(),"src/generated"),SG=Y8.env.CLARITY_LOG_DIR||dT(CH(),"logs"),$8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:SG,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},pW=await QH(),R0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},c=R0,$f=R0.red,ZG=R0.green,wf=R0.yellow,hG=R0.blue,Yf=R0.magenta,Af=R0.cyan,bW=R0.white,Xf=R0.gray,DG=R0.bgRed,kG=R0.bgYellow,Jf=R0.bgGray,uW=R0.bold,Uf=R0.dim,Wf=R0.italic,Bf=R0.underline,jf=R0.strikethrough,zf=R0.reset,w8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},X5={debug:"\uD83D\uDD0D",info:hG("ℹ"),success:ZG("✓"),warning:kG(bW(uW(" WARN "))),error:DG(bW(uW(" ERROR ")))},Gf=new B8("stacks"),$$=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},j8=class extends $${code="CONFIG_NOT_FOUND";constructor(w,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},yY=class extends $${code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},rW=class extends $${code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},tW=class extends $${code="CONFIG_MERGE_ERROR";constructor(w,Y,A,X){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},z8=class extends $${code="ENV_VAR_ERROR";constructor(w,Y,A,X){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:X})}},aW=class extends $${code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},sW=class extends $${code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},LY=class extends $${code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},oW=class extends $${code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,X){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:X})}},eW=class extends $${code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Tw={configNotFound($,w,Y){return new j8($,w,Y)},configLoad($,w,Y){return new yY($,w,Y)},configValidation($,w,Y){return new rW($,w,Y)},configMerge($,w,Y,A){return new tW($,w,Y,A)},envVar($,w,Y,A){return new z8($,w,Y,A)},fileSystem($,w,Y){return new aW($,w,Y)},typeGeneration($,w,Y){return new sW($,w,Y)},schemaValidation($,w,Y){return new LY($,w,Y)},browserConfig($,w,Y,A){return new oW($,w,Y,A)},plugin($,w,Y){return new eW($,w,Y)}},J5={replace:"replace",concat:"concat",smart:"smart"},U5=/^https?:\/\//,f$=new B8("bunfig",{showTags:!0}),ww=new UB,W5=l0(Pw.cwd(),"config"),B5=l0(Pw.cwd(),"src/generated")});Tf=G8.env.CLARITY_LOG_DIR||Nf(Ef(),"logs"),j5={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Tf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},K8={...j5},py=(async()=>{try{let{loadConfig:$}=await Ff().then(()=>dG),w=await $({name:"clarity",alias:"logging",defaultConfig:j5,cwd:G8.cwd()});if(w)Object.assign(K8,w)}catch{}return K8})();C0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},g=C0,XL=C0.red,Of=C0.green,JL=C0.yellow,_f=C0.blue,UL=C0.magenta,WL=C0.cyan,mG=C0.white,BL=C0.gray,Sf=C0.bgRed,Zf=C0.bgYellow,jL=C0.bgGray,gG=C0.bold,zL=C0.dim,GL=C0.italic,KL=C0.underline,FL=C0.strikethrough,NL=C0.reset,mW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},hf={debug:"\uD83D\uDD0D",info:_f("ℹ"),success:Of("✓"),warning:Zf(mG(gG(" WARN "))),error:Sf(mG(gG(" ERROR ")))};qL=new bw("stacks")});var u1={};Kj(u1,{shouldReusePort:()=>b1,safeStringify:()=>R$,safeDeleteFile:()=>GB,resolvePathRewrite:()=>zB,redactSensitive:()=>q8,isValidRootCA:()=>jB,isSingleProxyOptions:()=>SY,isSingleProxyConfig:()=>uf,isProcessElevated:()=>E8,isMultiProxyOptions:()=>vw,isMultiProxyConfig:()=>F5,getSudoPassword:()=>uw,getPrimaryDomain:()=>T8,extractHostname:()=>bf,execSudoSync:()=>_Y,debugLog:()=>N});import{execSync as BB}from"node:child_process";import*as K5 from"node:fs/promises";function uw(){return process.env.SUDO_PASSWORD}function E8(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function _Y($){if(E8())return BB($,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let w=uw(),Y=$.replace(/'/g,"'\\''");if(w)return BB(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return BB(`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 N($,w,Y){if(Y)Df.debug(`[rpx:${$}] ${w}`)}function b1(){let $=process.env.RPX_REUSE_PORT;return $==="1"||$==="true"}function Pf($){let w=$.toLowerCase();return kf.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function q8($){if(Array.isArray($))return $.map((Y)=>q8(Y));if(typeof $==="string")return xf.test($)?G5:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(Pf(Y)){w[Y]=G5;continue}w[Y]=q8(A)}return w}function R$($,w){return JSON.stringify(q8($),null,w)}function bf($){if(vw($))return $.proxies.map((w)=>{let Y=w.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(SY($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function jB($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function T8($){if(!$)return"stacks.localhost";if(vw($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(SY($))return $.to||"stacks.localhost";return"stacks.localhost"}function F5($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function vw($){return"proxies"in $&&Array.isArray($.proxies)}function SY($){return"to"in $&&typeof $.to==="string"}function uf($){return!!($&&("to"in $)&&!("proxies"in $))}function zB($,w){if(!w||w.length===0)return null;for(let Y of w)if($===Y.from||$.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?$.slice(Y.from.length)||"/":$;return{targetHost:A,targetPath:X}}return null}async function GB($,w){try{await K5.unlink($),N("certificates",`Successfully deleted: ${$}`,w)}catch(Y){if(Y.code!=="ENOENT")N("certificates",`Warning: Could not delete ${$}: ${Y}`,w)}}var Df,G5="[redacted]",kf,xf;var X0=t(()=>{WB();Df=new bw("rpx",{showTags:!1});kf=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),xf=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as H8}from"node:child_process";import{homedir as vf}from"node:os";import{join as cf}from"node:path";function f8(){return cf(vf(),"Library/Keychains/login.keychain-db")}function FB(){return[c1,f8()]}function N5($,w=KB){let Y=H8(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
182
+ `)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function NB($){if(process.platform!=="darwin")return;let w=xw($.caPath);if(!w)return;let Y=$.commonName??KB,A=$.keychains??FB();for(let X of A)for(let J of N5(X,Y)){if(J===w)continue;try{if(X.startsWith("/Library"))_Y(`security delete-certificate -Z ${J} "${X}"`);else H8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});N("ssl",`Removed stale Root CA ${J} from ${X}`,$.verbose)}catch{}}}function qB($,w,Y){if(process.platform!=="darwin")return R8($,Y);try{let X=H8(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return N("ssl",`verify-cert ${w}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function R8($,w){let Y=xw($);if(!Y)return!1;for(let A of FB())try{let X=H8(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let J of X.split(`
183
+ `))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return N("ssl",`Root CA fingerprint found in ${A}`,w?.verbose),!0}}catch{}return!1}var v1="-d -r trustRoot -p ssl -p basic",c1="/Library/Keychains/System.keychain",KB="rpx.localhost";var EB=t(()=>{vX();X0()});import{execSync as TB}from"node:child_process";import G0 from"node:fs/promises";import*as HB from"node:os";import{homedir as i1}from"node:os";import*as T5 from"node:path";import{join as K0}from"node:path";import*as Hw from"node:process";function fB($,w){return[...new Set($.filter(Boolean))].map((Y)=>({serverName:Y,cert:w.cert,key:w.key}))}function RB($,w,Y){let A=K0(i1(),".stacks","ssl"),X=[...new Set([w,...$,"rpx.localhost"])];return{https:{certPath:M8,keyPath:K0(A,"rpx.localhost.key"),caCertPath:K0(A,"rpx.localhost.ca.crt"),commonName:w},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function H5($){return{caCertPath:K0($,gf),caKeyPath:K0($,df)}}async function lf($,w){try{let[Y,A]=await Promise.all([G0.readFile($.caCertPath,"utf8"),G0.readFile($.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return N("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:Y,privateKey:A}}catch(Y){return N("ssl",`No existing Root CA at ${$.caCertPath} (${Y.code||Y}), will create one`,w),null}}function q5($){let w=new Set;w.add($);let Y=$.split(".");if(Y.length>=2)w.add(`*.${Y.slice(1).join(".")}`);return Array.from(w)}function f5($){let Y=T8($).replace(/\*/g,"wildcard"),A=K0(i1(),".stacks","ssl"),X=A;if(typeof $?.https==="object")return X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:A,{caCertPath:$.https.caCertPath||K0(X,`${Y}.ca.crt`),certPath:$.https.certPath||K0(X,`${Y}.crt`),keyPath:$.https.keyPath||K0(X,`${Y}.key`)};return{caCertPath:K0(X,`${Y}.ca.crt`),certPath:K0(X,`${Y}.crt`),keyPath:K0(X,`${Y}.key`)}}function E5($){let w=new Set;if(vw($))$.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";q5(A).forEach((X)=>w.add(X))});else if(SY($)){let Y=$.to||"rpx.localhost";q5(Y).forEach((A)=>w.add(A))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function m1($){if(fw&&!$.forceRegenerate){N("ssl","Using cached SSL configuration",$.verbose);return}I8();let w=vw($)?$.proxies.map((z)=>z.to):[$.to];N("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let Y=ZY($,$.verbose),A=Y.basePath||K0(i1(),".stacks","ssl");await G0.mkdir(A,{recursive:!0});let X=H5(A),J=await lf(X,$.verbose),U=!1;if(!J){if($.verbose)R.info("Generating Root CA certificate (one-time)...");J=await qW(Y);try{await Promise.all([G0.writeFile(X.caCertPath,J.certificate),G0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,N("ssl",`Persisted Root CA at ${X.caCertPath}`,$.verbose)}catch(z){throw N("ssl",`Error saving Root CA files: ${z}`,$.verbose),Error(`Failed to save Root CA files: ${z}`)}}else N("ssl",`Reusing existing Root CA from ${X.caCertPath}`,$.verbose);if($.verbose)R.info(`Generating host certificate for: ${w.join(", ")}`);let B=await EW({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([G0.writeFile(Y.certPath,B.certificate),G0.writeFile(Y.keyPath,B.privateKey),G0.writeFile(Y.caCertPath,J.certificate)]),N("ssl","Certificate files saved successfully",$.verbose)}catch(z){throw N("ssl",`Error saving certificate files: ${z}`,$.verbose),Error(`Failed to save certificate files: ${z}`)}if(U?!1:await M5(X.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(N("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)R.success("Root CA is already trusted in system trust store");if(fw={key:B.privateKey,cert:B.certificate,ca:J.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)R.info("Adding certificate to system trust store (may require sudo permission)...");let j=!1;if(Hw.platform==="darwin")try{NB({caPath:X.caCertPath,verbose:$.verbose});let z=f8();try{TB(`security add-trusted-cert ${v1} -k "${z}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(_Y(`security add-trusted-cert ${v1} -k ${c1} "${X.caCertPath}"`),$.verbose)R.success("Successfully added Root CA to system trust store");j=!0;let G=K0(A,"trust-rpx-cert.sh"),K=`#!/bin/bash
184
184
  echo "Trusting RPX Root CA"
185
- sudo security add-trusted-cert ${u1} -k ${v1} "${X.caCertPath}"
185
+ sudo security add-trusted-cert ${v1} -k ${c1} "${X.caCertPath}"
186
186
  echo "Root CA trusted! Please restart your browser."
187
187
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
188
188
  `;await G0.writeFile(G,K,{mode:493})}catch(z){if($.verbose)R.warn(`Could not add Root CA to trust store automatically: ${z}`);let G=K0(A,"trust-rpx-cert.sh"),K=`#!/bin/bash
189
189
  echo "Trusting RPX Root CA"
190
- sudo security add-trusted-cert ${u1} -k ${v1} "${X.caCertPath}"
190
+ sudo security add-trusted-cert ${v1} -k ${c1} "${X.caCertPath}"
191
191
  echo "Root CA trusted! Please restart your browser."
192
192
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
193
193
  `;if(await G0.writeFile(G,K,{mode:493}),$.verbose)R.info(`Created a trust helper script at: ${G}`),R.info(`If you're still having certificate issues, run: sh ${G}`)}else if(Hw.platform==="linux")try{let{exec:z}=await import("node:child_process"),G="/usr/local/share/ca-certificates/rpx",K=`
@@ -202,41 +202,41 @@ $store.Open("ReadWrite")
202
202
  $store.Add($cert)
203
203
  $store.Close()
204
204
  Write-Host "Root CA trusted successfully!"
205
- `,G=K0(HB.tmpdir(),"rpx-trust.ps1");if(await G0.writeFile(G,z),TB(`powershell -ExecutionPolicy Bypass -File "${G}"`),$.verbose)R.success("Successfully added certificate to Windows trust store");j=!0}catch(z){if($.verbose)R.warn(`Could not trust certificate: ${z}`)}else try{await fW(B,J.certificate,Y),j=!0}catch(z){if($.verbose)R.warn(`Could not add certificate to trust store: ${z}`)}if(fw={key:B.privateKey,cert:B.certificate,ca:J.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!j&&$.verbose)R.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),R.warn("This will bypass the warning and you should only need to do it once")}function I8(){fw=null}async function Yw($){if(!$)return null;if(fw)return fw;let w=ZY($);try{let[Y,A,X]=await Promise.all([G0.access(w.keyPath).then(()=>!0).catch(()=>!1),G0.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?G0.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return N("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let J="regenerateUntrustedCerts"in $,U=$.regenerateUntrustedCerts,B=J?U!==!1:!0;N("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${B}`,$.verbose);let W=w.basePath||K0(c1(),".stacks","ssl"),j=T5(W);if(!(B?await R5(j.caCertPath,$):!0))return N("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[G,K,F]=await Promise.all([G0.readFile(w.keyPath,"utf8"),G0.readFile(w.certPath,"utf8"),X&&w.caCertPath?G0.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return N("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(vw($))try{let{X509Certificate:T}=await import("node:crypto"),E=new T(K).subjectAltName||"",M=$.proxies.map((Q)=>Q.to).filter((Q)=>!E.includes(`DNS:${Q}`));if(M.length>0)return N("ssl",`Certificate missing SANs for: ${M.join(", ")}, will regenerate`,$.verbose),null}catch(T){N("ssl",`Could not verify cert SANs: ${T}`,$.verbose)}return N("ssl","Successfully loaded existing certificates",$.verbose),fw={key:G,cert:K,ca:F},fw}catch(Y){return N("ssl",`Error checking existing certificates: ${Y}`,$.verbose),null}}function ZY($,w){let Y=T8($);N("ssl",`Primary domain: ${Y}`,w);let A=H5($),X=K0(c1(),".stacks","ssl");if(typeof $.https==="object"){let J=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:$.https.caCertPath||A.caCertPath,certPath:$.https.certPath||A.certPath,keyPath:$.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||Y,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(q5($)).map((B)=>({type:2,value:B}))};if(jB($.https.rootCA))U.rootCA=$.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:w||!1,subjectAltNames:Array.from(q5($)).map((J)=>({type:2,value:J}))}}async function f5($,w){let Y=H5({to:$,verbose:w}),A=[Y.caCertPath,Y.certPath,Y.keyPath];N("certificates","Attempting to clean up relating certificates",w),await Promise.all(A.map((X)=>GB(X,w)))}async function R5($,w){try{if(N("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),Hw.platform==="darwin"){if(w?.serverName)return qB($,w.serverName,{verbose:w?.verbose});return R8($,{verbose:w?.verbose})}else if(Hw.platform==="win32")try{let Y=CW($)||"";if(!Y)return N("ssl","Could not extract certificate subject",w?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(TB(A).toString().includes(Y))return N("ssl","Certificate found in trusted root store",w?.verbose),!0;return N("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(Y){return N("ssl",`Error checking certificate trust on Windows: ${Y}`,w?.verbose),!1}else if(Hw.platform==="linux")try{let Y=xw($);if(!Y)return N("ssl","Could not extract certificate fingerprint",w?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await G0.readdir(X)}catch{continue}for(let U of J){let B=xw(E5.join(X,U));if(B&&B===Y)return N("ssl",`Certificate fingerprint found in ${X}`,w?.verbose),!0}}return N("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(Y){return N("ssl",`Error checking certificate trust on Linux: ${Y}`,w?.verbose),!1}return N("ssl",`Platform ${Hw.platform} not supported for certificate trust check`,w?.verbose),!1}catch(Y){return N("ssl",`Error checking if certificate is trusted: ${Y}`,w?.verbose),!1}}var fw=null,M8,mf="rpx-root-ca.crt",gf="rpx-root-ca.key";var V8=t(()=>{bX();i$();VW();EB();X0();EB();vX();vX();M8=K0(c1(),".stacks","ssl","rpx.localhost.crt")});function lf($){return{enabled:$?.enabled??!1,path:$?.path??"/",interval:$?.interval??1e4,timeout:$?.timeout??2000,healthyThreshold:$?.healthyThreshold??2,unhealthyThreshold:$?.unhealthyThreshold??3}}function nf($){return(Array.isArray($)?$:[$]).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 Rw($){if(!$)return"localhost:5173";let w=Array.isArray($)?$[0]:$;if(!w)return"localhost:5173";return typeof w==="string"?w:w.url}function m1($,w){return{upstreams:nf($),strategy:w?.strategy??"round-robin",healthCheck:lf(w?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function pf($){let w=$.upstreams.filter((Y)=>Y.healthy);if(w.length===0&&$.upstreams.length===1)return $.upstreams;return w}function rf($,w){let Y=$.cursor%w.length;return $.cursor=($.cursor+1)%w.length,w[Y]}function tf($,w){if($.wrrCurrentWeights.length!==w.length)$.wrrCurrentWeights=w.map(()=>0);let Y=w.reduce((X,J)=>X+J.weight,0),A=0;for(let X=0;X<w.length;X++)if($.wrrCurrentWeights[X]+=w[X].weight,$.wrrCurrentWeights[X]>$.wrrCurrentWeights[A])A=X;return $.wrrCurrentWeights[A]-=Y,w[A]}function af($){let w=$[0];for(let Y=1;Y<$.length;Y++)if($[Y].activeConnections<w.activeConnections)w=$[Y];return w}function M5($){let w=pf($);if(w.length===0)return;if(w.length===1)return w[0];switch($.strategy){case"weighted-round-robin":return tf($,w);case"least-connections":return af(w);case"round-robin":default:return rf($,w)}}function C8($,w){if(w.consecutiveFailures=0,w.consecutiveSuccesses+=1,!w.healthy&&w.consecutiveSuccesses>=$.healthCheck.healthyThreshold)w.healthy=!0}function hY($,w){if(w.consecutiveSuccesses=0,w.consecutiveFailures+=1,w.healthy&&w.consecutiveFailures>=$.healthCheck.unhealthyThreshold)w.healthy=!1}function sf($){let w=$.lastIndexOf(":");if(w===-1)return{hostname:$,port:80};let Y=Number($.slice(w+1));return{hostname:$.slice(0,w),port:Number.isFinite(Y)?Y:80}}async function of($,w){let{hostname:Y,port:A}=sf(w.url),X=new AbortController,J=setTimeout(()=>X.abort(),$.healthCheck.timeout);try{(await fetch(`http://${Y}:${A}${$.healthCheck.path}`,{signal:X.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),C8($,w)}catch{hY($,w)}finally{clearTimeout(J)}}function g1($){if(!$.healthCheck.enabled||$.healthCheckTimer||$.upstreams.length<2)return;let w=setInterval(()=>{for(let Y of $.upstreams)of($,Y)},$.healthCheck.interval);w.unref?.(),$.healthCheckTimer=w}function d1($){if($.healthCheckTimer)clearInterval($.healthCheckTimer),$.healthCheckTimer=null}import{createHash as V5,timingSafeEqual as I5}from"node:crypto";import{readFileSync as ef}from"node:fs";function kY($,w){let Y=Buffer.from($,"utf8"),A=Buffer.from(w,"utf8");if(Y.length!==A.length)return I5(Y,Y),!1;return I5(Y,A)}function wR($,w){let Y=(K)=>V5("md5").update(K).digest(),A=Buffer.from($,"utf8"),X=Buffer.from(w,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let K=A.length;K>0;K-=16)U.push(J.subarray(0,Math.min(K,16)));for(let K=A.length;K>0;K>>=1)U.push(K&1?Buffer.from([0]):A.subarray(0,1));let B=Y(Buffer.concat(U));for(let K=0;K<1000;K++){let F=[];if(F.push(K&1?A:B.subarray(0,16)),K%3)F.push(X);if(K%7)F.push(A);F.push(K&1?B.subarray(0,16):A),B=Y(Buffer.concat(F))}let W="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",j=(K,F)=>{let T="",q=K;for(let E=0;E<F;E++)T+=W[q&63],q>>=6;return T},z=B,G="";return G+=j(z[0]<<16|z[6]<<8|z[12],4),G+=j(z[1]<<16|z[7]<<8|z[13],4),G+=j(z[2]<<16|z[8]<<8|z[14],4),G+=j(z[3]<<16|z[9]<<8|z[15],4),G+=j(z[4]<<16|z[10]<<8|z[5],4),G+=j(z[11],2),`$apr1$${w}$${G}`}function YR($,w){if(/^\$2[aby]?\$/.test(w))try{return Bun.password.verifySync($,w)}catch{return!1}if(w.startsWith("$apr1$")){let A=w.split("$")[2]??"";return kY(wR($,A),w)}if(w.startsWith("{SHA}")){let Y=V5("sha1").update($,"utf8").digest("base64");return kY(`{SHA}${Y}`,w)}return kY($,w)}function AR($){let w=new Map;for(let Y of $.split(`
206
- `)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;w.set(A.slice(0,X),A.slice(X+1))}return w}function l1($){if(!$)return;let w=($.realm??"").trim()||"Restricted",Y=[];if($.username)Y.push({username:$.username,password:$.password??""});for(let J of $.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if($.htpasswdFile)try{A=AR(ef($.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:w,verify:(J,U)=>{let B=!1;for(let W of Y)if(kY(J,W.username)&&kY(U,W.password))B=!0;if(A){let W=A.get(J);if(W&&YR(U,W))B=!0}return B}}}function C5($,w,Y){if(w.startsWith($R))return;let A=$.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 j=W.indexOf(":");if(j>=0&&Y.verify(W.slice(0,j),W.slice(j+1)))return}let B=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${B}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var $R="/.well-known/acme-challenge/";var DY=()=>{};function UR($){return JR.has($.toUpperCase())}function WR(){let $=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite($)&&$>0?$:30000}function BR($){let w=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(w)&&w>0?w:$*8}function jR(){let $=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite($)&&$>0?$:0}function zR(){let $=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite($)&&$>0?$:0}function GR(){let $=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite($)&&$>0?$:256}class _5{socket=null;buf=new Uint8Array(KR);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll($){let w=this.socket,Y=w.write($);while(Y<$.length){if(this.closed)throw Q8;await new Promise((A)=>{this.drainWaiter=A}),Y+=w.write($.subarray(Y))}}wakeDrain(){let $=this.drainWaiter;if($)this.drainWaiter=null,$()}push($){if(this.bodyQueue){let w=$.length<=this.bodyRemaining?$.length:this.bodyRemaining;if(w>0)this.bodyQueue.push($.slice(0,w)),this.queuedBytes+=w;if(this.bodyRemaining-=w,w<$.length)this.appendToBuf($.subarray(w));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf($),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>FR)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=NR)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf($){let w=this.len+$.length;if(w>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,w));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set($,this.len),this.len=w}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let $=this.waiter;if($)this.waiter=null,$()}waitForData($){if(this.len>$||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class S5{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=WR();maxWaiters;checkoutIdleMs=jR();inUse=new Set;constructor($,w,Y,A=""){this.host=$;this.port=w;this.maxTotal=Y;this.key=A;this.maxWaiters=BR(Y)}trackCheckout($){if($.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add($),this.ensureSweeper()}dial(){let $=new _5;return XR({hostname:this.host,port:this.port,socket:{data:(w,Y)=>$.push(Y),drain:()=>$.wakeDrain(),close:()=>$.markClosed(),end:()=>$.markClosed(),error:()=>$.markClosed(),connectError:()=>$.markClosed(),timeout:()=>$.markTimedOut()}}).then((w)=>{let Y=w;Y.setNoDelay?.(!0);let A=zR();if(A>0)Y.timeout?.(A);return $.socket=w,$})}acquireIdleSync(){while(this.idle.length){let $=this.idle.pop();if(!$.closed)return $.socket?.ref(),$.pos=0,$.len=0,this.trackCheckout($),$;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw cw;let $=await this.waitForSlot();if($===cw)throw cw;if($)return $.pos=0,$.len=0,this.trackCheckout($),$}this.open++;try{let $=await this.dial();return this.trackCheckout($),$}catch($){throw this.open--,this.wakeWaiter(),$}}waitForSlot(){return new Promise(($)=>{let w=!1,Y=(J)=>{if(w)return;w=!0,clearTimeout(X),$(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(cw)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release($){if(this.inUse.delete($),$.closed){this.open--,this.wakeWaiter();return}$.clearStreaming(),$.compact(),$.fresh=!1;let w=this.waiters.shift();if(w){$.socket?.ref(),this.trackCheckout($),w($);return}$.idleSince=Date.now(),$.socket?.unref(),this.idle.push($),this.ensureSweeper()}destroy($){this.inUse.delete($),$.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let $=this.waiters.shift();if($)$(null)}ensureSweeper(){if(this.sweeper)return;let $=this.checkoutIdleMs>0?Math.min(MB,this.checkoutIdleMs):MB;this.sweeper=setInterval(()=>this.sweep(),$),this.sweeper.unref?.()}sweep(){let $=Date.now(),w=$-MB;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=w)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=$-this.checkoutIdleMs;for(let A of this.inUse)if(!A.closed&&A.lastActivityAt>0&&A.lastActivityAt<=Y)A.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&y8.get(this.key)===this)y8.delete(this.key)}}}function fR($,w){let Y=y8.get($);if(!Y){let A=$.lastIndexOf(":"),X=A===-1?$:$.slice(0,A),J=A===-1?80:Number($.slice(A+1));Y=new S5(X,J,w,$),y8.set($,Y)}return Y}function Q5($,w,Y){for(let A=Y+3;A<w;A++)if($[A]===10&&$[A-1]===13&&$[A-2]===10&&$[A-3]===13)return A-3;return-1}function RR($,w,Y){let A=O5.decode($.subarray(w,Y)),X=A.indexOf(`\r
205
+ `,G=K0(HB.tmpdir(),"rpx-trust.ps1");if(await G0.writeFile(G,z),TB(`powershell -ExecutionPolicy Bypass -File "${G}"`),$.verbose)R.success("Successfully added certificate to Windows trust store");j=!0}catch(z){if($.verbose)R.warn(`Could not trust certificate: ${z}`)}else try{await fW(B,J.certificate,Y),j=!0}catch(z){if($.verbose)R.warn(`Could not add certificate to trust store: ${z}`)}if(fw={key:B.privateKey,cert:B.certificate,ca:J.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!j&&$.verbose)R.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),R.warn("This will bypass the warning and you should only need to do it once")}function I8(){fw=null}async function Yw($){if(!$)return null;if(fw)return fw;let w=ZY($);try{let[Y,A,X]=await Promise.all([G0.access(w.keyPath).then(()=>!0).catch(()=>!1),G0.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?G0.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return N("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let J="regenerateUntrustedCerts"in $,U=$.regenerateUntrustedCerts,B=J?U!==!1:!0;N("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${B}`,$.verbose);let W=w.basePath||K0(i1(),".stacks","ssl"),j=H5(W);if(!(B?await M5(j.caCertPath,$):!0))return N("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[G,K,F]=await Promise.all([G0.readFile(w.keyPath,"utf8"),G0.readFile(w.certPath,"utf8"),X&&w.caCertPath?G0.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return N("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(vw($))try{let{X509Certificate:T}=await import("node:crypto"),E=new T(K).subjectAltName||"",M=$.proxies.map((Q)=>Q.to).filter((Q)=>!E.includes(`DNS:${Q}`));if(M.length>0)return N("ssl",`Certificate missing SANs for: ${M.join(", ")}, will regenerate`,$.verbose),null}catch(T){N("ssl",`Could not verify cert SANs: ${T}`,$.verbose)}return N("ssl","Successfully loaded existing certificates",$.verbose),fw={key:G,cert:K,ca:F},fw}catch(Y){return N("ssl",`Error checking existing certificates: ${Y}`,$.verbose),null}}function ZY($,w){let Y=T8($);N("ssl",`Primary domain: ${Y}`,w);let A=f5($),X=K0(i1(),".stacks","ssl");if(typeof $.https==="object"){let J=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:$.https.caCertPath||A.caCertPath,certPath:$.https.certPath||A.certPath,keyPath:$.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||Y,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(E5($)).map((B)=>({type:2,value:B}))};if(jB($.https.rootCA))U.rootCA=$.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:w||!1,subjectAltNames:Array.from(E5($)).map((J)=>({type:2,value:J}))}}async function R5($,w){let Y=f5({to:$,verbose:w}),A=[Y.caCertPath,Y.certPath,Y.keyPath];N("certificates","Attempting to clean up relating certificates",w),await Promise.all(A.map((X)=>GB(X,w)))}async function M5($,w){try{if(N("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),Hw.platform==="darwin"){if(w?.serverName)return qB($,w.serverName,{verbose:w?.verbose});return R8($,{verbose:w?.verbose})}else if(Hw.platform==="win32")try{let Y=CW($)||"";if(!Y)return N("ssl","Could not extract certificate subject",w?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(TB(A).toString().includes(Y))return N("ssl","Certificate found in trusted root store",w?.verbose),!0;return N("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(Y){return N("ssl",`Error checking certificate trust on Windows: ${Y}`,w?.verbose),!1}else if(Hw.platform==="linux")try{let Y=xw($);if(!Y)return N("ssl","Could not extract certificate fingerprint",w?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await G0.readdir(X)}catch{continue}for(let U of J){let B=xw(T5.join(X,U));if(B&&B===Y)return N("ssl",`Certificate fingerprint found in ${X}`,w?.verbose),!0}}return N("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(Y){return N("ssl",`Error checking certificate trust on Linux: ${Y}`,w?.verbose),!1}return N("ssl",`Platform ${Hw.platform} not supported for certificate trust check`,w?.verbose),!1}catch(Y){return N("ssl",`Error checking if certificate is trusted: ${Y}`,w?.verbose),!1}}var fw=null,M8,gf="rpx-root-ca.crt",df="rpx-root-ca.key";var V8=t(()=>{bX();i$();VW();EB();X0();EB();vX();vX();M8=K0(i1(),".stacks","ssl","rpx.localhost.crt")});function nf($){return{enabled:$?.enabled??!1,path:$?.path??"/",interval:$?.interval??1e4,timeout:$?.timeout??2000,healthyThreshold:$?.healthyThreshold??2,unhealthyThreshold:$?.unhealthyThreshold??3}}function pf($){return(Array.isArray($)?$:[$]).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 MB($){return(Array.isArray($)?$:[$]).map((Y)=>typeof Y==="string"?Y:Y.url)}function Rw($){if(!$)return"localhost:5173";let w=Array.isArray($)?$[0]:$;if(!w)return"localhost:5173";return typeof w==="string"?w:w.url}function g1($,w){return{upstreams:pf($),strategy:w?.strategy??"round-robin",healthCheck:nf(w?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function rf($){let w=$.upstreams.filter((Y)=>Y.healthy);if(w.length===0&&$.upstreams.length===1)return $.upstreams;return w}function tf($,w){let Y=$.cursor%w.length;return $.cursor=($.cursor+1)%w.length,w[Y]}function af($,w){if($.wrrCurrentWeights.length!==w.length)$.wrrCurrentWeights=w.map(()=>0);let Y=w.reduce((X,J)=>X+J.weight,0),A=0;for(let X=0;X<w.length;X++)if($.wrrCurrentWeights[X]+=w[X].weight,$.wrrCurrentWeights[X]>$.wrrCurrentWeights[A])A=X;return $.wrrCurrentWeights[A]-=Y,w[A]}function sf($){let w=$[0];for(let Y=1;Y<$.length;Y++)if($[Y].activeConnections<w.activeConnections)w=$[Y];return w}function I5($){let w=rf($);if(w.length===0)return;if(w.length===1)return w[0];switch($.strategy){case"weighted-round-robin":return af($,w);case"least-connections":return sf(w);case"round-robin":default:return tf($,w)}}function C8($,w){if(w.consecutiveFailures=0,w.consecutiveSuccesses+=1,!w.healthy&&w.consecutiveSuccesses>=$.healthCheck.healthyThreshold)w.healthy=!0}function hY($,w){if(w.consecutiveSuccesses=0,w.consecutiveFailures+=1,w.healthy&&w.consecutiveFailures>=$.healthCheck.unhealthyThreshold)w.healthy=!1}function of($){let w=$.lastIndexOf(":");if(w===-1)return{hostname:$,port:80};let Y=Number($.slice(w+1));return{hostname:$.slice(0,w),port:Number.isFinite(Y)?Y:80}}async function ef($,w){let{hostname:Y,port:A}=of(w.url),X=new AbortController,J=setTimeout(()=>X.abort(),$.healthCheck.timeout);try{(await fetch(`http://${Y}:${A}${$.healthCheck.path}`,{signal:X.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),C8($,w)}catch{hY($,w)}finally{clearTimeout(J)}}function d1($){if(!$.healthCheck.enabled||$.healthCheckTimer||$.upstreams.length<2)return;let w=setInterval(()=>{for(let Y of $.upstreams)ef($,Y)},$.healthCheck.interval);w.unref?.(),$.healthCheckTimer=w}function cw($){if($.healthCheckTimer)clearInterval($.healthCheckTimer),$.healthCheckTimer=null}import{createHash as C5,timingSafeEqual as V5}from"node:crypto";import{readFileSync as $R}from"node:fs";function DY($,w){let Y=Buffer.from($,"utf8"),A=Buffer.from(w,"utf8");if(Y.length!==A.length)return V5(Y,Y),!1;return V5(Y,A)}function YR($,w){let Y=(K)=>C5("md5").update(K).digest(),A=Buffer.from($,"utf8"),X=Buffer.from(w,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let K=A.length;K>0;K-=16)U.push(J.subarray(0,Math.min(K,16)));for(let K=A.length;K>0;K>>=1)U.push(K&1?Buffer.from([0]):A.subarray(0,1));let B=Y(Buffer.concat(U));for(let K=0;K<1000;K++){let F=[];if(F.push(K&1?A:B.subarray(0,16)),K%3)F.push(X);if(K%7)F.push(A);F.push(K&1?B.subarray(0,16):A),B=Y(Buffer.concat(F))}let W="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",j=(K,F)=>{let T="",q=K;for(let E=0;E<F;E++)T+=W[q&63],q>>=6;return T},z=B,G="";return G+=j(z[0]<<16|z[6]<<8|z[12],4),G+=j(z[1]<<16|z[7]<<8|z[13],4),G+=j(z[2]<<16|z[8]<<8|z[14],4),G+=j(z[3]<<16|z[9]<<8|z[15],4),G+=j(z[4]<<16|z[10]<<8|z[5],4),G+=j(z[11],2),`$apr1$${w}$${G}`}function AR($,w){if(/^\$2[aby]?\$/.test(w))try{return Bun.password.verifySync($,w)}catch{return!1}if(w.startsWith("$apr1$")){let A=w.split("$")[2]??"";return DY(YR($,A),w)}if(w.startsWith("{SHA}")){let Y=C5("sha1").update($,"utf8").digest("base64");return DY(`{SHA}${Y}`,w)}return DY($,w)}function XR($){let w=new Map;for(let Y of $.split(`
206
+ `)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;w.set(A.slice(0,X),A.slice(X+1))}return w}function l1($){if(!$)return;let w=($.realm??"").trim()||"Restricted",Y=[];if($.username)Y.push({username:$.username,password:$.password??""});for(let J of $.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if($.htpasswdFile)try{A=XR($R($.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:w,verify:(J,U)=>{let B=!1;for(let W of Y)if(DY(J,W.username)&&DY(U,W.password))B=!0;if(A){let W=A.get(J);if(W&&AR(U,W))B=!0}return B}}}function Q5($,w,Y){if(w.startsWith(wR))return;let A=$.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 j=W.indexOf(":");if(j>=0&&Y.verify(W.slice(0,j),W.slice(j+1)))return}let B=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${B}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var wR="/.well-known/acme-challenge/";var kY=()=>{};function WR($){return UR.has($.toUpperCase())}function BR(){let $=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite($)&&$>0?$:30000}function jR($){let w=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(w)&&w>0?w:$*8}function zR(){let $=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite($)&&$>0?$:0}function GR(){let $=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite($)&&$>0?$:0}function KR(){let $=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite($)&&$>0?$:256}class S5{socket=null;buf=new Uint8Array(FR);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll($){let w=this.socket,Y=w.write($);while(Y<$.length){if(this.closed)throw Q8;await new Promise((A)=>{this.drainWaiter=A}),Y+=w.write($.subarray(Y))}}wakeDrain(){let $=this.drainWaiter;if($)this.drainWaiter=null,$()}push($){if(this.bodyQueue){let w=$.length<=this.bodyRemaining?$.length:this.bodyRemaining;if(w>0)this.bodyQueue.push($.slice(0,w)),this.queuedBytes+=w;if(this.bodyRemaining-=w,w<$.length)this.appendToBuf($.subarray(w));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf($),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>NR)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=qR)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf($){let w=this.len+$.length;if(w>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,w));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set($,this.len),this.len=w}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let $=this.waiter;if($)this.waiter=null,$()}waitForData($){if(this.len>$||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class Z5{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=BR();maxWaiters;checkoutIdleMs=zR();inUse=new Set;constructor($,w,Y,A=""){this.host=$;this.port=w;this.maxTotal=Y;this.key=A;this.maxWaiters=jR(Y)}trackCheckout($){if($.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add($),this.ensureSweeper()}dial(){let $=new S5;return JR({hostname:this.host,port:this.port,socket:{data:(w,Y)=>$.push(Y),drain:()=>$.wakeDrain(),close:()=>$.markClosed(),end:()=>$.markClosed(),error:()=>$.markClosed(),connectError:()=>$.markClosed(),timeout:()=>$.markTimedOut()}}).then((w)=>{let Y=w;Y.setNoDelay?.(!0);let A=GR();if(A>0)Y.timeout?.(A);return $.socket=w,$})}acquireIdleSync(){while(this.idle.length){let $=this.idle.pop();if(!$.closed)return $.socket?.ref(),$.pos=0,$.len=0,this.trackCheckout($),$;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw iw;let $=await this.waitForSlot();if($===iw)throw iw;if($)return $.pos=0,$.len=0,this.trackCheckout($),$}this.open++;try{let $=await this.dial();return this.trackCheckout($),$}catch($){throw this.open--,this.wakeWaiter(),$}}waitForSlot(){return new Promise(($)=>{let w=!1,Y=(J)=>{if(w)return;w=!0,clearTimeout(X),$(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(iw)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release($){if(this.inUse.delete($),$.closed){this.open--,this.wakeWaiter();return}$.clearStreaming(),$.compact(),$.fresh=!1;let w=this.waiters.shift();if(w){$.socket?.ref(),this.trackCheckout($),w($);return}$.idleSince=Date.now(),$.socket?.unref(),this.idle.push($),this.ensureSweeper()}destroy($){this.inUse.delete($),$.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let $=this.waiters.shift();if($)$(null)}ensureSweeper(){if(this.sweeper)return;let $=this.checkoutIdleMs>0?Math.min(IB,this.checkoutIdleMs):IB;this.sweeper=setInterval(()=>this.sweep(),$),this.sweeper.unref?.()}sweep(){let $=Date.now(),w=$-IB;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=w)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=$-this.checkoutIdleMs;for(let A of this.inUse)if(!A.closed&&A.lastActivityAt>0&&A.lastActivityAt<=Y)A.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&y8.get(this.key)===this)y8.delete(this.key)}}}function RR($,w){let Y=y8.get($);if(!Y){let A=$.lastIndexOf(":"),X=A===-1?$:$.slice(0,A),J=A===-1?80:Number($.slice(A+1));Y=new Z5(X,J,w,$),y8.set($,Y)}return Y}function y5($,w,Y){for(let A=Y+3;A<w;A++)if($[A]===10&&$[A-1]===13&&$[A-2]===10&&$[A-3]===13)return A-3;return-1}function MR($,w,Y){let A=_5.decode($.subarray(w,Y)),X=A.indexOf(`\r
207
207
  `),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),B=Number.parseInt(J.slice(U+1,U+5),10),W=J.startsWith("HTTP/1.0"),j=[],z=-1,G=!1,K=W,F=!1,T=!1,q=X===-1?A.length:X+2;while(q<A.length){let E=A.indexOf(`\r
208
- `,q);if(E===-1)E=A.length;let f=A.slice(q,E);if(q=E+2,f==="")continue;let M=f.indexOf(":");if(M===-1)continue;let Q=f.slice(0,M),V=f.slice(M+1).trim(),H=Q.charCodeAt(0)|32;if(H===99||H===116||H===107){let I=Q.toLowerCase();if(I==="content-length"){let O=/^\d+$/.test(V)?Number(V):Number.NaN;if(!Number.isSafeInteger(O)||z>=0&&z!==O)T=!0;else z=O;continue}if(I==="transfer-encoding"){if(V.toLowerCase().includes("chunked"))G=!0;continue}if(I==="connection"){let O=V.toLowerCase();if(O.includes("close"))K=!0;if(O.includes("keep-alive"))F=!0;continue}if(I==="keep-alive")continue}j.push([Q,V])}if(W&&F)K=!1;if(G&&z>=0)z=-1;return{status:B,headerEnd:Y,headers:j,contentLength:z,chunked:G,closeConn:K,malformed:T}}function MR($,w){return w||$===204||$===304}async function Z5($){let{hostPort:w,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:B}=$,W=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw xY;let j=null;if(B){let F=X.get("content-length"),T=F?Number.parseInt(F,10):Number.NaN;if(Number.isNaN(T)||T>y5)throw xY;if(j=await OR(B),j===null)throw xY}let z=LR(Y,A,X,w,J,U,j),G=z;if(j&&j.length)G=new Uint8Array(z.length+j.length),G.set(z),G.set(j,z.length);let K=fR(w,$.maxPerHost??GR());for(let F=0;;F++){if(F>0)await new Promise((q)=>{setTimeout(q,F)});let T;try{T=K.acquireIdleSync()??await K.acquireOrDial()}catch(q){if(q!==cw&&F<4)continue;throw q}try{let q=T.socket.write(G);if(q<G.length)await T.writeAll(G.subarray(q));return await VR(K,T,W)}catch(q){let E=q===Q8&&F<4&&(T.fresh||UR(Y));if(K.destroy(T),E)continue;if(q===Q8)throw Error("upstream closed connection");throw q}}}async function IR($){let w=Q5($.buf,$.len,$.pos);while(w===-1){if($.closed){if($.timedOut)throw IB;if($.len===$.pos)throw Q8;throw Error("upstream closed mid-header")}if($.len-$.pos>L5)throw Error("upstream header block too large");await $.waitForData($.len),w=Q5($.buf,$.len,$.pos)}return w}async function VR($,w,Y){let A;for(;;){let J=await IR(w);if(A=RR(w.buf,w.pos,J),w.pos=J+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw $.destroy(w),Error("upstream sent malformed response framing");let X=A.headers;if(MR(A.status,Y))return h5($,w,A.closeConn),new Response(null,{status:A.status,headers:X});if(A.chunked)return new Response(yR($,w,A.closeConn),{status:A.status,headers:X});if(A.contentLength>=0){if(w.len-w.pos>=A.contentLength){let U=w.pos+A.contentLength,B=w.len>U,W=null;if(A.contentLength>=qR)W=w.buf.subarray(w.pos,U),w.buf=new Uint8Array(ER);else if(A.contentLength>0)W=w.buf.slice(w.pos,U);if(w.pos=0,w.len=0,A.closeConn||B)$.destroy(w);else $.release(w);return new Response(W,{status:A.status,headers:X})}return new Response(CR($,w,A.contentLength,A.closeConn),{status:A.status,headers:X})}return new Response(QR(w),{status:A.status,headers:X})}function h5($,w,Y){if(Y||w.pos!==w.len)$.destroy(w);else $.release(w)}function CR($,w,Y,A){let X=w.len-w.pos,J=X>0?w.buf.slice(w.pos,w.len):null;w.pos=0,w.len=0,w.bodyQueue=[],w.bodyRemaining=Y-X,w.queuedBytes=0,w.streamingBody=!0;let U=(B)=>{if(w.bodyQueue=null,A||w.len>0)$.destroy(w);else $.release(w);B.close()};return new ReadableStream({start(B){if(J)B.enqueue(J);if(w.bodyRemaining===0&&w.bodyQueue.length===0)U(B)},async pull(B){for(;;){let W=w.bodyQueue;if(W&&W.length>0){let j=W.shift();if(w.queuedBytes-=j.length,w.resumeIfDrained(),B.enqueue(j),w.bodyRemaining===0&&W.length===0)U(B);return}if(w.bodyRemaining===0){if(w.bodyQueue)U(B);return}if(w.closed){w.bodyQueue=null,$.destroy(w),B.error(Error("upstream closed mid-body"));return}await w.waitForBody()}},cancel(){w.bodyQueue=null,$.destroy(w)}})}function QR($){return $.streamingBody=!0,new ReadableStream({async pull(w){for(;;){if($.len>$.pos){w.enqueue($.buf.slice($.pos,$.len)),$.pos=$.len,$.resumeIfDrained();return}if($.closed){$.destroy(),w.close();return}await $.waitForData($.len)}},cancel(){$.destroy()}})}function yR($,w,Y){w.streamingBody=!0;let A=0,X=!1;async function J(){for(;;){for(let U=w.pos;U+1<w.len;U++)if(w.buf[U]===13&&w.buf[U+1]===10){let B=O5.decode(w.buf.subarray(w.pos,U));return w.pos=U+2,B}if(w.closed)throw Error("upstream closed mid-chunk-header");if(w.len-w.pos>L5)throw Error("upstream chunk header too large");await w.waitForData(w.len)}}return new ReadableStream({async pull(U){for(;;){if(A>0){if(w.len===w.pos){if(w.closed){$.destroy(w),U.error(Error("upstream closed mid-chunk"));return}await w.waitForData(w.len);continue}let z=Math.min(A,w.len-w.pos);if(U.enqueue(w.buf.slice(w.pos,w.pos+z)),w.pos+=z,A-=z,w.resumeIfDrained(),A===0)X=!0;return}if(X)await J(),X=!1;let B=await J(),W=B.indexOf(";"),j=Number.parseInt(W===-1?B:B.slice(0,W),16);if(!Number.isInteger(j)||j<0){$.destroy(w),U.error(Error("upstream sent malformed chunk size"));return}if(j===0){for(;;)if(await J()==="")break;h5($,w,Y),U.close();return}A=j}},cancel(){$.destroy(w)}})}function LR($,w,Y,A,X,J,U){let B=`${$} ${w} HTTP/1.1\r
208
+ `,q);if(E===-1)E=A.length;let f=A.slice(q,E);if(q=E+2,f==="")continue;let M=f.indexOf(":");if(M===-1)continue;let Q=f.slice(0,M),V=f.slice(M+1).trim(),H=Q.charCodeAt(0)|32;if(H===99||H===116||H===107){let I=Q.toLowerCase();if(I==="content-length"){let O=/^\d+$/.test(V)?Number(V):Number.NaN;if(!Number.isSafeInteger(O)||z>=0&&z!==O)T=!0;else z=O;continue}if(I==="transfer-encoding"){if(V.toLowerCase().includes("chunked"))G=!0;continue}if(I==="connection"){let O=V.toLowerCase();if(O.includes("close"))K=!0;if(O.includes("keep-alive"))F=!0;continue}if(I==="keep-alive")continue}j.push([Q,V])}if(W&&F)K=!1;if(G&&z>=0)z=-1;return{status:B,headerEnd:Y,headers:j,contentLength:z,chunked:G,closeConn:K,malformed:T}}function IR($,w){return w||$===204||$===304}async function h5($){let{hostPort:w,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:B}=$,W=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw xY;let j=null;if(B){let F=X.get("content-length"),T=F?Number.parseInt(F,10):Number.NaN;if(Number.isNaN(T)||T>L5)throw xY;if(j=await _R(B),j===null)throw xY}let z=OR(Y,A,X,w,J,U,j),G=z;if(j&&j.length)G=new Uint8Array(z.length+j.length),G.set(z),G.set(j,z.length);let K=RR(w,$.maxPerHost??KR());for(let F=0;;F++){if(F>0)await new Promise((q)=>{setTimeout(q,F)});let T;try{T=K.acquireIdleSync()??await K.acquireOrDial()}catch(q){if(q!==iw&&F<4)continue;throw q}try{let q=T.socket.write(G);if(q<G.length)await T.writeAll(G.subarray(q));return await CR(K,T,W)}catch(q){let E=q===Q8&&F<4&&(T.fresh||WR(Y));if(K.destroy(T),E)continue;if(q===Q8)throw Error("upstream closed connection");throw q}}}async function VR($){let w=y5($.buf,$.len,$.pos);while(w===-1){if($.closed){if($.timedOut)throw VB;if($.len===$.pos)throw Q8;throw Error("upstream closed mid-header")}if($.len-$.pos>O5)throw Error("upstream header block too large");await $.waitForData($.len),w=y5($.buf,$.len,$.pos)}return w}async function CR($,w,Y){let A;for(;;){let J=await VR(w);if(A=MR(w.buf,w.pos,J),w.pos=J+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw $.destroy(w),Error("upstream sent malformed response framing");let X=A.headers;if(IR(A.status,Y))return D5($,w,A.closeConn),new Response(null,{status:A.status,headers:X});if(A.chunked)return new Response(LR($,w,A.closeConn),{status:A.status,headers:X});if(A.contentLength>=0){if(w.len-w.pos>=A.contentLength){let U=w.pos+A.contentLength,B=w.len>U,W=null;if(A.contentLength>=ER)W=w.buf.subarray(w.pos,U),w.buf=new Uint8Array(TR);else if(A.contentLength>0)W=w.buf.slice(w.pos,U);if(w.pos=0,w.len=0,A.closeConn||B)$.destroy(w);else $.release(w);return new Response(W,{status:A.status,headers:X})}return new Response(QR($,w,A.contentLength,A.closeConn),{status:A.status,headers:X})}return new Response(yR(w),{status:A.status,headers:X})}function D5($,w,Y){if(Y||w.pos!==w.len)$.destroy(w);else $.release(w)}function QR($,w,Y,A){let X=w.len-w.pos,J=X>0?w.buf.slice(w.pos,w.len):null;w.pos=0,w.len=0,w.bodyQueue=[],w.bodyRemaining=Y-X,w.queuedBytes=0,w.streamingBody=!0;let U=(B)=>{if(w.bodyQueue=null,A||w.len>0)$.destroy(w);else $.release(w);B.close()};return new ReadableStream({start(B){if(J)B.enqueue(J);if(w.bodyRemaining===0&&w.bodyQueue.length===0)U(B)},async pull(B){for(;;){let W=w.bodyQueue;if(W&&W.length>0){let j=W.shift();if(w.queuedBytes-=j.length,w.resumeIfDrained(),B.enqueue(j),w.bodyRemaining===0&&W.length===0)U(B);return}if(w.bodyRemaining===0){if(w.bodyQueue)U(B);return}if(w.closed){w.bodyQueue=null,$.destroy(w),B.error(Error("upstream closed mid-body"));return}await w.waitForBody()}},cancel(){w.bodyQueue=null,$.destroy(w)}})}function yR($){return $.streamingBody=!0,new ReadableStream({async pull(w){for(;;){if($.len>$.pos){w.enqueue($.buf.slice($.pos,$.len)),$.pos=$.len,$.resumeIfDrained();return}if($.closed){$.destroy(),w.close();return}await $.waitForData($.len)}},cancel(){$.destroy()}})}function LR($,w,Y){w.streamingBody=!0;let A=0,X=!1;async function J(){for(;;){for(let U=w.pos;U+1<w.len;U++)if(w.buf[U]===13&&w.buf[U+1]===10){let B=_5.decode(w.buf.subarray(w.pos,U));return w.pos=U+2,B}if(w.closed)throw Error("upstream closed mid-chunk-header");if(w.len-w.pos>O5)throw Error("upstream chunk header too large");await w.waitForData(w.len)}}return new ReadableStream({async pull(U){for(;;){if(A>0){if(w.len===w.pos){if(w.closed){$.destroy(w),U.error(Error("upstream closed mid-chunk"));return}await w.waitForData(w.len);continue}let z=Math.min(A,w.len-w.pos);if(U.enqueue(w.buf.slice(w.pos,w.pos+z)),w.pos+=z,A-=z,w.resumeIfDrained(),A===0)X=!0;return}if(X)await J(),X=!1;let B=await J(),W=B.indexOf(";"),j=Number.parseInt(W===-1?B:B.slice(0,W),16);if(!Number.isInteger(j)||j<0){$.destroy(w),U.error(Error("upstream sent malformed chunk size"));return}if(j===0){for(;;)if(await J()==="")break;D5($,w,Y),U.close();return}A=j}},cancel(){$.destroy(w)}})}function OR($,w,Y,A,X,J,U){let B=`${$} ${w} HTTP/1.1\r
209
209
  host: ${A}\r
210
210
  x-forwarded-for: 127.0.0.1\r
211
211
  x-forwarded-proto: https\r
212
212
  x-forwarded-host: ${X}\r
213
213
  `;if(J!==void 0)B+=`origin: ${J}\r
214
- `;let W=!1;for(let[j,z]of Y){let G=j.toLowerCase();if(HR.has(G))continue;if(J!==void 0&&G==="origin")continue;if(G==="content-length")W=!0;B+=`${j}: ${z}\r
214
+ `;let W=!1;for(let[j,z]of Y){let G=j.toLowerCase();if(fR.has(G))continue;if(J!==void 0&&G==="origin")continue;if(G==="content-length")W=!0;B+=`${j}: ${z}\r
215
215
  `}if(B+=`connection: keep-alive\r
216
216
  `,U&&!W)B+=`content-length: ${U.length}\r
217
217
  `;return B+=`\r
218
- `,TR.encode(B)}async function OR($){let w=$.getReader(),Y=[],A=0;for(;;){let{done:U,value:B}=await w.read();if(U)break;if(B){if(A+=B.length,A>y5)return w.cancel().catch(()=>{}),null;Y.push(B)}}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 XR,xY,Q8,JR,IB,cw,y5=1048576,MB=30000,KR=16384,L5=262144,FR=2097152,NR=524288,qR=8192,ER=4096,TR,O5,HR,y8;var k5=t(()=>{({connect:XR}=Bun),xY=Symbol("rpx.pool.fallback"),Q8=Symbol("rpx.pool.stale"),JR=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);IB=Symbol("rpx.pool.timeout"),cw=Symbol("rpx.pool.busy");TR=new TextEncoder,O5=new TextDecoder,HR=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);y8=new Map});function D5($){let w=typeof $==="string"?{to:$}:$,Y=(w.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:w.status??301,preservePath:w.preservePath??!0}}function x5($,w,Y){if(!$.preservePath)return $.to||"/";let A=`${w}${Y}`;return A==="/"?`${$.to}/`:`${$.to}${A}`}import*as z$ from"node:path";function PY($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function SR($){let w=z$.extname($).toLowerCase();return _R[w]??"application/octet-stream"}function ZR($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let Y=z$.posix.normalize(`/${w}`);if(Y.includes(".."))return null;return Y.replace(/^\/+/,"")}function hR($,w){let Y=ZR($);if(Y===null)return null;let A=z$.posix.extname(Y);if(w.cleanUrls&&A===".html"){let X=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:z$.join(w.dir,Y),redirectTo:X||"/"}}if(Y===""||$.endsWith("/"))return{filePath:z$.join(w.dir,Y,"index.html")};if(A!=="")return{filePath:z$.join(w.dir,Y)};if(w.pathRewriteStyle==="flat")return{filePath:z$.join(w.dir,`${Y}.html`)};return{filePath:z$.join(w.dir,Y,"index.html")}}async function P5($,w){let Y=hR($,w);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":SR(Y.filePath),"Cache-Control":A}});if(w.spa){let J=z$.join(w.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 _R;var bY=t(()=>{_R={".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 kR(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function xR($){let w=$.headers.get("host")||"",Y=w.indexOf(":");return Y===-1?w:w.slice(0,Y)}function v5($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let Y=$.slice(w.length);return Y===""?"/":Y}return $}function b5($){if($.upstreamPool)return M5($.upstreamPool);if($.sourceHost)return{url:$.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function u5($,w,Y,A){let X=Y?.url??w.sourceHost??"",U=w.stripBasePathPrefix??!1?v5($,w.basePath):$,B=zB(U,w.pathRewrites);if(B)X=B.targetHost,U=B.targetPath,N("request",`Path rewrite: ${$} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function PR($){let w=$.indexOf("://"),Y=w===-1?$.indexOf("/"):$.indexOf("/",w+3);if(Y===-1)return{pathname:"/",search:""};let A=$.indexOf("?",Y);if(A===-1)return{pathname:$.slice(Y),search:""};return{pathname:$.slice(Y,A),search:$.slice(A)}}function n1($,w,Y){let A=async(X,J)=>{let{pathname:U,search:B}=PR(X.url),W=xR(X),j=$(W,U);if(!j&&Y){let E=await Y(W,U,X);if(E instanceof Response)return E;if(E&&E.retry)j=$(W,U)}if(!j)return N("request",`No route found for host: ${W}`,w),new Response(`No proxy configured for ${W}`,{status:404});if(j.auth){let E=C5(X,U,j.auth);if(E)return N("request",`401 challenge for ${W}${U}`,w),E}if(j.redirect){let E=x5(j.redirect,U,B);return N("request",`${j.redirect.status} redirect ${W}${U} → ${E}`,w),new Response(null,{status:j.redirect.status,headers:{location:E}})}if(j.static){let f=j.stripBasePathPrefix??!0?v5(U,j.basePath):U;return P5(f,j.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let E=b5(j);if(!J||!E)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:f,targetPath:M}=u5(U,j,E,w),Q=`ws://${f}${M}${B}`,V={};for(let[O,Z]of X.headers)if(!DR.has(O.toLowerCase())&&O.toLowerCase()!=="host")V[O]=Z;V.host=f,V["x-forwarded-for"]="127.0.0.1",V["x-forwarded-proto"]="https",V["x-forwarded-host"]=W;let H={targetUrl:Q,forwardHeaders:V};if(J.upgrade(X,{data:H})){N("ws",`upgraded ${W}${M} → ${Q}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}let z=b5(j);if(!z)return new Response(`No upstream configured for ${W}`,{status:502});if(j.cleanUrls&&U.endsWith(".html")){let E=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:E}})}let{targetHost:G,targetPath:K}=u5(U,j,z,w),F=j.changeOrigin?`http://${G}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",q=j.upstreamPool;if(q)z.activeConnections++;try{let E=await Z5({hostPort:G,method:X.method,path:`${K}${B}`,reqHeaders:X.headers,forwardedHost:W,originOverride:F,body:X.body});if(q)C8(q,z);return E}catch(E){if(E===IB){if(N("request",`Upstream timeout for ${W}`,w),q)hY(q,z);return new Response("Gateway Timeout",{status:504})}if(E===cw)return N("request",`Upstream pool saturated for ${W}`,w),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(E===xY||!T)try{let f=new Headers(X.headers);if(f.set("host",G),f.set("x-forwarded-for","127.0.0.1"),f.set("x-forwarded-proto","https"),f.set("x-forwarded-host",W),F!==void 0)f.set("origin",F);let M=await fetch(`http://${G}${K}${B}`,{method:X.method,headers:f,body:X.body,redirect:"manual"});if(q)C8(q,z);return M}catch(f){if(N("request",`Proxy error for ${W}: ${f}`,w),q)hY(q,z);return new Response(`Proxy Error: ${f}`,{status:502})}if(N("request",`Proxy error for ${W}: ${E}`,w),q)hY(q,z);return new Response(`Proxy Error: ${E}`,{status:502})}finally{if(q)z.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return N("request",`Unhandled proxy handler error: ${U}`,w),new Response("Bad Gateway",{status:502})}}}function p1($){let w=new WeakMap,Y=kR();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){N("ws",`failed to open upstream ${X}: ${W}`,$),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let B={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};w.set(A,B),U.addEventListener("open",()=>{B.upstreamOpen=!0;for(let W of B.pending)U.send(W);B.pending=[],B.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",()=>{N("ws",`upstream error for ${X}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=w.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let B=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+B>Y){N("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,$);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}w.delete(A);return}J.pending.push(U),J.pendingBytes+=B},close(A,X,J){let U=w.get(A);if(!U)return;w.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var DR;var L8=t(()=>{DY();k5();bY();X0();DR=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 i5 from"node:fs";import*as m5 from"node:path";function uY($,w){if(!$||!w.startsWith(c5))return null;let Y=w.slice(c5.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return i5.readFileSync(m5.join($,Y),"utf8")}catch{return null}}var c5="/.well-known/acme-challenge/";var O8=()=>{};function Q$($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function bR($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function r1($){let w=new Map;for(let A of $){let X=Q$(A.path),J=w.get(A.host);if(!J)J=new Map,w.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of w){let J=[];for(let[U,B]of X)J.push({path:U,route:B});J.sort((U,B)=>B.path.length-U.path.length),Y.set(A,J)}return Y}function _8($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of $){if(!B1(J))continue;if(NY(w,J)){let B=J.length-1;if(B>X)X=B,A=U}}return A}function t1($,w,Y){let A=_8($,w);if(!A)return;for(let X of A)if(bR(Y,X.path))return X.route;return}var vY=()=>{};import*as cY from"node:fs/promises";import*as VB from"node:path";function uR($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function vR($,w,Y,A){try{let[X,J]=await Promise.all([cY.readFile(w,"utf8"),cY.readFile(Y,"utf8")]);return{serverName:$,cert:X,key:J}}catch(X){return N("sni",`skipping ${$}: ${X.message}`,A),null}}async function a1($,w){let Y=new Map;if($.certsDir){let X=[];try{X=await cY.readdir($.certsDir)}catch(J){N("sni",`certsDir read failed (${$.certsDir}): ${J.message}`,w)}for(let J of X){let U=uR(J);if(!U)continue;let B=J.slice(0,-4);Y.set(U,{certPath:VB.join($.certsDir,J),keyPath:VB.join($.certsDir,`${B}.key`)})}}if($.domains)for(let[X,J]of Object.entries($.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await vR(X,J.certPath,J.keyPath,w);if(U)A.push(U)}return A}var S8=t(()=>{X0()});import*as Mw from"node:fs/promises";import*as CB from"node:path";function iR($,w){if(!w||w.length===0)return!1;return w.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return $===A||$.endsWith(`.${A}`)})}function d5($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class iY{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??_X,this.issuer=$.issuer??wW,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??cR;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!d5($))return!1;if(iR($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return N("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;if(!d5($))return!1;let w=this.inFlight.get($);if(w)return w;let Y=this.negativeCache.get($);if(Y!==void 0&&Date.now()<Y)return N("on-demand",`${$} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1;let A=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,A),A}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return N("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),this.cacheNegative($),!1;try{N("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let Y={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,Y),this.negativeCache.delete($),N("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.cacheNegative($),N("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}cacheNegative($){if(this.negativeCache.size>=g5){let w=Date.now();for(let[Y,A]of this.negativeCache)if(A<=w)this.negativeCache.delete(Y);if(this.negativeCache.size>=g5){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set($,Date.now()+this.negativeCacheMs)}async loadFromDisk($){let{certPath:w,keyPath:Y}=this.pathsFor($);try{let[A,X]=await Promise.all([Mw.readFile(w,"utf8"),Mw.readFile(Y,"utf8")]),J={serverName:$,cert:A,key:X};return this.certs.set($,J),N("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:CB.join(this.certsDir,`${$}.crt`),keyPath:CB.join(this.certsDir,`${$}.key`)}}async persist($,w,Y){await Mw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor($);await Promise.all([Mw.writeFile(A,w,"utf8"),Mw.writeFile(X,Y,{encoding:"utf8",mode:384})])}}var cR=60000,g5=4096;var QB=t(()=>{bX();X0()});import{existsSync as mR,readdirSync as BO,readFileSync as gR,statSync as dR}from"node:fs";import{homedir as lR}from"node:os";import{isAbsolute as nR,join as s1}from"node:path";function l5($,w){if($==="~")return w;if($.startsWith("~/"))return s1(w,$.slice(2));return $}function aR($){let w=$.indexOf(":");return(w===-1?$:$.slice(0,w)).toLowerCase()}function n5($){return $.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function sR($,w){for(let Y of w){let A=`.${Y}`;if($.endsWith(A)){let X=$.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 oR($,w){let Y=w.readText(s1($,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=w.readText(s1($,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function eR($){let w=$.selfRegisters??!1;return{command:$.command,env:$.env,urlEnv:$.urlEnv,selfRegisters:w,routes:$.routes??(w?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function $M($,w){let Y=oR($,w);if(Y?.command)return eR(Y);let A=w.fileExists(s1($,"buddy")),X=w.readText(s1($,"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 LB($,w={}){let Y={dirExists:w.dirExists??yB.dirExists,fileExists:w.fileExists??yB.fileExists,readText:w.readText??yB.readText},A=w.detect??$M,X=w.homeDir??lR(),J=$.tlds??rR,U=($.roots??pR).map((K)=>l5(K,X)),B=$.idleTimeoutMs??tR,W=new Map;for(let K of $.sites??[])W.set(K.to,K);let j=(K)=>K.idleTimeoutMs??B;function z(K){let F=gA(W,K);if(!F)return null;let T=nR(F.dir)?F.dir:l5(F.dir,X),q=F.selfRegisters??!1,E=F.routes??[];if(!q&&E.length===0)E=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let f=p5({...F.env??{}},void 0,K);return{host:K,id:n5(K),dir:T,command:F.command,env:f,routes:E,selfRegisters:q,idleTimeoutMs:j(F),source:"config"}}function G(K){let F=sR(K,J);if(!F)return null;for(let T of U){let q=s1(T,F);if(!Y.dirExists(q))continue;let E=A(q,Y);if(!E)continue;let f=E.selfRegisters??!1;return{host:K,id:n5(K),dir:q,command:E.command,env:p5({...E.env??{}},E.urlEnv,K),routes:f?[]:E.routes??[],selfRegisters:f,idleTimeoutMs:B,source:"discovered"}}return null}return{resolve(K){let F=aR(K);if(!F)return null;return z(F)??G(F)}}}function p5($,w,Y){if(!w)return $;let A=`https://${Y}`;for(let X of w)if($[X]===void 0)$[X]=A;return $}var pR,rR,tR=1800000,yB;var OB=t(()=>{pR=["~/Code"],rR=["localhost","test"],yB={dirExists:($)=>{try{return dR($).isDirectory()}catch{return!1}},fileExists:($)=>{try{return mR($)}catch{return!1}},readText:($)=>{try{return gR($,"utf8")}catch{return null}}}});import*as Z8 from"node:net";function Iw($,w,Y){return N("port",`Checking if port ${$} is in use on ${w}`,Y),new Promise((A)=>{let X=Z8.createServer(),J=setTimeout(()=>{N("port",`Checking port ${$} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")N("port",`Port ${$} is in use`,Y),A(!0);else N("port",`Error checking port ${$}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),N("port",`Port ${$} is available`,Y),X.close(),A(!1)});try{X.listen($,w)}catch(U){clearTimeout(J),N("port",`Exception checking port ${$}: ${U}`,Y),A(!0)}})}async function _B($,w,Y,A=50){N("port",`Finding available port starting from ${$} (max attempts: ${A})`,Y);let X=$,J=0;while(J<A){if(J++,!await Iw(X,w,Y))return N("port",`Found available port: ${X} after ${J} attempts`,Y),X;N("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 ${$}`)}function r5($,w,Y=5000,A){return N("port",`Testing connection to ${w}:${$}`,A),new Promise((X)=>{let J=Z8.connect({host:w,port:$,timeout:Y});J.once("connect",()=>{N("port",`Successfully connected to ${w}:${$}`,A),J.end(),X(!0)}),J.once("timeout",()=>{N("port",`Connection to ${w}:${$} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{N("port",`Failed to connect to ${w}:${$}: ${U.message}`,A),J.destroy(),X(!1)})})}class h8{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,Y=50){this.hostname=$,this.verbose=w,this.maxRetries=Y}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Iw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await r5($,this.hostname,3000,this.verbose))return N("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let Y=await _B($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await r5(Y,this.hostname,3000,this.verbose))if(Y<$+this.maxRetries)return this.findNextAvailablePort(Y+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort($){N("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var NO;var SB=t(()=>{X0();NO=new h8});import*as k8 from"node:fs";import*as n0 from"node:fs/promises";import{homedir as wM}from"node:os";import*as ZB from"node:path";import*as D8 from"node:process";function L$(){return ZB.join(wM(),".stacks","rpx","registry.d")}function mY($){return typeof $==="string"&&$.length>0&&$.length<=128&&YM.test($)}function hB($,w){if(!mY(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return ZB.join($,`${w}.json`)}function r0($){if(!Number.isInteger($)||$<=0)return!1;try{return D8.kill($,0),!0}catch(w){return w.code==="EPERM"}}function t5($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0||Array.isArray(w.from)&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&mY(w.id)&&(A||X)&&typeof w.to==="string"&&w.to.length>0&&J&&Y&&typeof w.createdAt==="string"}async function AM($){await n0.mkdir($,{recursive:!0})}async function x8($,w=L$(),Y){if(!t5($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await AM(w);let A=hB(w,$.id),X=`${A}.tmp.${D8.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await n0.writeFile(X,J,{encoding:"utf8",mode:420}),await n0.rename(X,A),N("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(U){throw await n0.unlink(X).catch(()=>{}),U}}async function gY($,w=L$(),Y){let A=hB(w,$);try{await n0.unlink(A),N("registry",`removed entry ${$}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function XM($,w=L$(),Y){let A=hB(w,$);try{let X=await n0.readFile(A,"utf8"),J=JSON.parse(X);if(!t5(J))return N("registry",`entry ${$} failed validation, removing`,Y),await n0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return N("registry",`entry ${$} has invalid JSON, removing`,Y),await n0.unlink(A).catch(()=>{}),null;throw X}}async function y$($=L$(),w){let Y;try{Y=await n0.readdir($)}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(!mY(J))continue;let U=await XM(J,$,w);if(U)A.push(U)}return A}async function o1($=L$(),w){let Y=await y$($,w),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!r0(X.pid))N("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,w),await gY(X.id,$,w).catch(()=>{}),A++}return A}function dY($,w={}){let Y=w.dir??L$(),A=w.debounceMs??100,X=w.pollMs??Math.max(A*2,250),J=w.verbose;k8.mkdirSync(Y,{recursive:!0});let U=null,B=!1,W=null,j=!1,z=(E)=>{return JSON.stringify(E.map((f)=>({id:f.id,from:f.from,to:f.to,path:f.path,pid:f.pid,pathRewrites:f.pathRewrites,cleanUrls:f.cleanUrls,changeOrigin:f.changeOrigin,static:f.static,loadBalancer:f.loadBalancer})).sort((f,M)=>f.id.localeCompare(M.id)))},G=()=>{if(U=null,B)return;y$(Y,J).then((E)=>{return W=z(E),$(E)}).catch((E)=>{N("registry",`watcher onChange failed: ${E}`,J)})},K=()=>{if(B)return;if(U)clearTimeout(U);U=setTimeout(G,A)},T=setInterval(()=>{if(B||j)return;j=!0,y$(Y,J).then((E)=>{if(z(E)!==W)K()}).catch((E)=>{N("registry",`watcher poll failed: ${E}`,J)}).finally(()=>{j=!1})},X),q=k8.watch(Y,{persistent:!0},(E,f)=>{if(f&&/\.tmp\.\d+\.\d+$/.test(f))return;K()});return q.on("error",(E)=>{N("registry",`watcher error: ${E}`,J)}),K(),{close:()=>{if(B=!0,U)clearTimeout(U);clearInterval(T),q.close()}}}var YM;var e1=t(()=>{X0();YM=/^[a-zA-Z0-9._-]+$/});import{closeSync as a5,openSync as JM,readFileSync as UM}from"node:fs";import*as s5 from"node:fs/promises";import{spawn as WM}from"node:child_process";import{homedir as BM}from"node:os";import*as lY from"node:path";import*as M$ from"node:process";class P8{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor($){this.resolver=$.resolver,this.registryDir=$.registryDir??L$(),this.rpxDir=$.rpxDir??lY.join(BM(),".stacks","rpx"),this.verbose=$.verbose??!1,this.startupTimeoutMs=$.startupTimeoutMs??jM,this.pollIntervalMs=$.pollIntervalMs??zM,this.restartDelayMs=$.restartDelayMs??KM,this.killGraceMs=$.killGraceMs??FM,this.launch=$.launcher??qM(this.verbose),this.probePort=$.probePort??NM,this.pickPort=$.pickPort??((Y)=>_B(Y,"127.0.0.1")),this.isHostRoutable=$.isHostRoutable??(()=>!1),this.onSiteActivating=$.onSiteActivating,this.now=$.now??Date.now,this.writeEntry=$.writeEntry??x8,this.removeEntry=$.removeEntry??gY;let w=$.reapIntervalMs??GM;if(this.reaper=setInterval(()=>{this.reapIdle()},w),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest($){if(this.stopped)return{kind:"unknown"};let w=this.sites.get($);if(w&&w.status==="failed"&&this.now()-w.failedAt>=this.restartDelayMs)this.sites.delete($),w=void 0;if(!w){let Y=this.resolver.resolve($);if(!Y)return{kind:"unknown"};w=await this.start(Y)}if(w.lastAccess=this.now(),w.status==="ready")return{kind:"ready",host:$};if(w.status==="failed")return{kind:"failed",host:$,error:w.error??"failed to start",logTail:this.readLogTail(w)};return{kind:"starting",host:$,sinceMs:this.now()-w.startedAt,source:w.site.source,logTail:this.readLogTail(w,16)}}async start($){try{this.onSiteActivating?.($.host)}catch{}let w=new Map;if(!$.selfRegisters)for(let B of $.routes){if(w.has(B.portEnv))continue;let W=await this.pickPort(B.defaultPort??3000);w.set(B.portEnv,W)}let Y=lY.join(this.rpxDir,"sites",`${$.id}.log`);await s5.mkdir(lY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv($,w),X=null,J;try{X=this.launch({command:$.command,cwd:$.dir,env:A,logPath:Y})}catch(B){J=`failed to spawn: ${B.message}`}let U={site:$,status:J?"failed":"starting",handle:X,ports:w,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($.host,U),J)return R.warn(`rpx: site ${$.host} ${J}`),U;return R.info(`rpx: booting ${$.host} → ${$.command} (${$.dir})`),X.exited.then((B)=>this.onProcessExit(U,B)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((B)=>{N("sites",`readiness loop for ${$.host} threw: ${B}`,this.verbose)}),U}async onProcessExit($,w){if($.exited=!0,this.stopped||this.sites.get($.site.host)!==$)return;if($.status==="ready"){R.warn(`rpx: ${$.site.host} exited${w!==null?` (code ${w})`:""} — will reboot on next request`),this.sites.delete($.site.host);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if($.status==="starting")this.fail($,`process exited${w!==null?` with code ${w}`:""} before becoming ready`)}async driveReadiness($){let{site:w}=$,Y=this.now()+this.startupTimeoutMs,A=w.selfRegisters?()=>this.isHostRoutable(w.host):await this.makeGateProbe(w,$.ports);while(this.now()<Y&&!this.stopped){if($.status!=="starting"||$.exited)return;if(await A()){if(await this.publishRoutes($),$.status==="starting")$.status="ready",R.success(`rpx: ${w.host} ready`);return}await kB(this.pollIntervalMs)}if($.status==="starting")this.fail($,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe($,w){let Y=$.routes.filter((X)=>X.readyGate??Q$(X.path)==="/").map((X)=>w.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...w.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes($){let{site:w,ports:Y}=$;if(w.selfRegisters||w.routes.length===0)return;let A=w.routes.find((W)=>Q$(W.path)==="/")??w.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of w.routes){if(W===A)continue;let j=Y.get(W.portEnv);if(j===void 0)continue;J.push({from:Q$(W.path),to:`localhost:${j}`,stripPrefix:W.stripPrefix??!1})}let U={id:w.id,from:`localhost:${X}`,to:w.host,cwd:w.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:$.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),$.routeIds=[w.id];let B=this.now()+2000;while(this.now()<B&&!this.isHostRoutable(w.host))await kB(50)}fail($,w){$.status="failed",$.error=w,$.failedAt=this.now(),R.warn(`rpx: site ${$.site.host} failed — ${w}`),this.killProcess($)}buildEnv($,w){let Y={};for(let[A,X]of Object.entries(M$.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,$.env);for(let[A,X]of w)Y[A]=String(X);return Y.RPX_SITE_HOST=$.host,Y.RPX_SITE_URL=`https://${$.host}`,Y}readLogTail($,w=40){try{return UM($.logPath,"utf8").split(`
218
+ `,HR.encode(B)}async function _R($){let w=$.getReader(),Y=[],A=0;for(;;){let{done:U,value:B}=await w.read();if(U)break;if(B){if(A+=B.length,A>L5)return w.cancel().catch(()=>{}),null;Y.push(B)}}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 JR,xY,Q8,UR,VB,iw,L5=1048576,IB=30000,FR=16384,O5=262144,NR=2097152,qR=524288,ER=8192,TR=4096,HR,_5,fR,y8;var k5=t(()=>{({connect:JR}=Bun),xY=Symbol("rpx.pool.fallback"),Q8=Symbol("rpx.pool.stale"),UR=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);VB=Symbol("rpx.pool.timeout"),iw=Symbol("rpx.pool.busy");HR=new TextEncoder,_5=new TextDecoder,fR=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);y8=new Map});function x5($){let w=typeof $==="string"?{to:$}:$,Y=(w.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:w.status??301,preservePath:w.preservePath??!0}}function P5($,w,Y){if(!$.preservePath)return $.to||"/";let A=`${w}${Y}`;return A==="/"?`${$.to}/`:`${$.to}${A}`}import*as z$ from"node:path";function PY($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function ZR($){let w=z$.extname($).toLowerCase();return SR[w]??"application/octet-stream"}function hR($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let Y=z$.posix.normalize(`/${w}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function DR($,w){let Y=hR($);if(Y===null)return null;let A=z$.posix.extname(Y);if(w.cleanUrls&&A===".html"){let X=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:z$.join(w.dir,Y),redirectTo:X||"/"}}if(Y===""||$.endsWith("/"))return{filePath:z$.join(w.dir,Y,"index.html")};if(A!=="")return{filePath:z$.join(w.dir,Y)};if(w.pathRewriteStyle==="flat")return{filePath:z$.join(w.dir,`${Y}.html`)};return{filePath:z$.join(w.dir,Y,"index.html")}}async function b5($,w){let Y=DR($,w);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":ZR(Y.filePath),"Cache-Control":A}});if(w.spa){let J=z$.join(w.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 SR;var bY=t(()=>{SR={".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 kR(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function PR($){let w=$.headers.get("host")||"",Y=w.indexOf(":");return Y===-1?w:w.slice(0,Y)}function c5($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let Y=$.slice(w.length);return Y===""?"/":Y}return $}function u5($){if($.upstreamPool)return I5($.upstreamPool);if($.sourceHost)return{url:$.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function v5($,w,Y,A){let X=Y?.url??w.sourceHost??"",U=w.stripBasePathPrefix??!1?c5($,w.basePath):$,B=zB(U,w.pathRewrites);if(B)X=B.targetHost,U=B.targetPath,N("request",`Path rewrite: ${$} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function bR($){let w=$.indexOf("://"),Y=w===-1?$.indexOf("/"):$.indexOf("/",w+3);if(Y===-1)return{pathname:"/",search:""};let A=$.indexOf("?",Y);if(A===-1)return{pathname:$.slice(Y),search:""};return{pathname:$.slice(Y,A),search:$.slice(A)}}function n1($,w,Y){let A=async(X,J)=>{let{pathname:U,search:B}=bR(X.url),W=PR(X),j=$(W,U);if(!j&&Y){let E=await Y(W,U,X);if(E instanceof Response)return E;if(E&&E.retry)j=$(W,U)}if(!j)return N("request",`No route found for host: ${W}`,w),new Response(`No proxy configured for ${W}`,{status:404});if(j.auth){let E=Q5(X,U,j.auth);if(E)return N("request",`401 challenge for ${W}${U}`,w),E}if(j.redirect){let E=P5(j.redirect,U,B);return N("request",`${j.redirect.status} redirect ${W}${U} → ${E}`,w),new Response(null,{status:j.redirect.status,headers:{location:E}})}if(j.static){let f=j.stripBasePathPrefix??!0?c5(U,j.basePath):U;return b5(f,j.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let E=u5(j);if(!J||!E)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:f,targetPath:M}=v5(U,j,E,w),Q=`ws://${f}${M}${B}`,V={};for(let[O,Z]of X.headers)if(!xR.has(O.toLowerCase())&&O.toLowerCase()!=="host")V[O]=Z;V.host=f,V["x-forwarded-for"]="127.0.0.1",V["x-forwarded-proto"]="https",V["x-forwarded-host"]=W;let H={targetUrl:Q,forwardHeaders:V};if(J.upgrade(X,{data:H})){N("ws",`upgraded ${W}${M} → ${Q}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}let z=u5(j);if(!z)return new Response(`No upstream configured for ${W}`,{status:502});if(j.cleanUrls&&U.endsWith(".html")){let E=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:E}})}let{targetHost:G,targetPath:K}=v5(U,j,z,w),F=j.changeOrigin?`http://${G}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",q=j.upstreamPool;if(q)z.activeConnections++;try{let E=await h5({hostPort:G,method:X.method,path:`${K}${B}`,reqHeaders:X.headers,forwardedHost:W,originOverride:F,body:X.body});if(q)C8(q,z);return E}catch(E){if(E===VB){if(N("request",`Upstream timeout for ${W}`,w),q)hY(q,z);return new Response("Gateway Timeout",{status:504})}if(E===iw)return N("request",`Upstream pool saturated for ${W}`,w),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(E===xY||!T)try{let f=new Headers(X.headers);if(f.set("host",G),f.set("x-forwarded-for","127.0.0.1"),f.set("x-forwarded-proto","https"),f.set("x-forwarded-host",W),F!==void 0)f.set("origin",F);let M=await fetch(`http://${G}${K}${B}`,{method:X.method,headers:f,body:X.body,redirect:"manual"});if(q)C8(q,z);return M}catch(f){if(N("request",`Proxy error for ${W}: ${f}`,w),q)hY(q,z);return new Response(`Proxy Error: ${f}`,{status:502})}if(N("request",`Proxy error for ${W}: ${E}`,w),q)hY(q,z);return new Response(`Proxy Error: ${E}`,{status:502})}finally{if(q)z.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return N("request",`Unhandled proxy handler error: ${U}`,w),new Response("Bad Gateway",{status:502})}}}function p1($){let w=new WeakMap,Y=kR();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){N("ws",`failed to open upstream ${X}: ${W}`,$),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let B={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};w.set(A,B),U.addEventListener("open",()=>{B.upstreamOpen=!0;for(let W of B.pending)U.send(W);B.pending=[],B.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",()=>{N("ws",`upstream error for ${X}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=w.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let B=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+B>Y){N("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,$);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}w.delete(A);return}J.pending.push(U),J.pendingBytes+=B},close(A,X,J){let U=w.get(A);if(!U)return;w.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var xR;var L8=t(()=>{kY();k5();bY();X0();xR=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 m5 from"node:fs";import*as g5 from"node:path";function uY($,w){if(!$||!w.startsWith(i5))return null;let Y=w.slice(i5.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return m5.readFileSync(g5.join($,Y),"utf8")}catch{return null}}var i5="/.well-known/acme-challenge/";var O8=()=>{};function Q$($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function uR($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function r1($){let w=new Map;for(let A of $){let X=Q$(A.path),J=w.get(A.host);if(!J)J=new Map,w.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of w){let J=[];for(let[U,B]of X)J.push({path:U,route:B});J.sort((U,B)=>B.path.length-U.path.length),Y.set(A,J)}return Y}function _8($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of $){if(!j1(J))continue;if(NY(w,J)){let B=J.length-1;if(B>X)X=B,A=U}}return A}function t1($,w,Y){let A=_8($,w);if(!A)return;for(let X of A)if(uR(Y,X.path))return X.route;return}var vY=()=>{};import*as cY from"node:fs/promises";import*as CB from"node:path";function vR($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function cR($,w,Y,A){try{let[X,J]=await Promise.all([cY.readFile(w,"utf8"),cY.readFile(Y,"utf8")]);return{serverName:$,cert:X,key:J}}catch(X){return N("sni",`skipping ${$}: ${X.message}`,A),null}}async function a1($,w){let Y=new Map;if($.certsDir){let X=[];try{X=await cY.readdir($.certsDir)}catch(J){N("sni",`certsDir read failed (${$.certsDir}): ${J.message}`,w)}for(let J of X){let U=vR(J);if(!U)continue;let B=J.slice(0,-4);Y.set(U,{certPath:CB.join($.certsDir,J),keyPath:CB.join($.certsDir,`${B}.key`)})}}if($.domains)for(let[X,J]of Object.entries($.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await cR(X,J.certPath,J.keyPath,w);if(U)A.push(U)}return A}var S8=t(()=>{X0()});import*as Mw from"node:fs/promises";import*as QB from"node:path";function mR($,w){if(!w||w.length===0)return!1;return w.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return $===A||$.endsWith(`.${A}`)})}function l5($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class iY{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??_X,this.issuer=$.issuer??wW,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??iR;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!l5($))return!1;if(mR($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return N("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;if(!l5($))return!1;let w=this.inFlight.get($);if(w)return w;let Y=this.negativeCache.get($);if(Y!==void 0&&Date.now()<Y)return N("on-demand",`${$} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1;let A=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,A),A}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return N("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),this.cacheNegative($),!1;try{N("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let Y={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,Y),this.negativeCache.delete($),N("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.cacheNegative($),N("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}cacheNegative($){if(this.negativeCache.size>=d5){let w=Date.now();for(let[Y,A]of this.negativeCache)if(A<=w)this.negativeCache.delete(Y);if(this.negativeCache.size>=d5){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set($,Date.now()+this.negativeCacheMs)}async loadFromDisk($){let{certPath:w,keyPath:Y}=this.pathsFor($);try{let[A,X]=await Promise.all([Mw.readFile(w,"utf8"),Mw.readFile(Y,"utf8")]),J={serverName:$,cert:A,key:X};return this.certs.set($,J),N("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:QB.join(this.certsDir,`${$}.crt`),keyPath:QB.join(this.certsDir,`${$}.key`)}}async persist($,w,Y){await Mw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor($);await Promise.all([Mw.writeFile(A,w,"utf8"),Mw.writeFile(X,Y,{encoding:"utf8",mode:384})])}}var iR=60000,d5=4096;var yB=t(()=>{bX();X0()});import{existsSync as gR,readdirSync as zO,readFileSync as dR,statSync as lR}from"node:fs";import{homedir as nR}from"node:os";import{isAbsolute as pR,join as s1}from"node:path";function n5($,w){if($==="~")return w;if($.startsWith("~/"))return s1(w,$.slice(2));return $}function sR($){let w=$.indexOf(":");return(w===-1?$:$.slice(0,w)).toLowerCase()}function p5($){return $.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function oR($,w){for(let Y of w){let A=`.${Y}`;if($.endsWith(A)){let X=$.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 eR($,w){let Y=w.readText(s1($,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=w.readText(s1($,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function $M($){let w=$.selfRegisters??!1;return{command:$.command,env:$.env,urlEnv:$.urlEnv,selfRegisters:w,routes:$.routes??(w?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function wM($,w){let Y=eR($,w);if(Y?.command)return $M(Y);let A=w.fileExists(s1($,"buddy")),X=w.readText(s1($,"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 OB($,w={}){let Y={dirExists:w.dirExists??LB.dirExists,fileExists:w.fileExists??LB.fileExists,readText:w.readText??LB.readText},A=w.detect??wM,X=w.homeDir??nR(),J=$.tlds??tR,U=($.roots??rR).map((K)=>n5(K,X)),B=$.idleTimeoutMs??aR,W=new Map;for(let K of $.sites??[])W.set(K.to,K);let j=(K)=>K.idleTimeoutMs??B;function z(K){let F=gA(W,K);if(!F)return null;let T=pR(F.dir)?F.dir:n5(F.dir,X),q=F.selfRegisters??!1,E=F.routes??[];if(!q&&E.length===0)E=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let f=r5({...F.env??{}},void 0,K);return{host:K,id:p5(K),dir:T,command:F.command,env:f,routes:E,selfRegisters:q,idleTimeoutMs:j(F),source:"config"}}function G(K){let F=oR(K,J);if(!F)return null;for(let T of U){let q=s1(T,F);if(!Y.dirExists(q))continue;let E=A(q,Y);if(!E)continue;let f=E.selfRegisters??!1;return{host:K,id:p5(K),dir:q,command:E.command,env:r5({...E.env??{}},E.urlEnv,K),routes:f?[]:E.routes??[],selfRegisters:f,idleTimeoutMs:B,source:"discovered"}}return null}return{resolve(K){let F=sR(K);if(!F)return null;return z(F)??G(F)}}}function r5($,w,Y){if(!w)return $;let A=`https://${Y}`;for(let X of w)if($[X]===void 0)$[X]=A;return $}var rR,tR,aR=1800000,LB;var _B=t(()=>{rR=["~/Code"],tR=["localhost","test"],LB={dirExists:($)=>{try{return lR($).isDirectory()}catch{return!1}},fileExists:($)=>{try{return gR($)}catch{return!1}},readText:($)=>{try{return dR($,"utf8")}catch{return null}}}});import*as Z8 from"node:net";function Iw($,w,Y){return N("port",`Checking if port ${$} is in use on ${w}`,Y),new Promise((A)=>{let X=Z8.createServer(),J=setTimeout(()=>{N("port",`Checking port ${$} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")N("port",`Port ${$} is in use`,Y),A(!0);else N("port",`Error checking port ${$}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),N("port",`Port ${$} is available`,Y),X.close(),A(!1)});try{X.listen($,w)}catch(U){clearTimeout(J),N("port",`Exception checking port ${$}: ${U}`,Y),A(!0)}})}async function SB($,w,Y,A=50){N("port",`Finding available port starting from ${$} (max attempts: ${A})`,Y);let X=$,J=0;while(J<A){if(J++,!await Iw(X,w,Y))return N("port",`Found available port: ${X} after ${J} attempts`,Y),X;N("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 ${$}`)}function t5($,w,Y=5000,A){return N("port",`Testing connection to ${w}:${$}`,A),new Promise((X)=>{let J=Z8.connect({host:w,port:$,timeout:Y});J.once("connect",()=>{N("port",`Successfully connected to ${w}:${$}`,A),J.end(),X(!0)}),J.once("timeout",()=>{N("port",`Connection to ${w}:${$} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{N("port",`Failed to connect to ${w}:${$}: ${U.message}`,A),J.destroy(),X(!1)})})}class h8{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,Y=50){this.hostname=$,this.verbose=w,this.maxRetries=Y}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Iw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await t5($,this.hostname,3000,this.verbose))return N("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let Y=await SB($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await t5(Y,this.hostname,3000,this.verbose))if(Y<$+this.maxRetries)return this.findNextAvailablePort(Y+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort($){N("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var EO;var ZB=t(()=>{X0();EO=new h8});import*as D8 from"node:fs";import*as n0 from"node:fs/promises";import{homedir as YM}from"node:os";import*as hB from"node:path";import*as k8 from"node:process";function L$(){return hB.join(YM(),".stacks","rpx","registry.d")}function mY($){return typeof $==="string"&&$.length>0&&$.length<=128&&AM.test($)}function DB($,w){if(!mY(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return hB.join($,`${w}.json`)}function r0($){if(!Number.isInteger($)||$<=0)return!1;try{return k8.kill($,0),!0}catch(w){return w.code==="EPERM"}}function a5($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0||Array.isArray(w.from)&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&mY(w.id)&&(A||X)&&typeof w.to==="string"&&w.to.length>0&&J&&Y&&typeof w.createdAt==="string"}async function XM($){await n0.mkdir($,{recursive:!0})}async function x8($,w=L$(),Y){if(!a5($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await XM(w);let A=DB(w,$.id),X=`${A}.tmp.${k8.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await n0.writeFile(X,J,{encoding:"utf8",mode:420}),await n0.rename(X,A),N("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(U){throw await n0.unlink(X).catch(()=>{}),U}}async function gY($,w=L$(),Y){let A=DB(w,$);try{await n0.unlink(A),N("registry",`removed entry ${$}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function JM($,w=L$(),Y){let A=DB(w,$);try{let X=await n0.readFile(A,"utf8"),J=JSON.parse(X);if(!a5(J))return N("registry",`entry ${$} failed validation, removing`,Y),await n0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return N("registry",`entry ${$} has invalid JSON, removing`,Y),await n0.unlink(A).catch(()=>{}),null;throw X}}async function y$($=L$(),w){let Y;try{Y=await n0.readdir($)}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(!mY(J))continue;let U=await JM(J,$,w);if(U)A.push(U)}return A}async function o1($=L$(),w){let Y=await y$($,w),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!r0(X.pid))N("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,w),await gY(X.id,$,w).catch(()=>{}),A++}return A}function dY($,w={}){let Y=w.dir??L$(),A=w.debounceMs??100,X=w.pollMs??Math.max(A*2,250),J=w.verbose;D8.mkdirSync(Y,{recursive:!0});let U=null,B=!1,W=null,j=!1,z=(E)=>{return JSON.stringify(E.map((f)=>({id:f.id,from:f.from,to:f.to,path:f.path,pid:f.pid,pathRewrites:f.pathRewrites,cleanUrls:f.cleanUrls,changeOrigin:f.changeOrigin,static:f.static,loadBalancer:f.loadBalancer})).sort((f,M)=>f.id.localeCompare(M.id)))},G=()=>{if(U=null,B)return;y$(Y,J).then((E)=>{return W=z(E),$(E)}).catch((E)=>{N("registry",`watcher onChange failed: ${E}`,J)})},K=()=>{if(B)return;if(U)clearTimeout(U);U=setTimeout(G,A)},T=setInterval(()=>{if(B||j)return;j=!0,y$(Y,J).then((E)=>{if(z(E)!==W)K()}).catch((E)=>{N("registry",`watcher poll failed: ${E}`,J)}).finally(()=>{j=!1})},X),q=D8.watch(Y,{persistent:!0},(E,f)=>{if(f&&/\.tmp\.\d+\.\d+$/.test(f))return;K()});return q.on("error",(E)=>{N("registry",`watcher error: ${E}`,J)}),K(),{close:()=>{if(B=!0,U)clearTimeout(U);clearInterval(T),q.close()}}}var AM;var e1=t(()=>{X0();AM=/^[a-zA-Z0-9._-]+$/});import{closeSync as s5,openSync as UM,readFileSync as WM}from"node:fs";import*as o5 from"node:fs/promises";import{spawn as BM}from"node:child_process";import{homedir as jM}from"node:os";import*as lY from"node:path";import*as M$ from"node:process";class P8{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor($){this.resolver=$.resolver,this.registryDir=$.registryDir??L$(),this.rpxDir=$.rpxDir??lY.join(jM(),".stacks","rpx"),this.verbose=$.verbose??!1,this.startupTimeoutMs=$.startupTimeoutMs??zM,this.pollIntervalMs=$.pollIntervalMs??GM,this.restartDelayMs=$.restartDelayMs??FM,this.killGraceMs=$.killGraceMs??NM,this.launch=$.launcher??EM(this.verbose),this.probePort=$.probePort??qM,this.pickPort=$.pickPort??((Y)=>SB(Y,"127.0.0.1")),this.isHostRoutable=$.isHostRoutable??(()=>!1),this.onSiteActivating=$.onSiteActivating,this.now=$.now??Date.now,this.writeEntry=$.writeEntry??x8,this.removeEntry=$.removeEntry??gY;let w=$.reapIntervalMs??KM;if(this.reaper=setInterval(()=>{this.reapIdle()},w),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest($){if(this.stopped)return{kind:"unknown"};let w=this.sites.get($);if(w&&w.status==="failed"&&this.now()-w.failedAt>=this.restartDelayMs)this.sites.delete($),w=void 0;if(!w){let Y=this.resolver.resolve($);if(!Y)return{kind:"unknown"};w=await this.start(Y)}if(w.lastAccess=this.now(),w.status==="ready")return{kind:"ready",host:$};if(w.status==="failed")return{kind:"failed",host:$,error:w.error??"failed to start",logTail:this.readLogTail(w)};return{kind:"starting",host:$,sinceMs:this.now()-w.startedAt,source:w.site.source,logTail:this.readLogTail(w,16)}}async start($){try{this.onSiteActivating?.($.host)}catch{}let w=new Map;if(!$.selfRegisters)for(let B of $.routes){if(w.has(B.portEnv))continue;let W=await this.pickPort(B.defaultPort??3000);w.set(B.portEnv,W)}let Y=lY.join(this.rpxDir,"sites",`${$.id}.log`);await o5.mkdir(lY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv($,w),X=null,J;try{X=this.launch({command:$.command,cwd:$.dir,env:A,logPath:Y})}catch(B){J=`failed to spawn: ${B.message}`}let U={site:$,status:J?"failed":"starting",handle:X,ports:w,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($.host,U),J)return R.warn(`rpx: site ${$.host} ${J}`),U;return R.info(`rpx: booting ${$.host} → ${$.command} (${$.dir})`),X.exited.then((B)=>this.onProcessExit(U,B)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((B)=>{N("sites",`readiness loop for ${$.host} threw: ${B}`,this.verbose)}),U}async onProcessExit($,w){if($.exited=!0,this.stopped||this.sites.get($.site.host)!==$)return;if($.status==="ready"){R.warn(`rpx: ${$.site.host} exited${w!==null?` (code ${w})`:""} — will reboot on next request`),this.sites.delete($.site.host);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if($.status==="starting")this.fail($,`process exited${w!==null?` with code ${w}`:""} before becoming ready`)}async driveReadiness($){let{site:w}=$,Y=this.now()+this.startupTimeoutMs,A=w.selfRegisters?()=>this.isHostRoutable(w.host):await this.makeGateProbe(w,$.ports);while(this.now()<Y&&!this.stopped){if($.status!=="starting"||$.exited)return;if(await A()){if(await this.publishRoutes($),$.status==="starting")$.status="ready",R.success(`rpx: ${w.host} ready`);return}await kB(this.pollIntervalMs)}if($.status==="starting")this.fail($,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe($,w){let Y=$.routes.filter((X)=>X.readyGate??Q$(X.path)==="/").map((X)=>w.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...w.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes($){let{site:w,ports:Y}=$;if(w.selfRegisters||w.routes.length===0)return;let A=w.routes.find((W)=>Q$(W.path)==="/")??w.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of w.routes){if(W===A)continue;let j=Y.get(W.portEnv);if(j===void 0)continue;J.push({from:Q$(W.path),to:`localhost:${j}`,stripPrefix:W.stripPrefix??!1})}let U={id:w.id,from:`localhost:${X}`,to:w.host,cwd:w.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:$.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),$.routeIds=[w.id];let B=this.now()+2000;while(this.now()<B&&!this.isHostRoutable(w.host))await kB(50)}fail($,w){$.status="failed",$.error=w,$.failedAt=this.now(),R.warn(`rpx: site ${$.site.host} failed — ${w}`),this.killProcess($)}buildEnv($,w){let Y={};for(let[A,X]of Object.entries(M$.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,$.env);for(let[A,X]of w)Y[A]=String(X);return Y.RPX_SITE_HOST=$.host,Y.RPX_SITE_URL=`https://${$.host}`,Y}readLogTail($,w=40){try{return WM($.logPath,"utf8").split(`
219
219
  `).slice(-w).join(`
220
- `).trim()}catch{return""}}async stop($){let w=this.sites.get($);if(!w)return;this.sites.delete($);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(w),R.info(`rpx: stopped ${$}`)}async killProcess($){let w=$.handle;if(!w)return;$.handle=null;try{w.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{w.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([w.exited.catch(()=>{}),kB(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let $=this.now();for(let[w,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=$-Y.lastAccess;if((Y.status==="ready"||$-Y.startedAt>this.startupTimeoutMs)&&X>A)N("sites",`reaping ${w} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop(w)}}list(){let $=this.now();return[...this.sites.values()].map((w)=>({host:w.site.host,dir:w.site.dir,status:w.status,pid:w.handle?.pid??null,ports:Object.fromEntries(w.ports),uptimeMs:$-w.startedAt,idleMs:$-w.lastAccess,error:w.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map(($)=>this.stop($)))}}function kB($){return new Promise((w)=>setTimeout(w,$))}async function NM($){let w=new AbortController,Y=setTimeout(()=>w.abort(),2000);try{return await fetch(`http://127.0.0.1:${$}/`,{signal:w.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(Y)}}function qM($){let w=EM();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=JM(J,"a");try{let B=WM("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...w?{uid:w.uid,gid:w.gid}:{}}),W=B.pid;if(W===void 0)throw Error("spawn returned no pid");let j=new Promise((z)=>{B.once("exit",(G)=>{z(G)}),B.once("error",()=>{z(null)})}).finally(()=>{try{a5(U)}catch{}});return N("sites",`spawned pid ${W}: sh -c ${Y} (cwd ${A})`,$),{pid:W,exited:j,stop:(z="SIGTERM")=>{try{M$.kill(-W,z)}catch{try{B.kill(z)}catch{}}}}}catch(B){try{a5(U)}catch{}throw B}}}function EM(){if(M$.platform==="win32")return null;if(!(typeof M$.getuid==="function"&&M$.getuid()===0))return null;let w=Number.parseInt(M$.env.SUDO_UID??"",10),Y=Number.parseInt(M$.env.SUDO_GID??"",10);if(!Number.isInteger(w)||w<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:w,gid:Y}}var jM=120000,zM=200,GM=30000,KM=3000,FM=4000;var DB=t(()=>{vY();SB();e1();X0();i$()});function $Y($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function o5($,w,Y){return`<!doctype html>
220
+ `).trim()}catch{return""}}async stop($){let w=this.sites.get($);if(!w)return;this.sites.delete($);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess(w),R.info(`rpx: stopped ${$}`)}async killProcess($){let w=$.handle;if(!w)return;$.handle=null;try{w.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{w.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([w.exited.catch(()=>{}),kB(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let $=this.now();for(let[w,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=$-Y.lastAccess;if((Y.status==="ready"||$-Y.startedAt>this.startupTimeoutMs)&&X>A)N("sites",`reaping ${w} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop(w)}}list(){let $=this.now();return[...this.sites.values()].map((w)=>({host:w.site.host,dir:w.site.dir,status:w.status,pid:w.handle?.pid??null,ports:Object.fromEntries(w.ports),uptimeMs:$-w.startedAt,idleMs:$-w.lastAccess,error:w.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map(($)=>this.stop($)))}}function kB($){return new Promise((w)=>setTimeout(w,$))}async function qM($){let w=new AbortController,Y=setTimeout(()=>w.abort(),2000);try{return await fetch(`http://127.0.0.1:${$}/`,{signal:w.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(Y)}}function EM($){let w=TM();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=UM(J,"a");try{let B=BM("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...w?{uid:w.uid,gid:w.gid}:{}}),W=B.pid;if(W===void 0)throw Error("spawn returned no pid");let j=new Promise((z)=>{B.once("exit",(G)=>{z(G)}),B.once("error",()=>{z(null)})}).finally(()=>{try{s5(U)}catch{}});return N("sites",`spawned pid ${W}: sh -c ${Y} (cwd ${A})`,$),{pid:W,exited:j,stop:(z="SIGTERM")=>{try{M$.kill(-W,z)}catch{try{B.kill(z)}catch{}}}}}catch(B){try{s5(U)}catch{}throw B}}}function TM(){if(M$.platform==="win32")return null;if(!(typeof M$.getuid==="function"&&M$.getuid()===0))return null;let w=Number.parseInt(M$.env.SUDO_UID??"",10),Y=Number.parseInt(M$.env.SUDO_GID??"",10);if(!Number.isInteger(w)||w<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:w,gid:Y}}var zM=120000,GM=200,KM=30000,FM=3000,NM=4000;var xB=t(()=>{vY();ZB();e1();X0();i$()});function $Y($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function e5($,w,Y){return`<!doctype html>
221
221
  <html lang="en">
222
222
  <head>
223
223
  <meta charset="utf-8">
224
224
  <meta name="viewport" content="width=device-width, initial-scale=1">
225
225
  ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
226
226
  <title>${$Y($)}</title>
227
- <style>${TM}</style>
227
+ <style>${HM}</style>
228
228
  </head>
229
229
  <body><main class="card">${w}</main></body>
230
- </html>`}function xB($){let w=Math.max(1,Math.round($.sinceMs/1000)),Y=$.logTail?`<pre>${$Y($.logTail)}</pre>`:"",A=`
230
+ </html>`}function PB($){let w=Math.max(1,Math.round($.sinceMs/1000)),Y=$.logTail?`<pre>${$Y($.logTail)}</pre>`:"",A=`
231
231
  <div class="row"><div class="spinner"></div><h1>Starting ${$Y($.host)}…</h1></div>
232
232
  <p>rpx is booting this site's dev server on demand. This page reloads itself —
233
233
  it'll switch to the app as soon as it's ready (usually a few seconds).</p>
234
234
  <p>Booting for ${w}s.</p>
235
- ${Y}`;return new Response(o5(`Starting ${$.host}`,A,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function PB($){let w=$.logTail?`<pre>${$Y($.logTail)}</pre>`:"<p>No output was captured.</p>",Y=`
235
+ ${Y}`;return new Response(e5(`Starting ${$.host}`,A,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function bB($){let w=$.logTail?`<pre>${$Y($.logTail)}</pre>`:"<p>No output was captured.</p>",Y=`
236
236
  <div class="row"><div class="dot"></div><h1>${$Y($.host)} failed to start</h1></div>
237
237
  <p>${$Y($.error)}</p>
238
238
  ${w}
239
- <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(o5(`${$.host} failed`,Y,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var TM=`
239
+ <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(e5(`${$.host} failed`,Y,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var HM=`
240
240
  :root { color-scheme: light dark }
241
241
  * { box-sizing: border-box }
242
242
  body {
@@ -262,59 +262,59 @@ ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
262
262
  }
263
263
  .dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
264
264
  @keyframes spin { to { transform: rotate(360deg) } }
265
- `;import{spawn as HM}from"node:child_process";import*as Aw from"node:fs/promises";import{homedir as fM}from"node:os";import*as nY from"node:path";import*as Q0 from"node:process";function Xw(){return nY.join(fM(),".stacks","rpx")}function $6($=Xw()){return nY.join($,"daemon.pid")}async function e5($=Xw()){try{let w=await Aw.readFile($6($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function RM($=Xw()){await Aw.unlink($6($)).catch(()=>{})}function MM(){let $=Q0.execPath,w=nY.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&Q0.argv[1])return[$,Q0.argv[1],"daemon:start"];return[$,"daemon:start"]}async function w6($={}){let w=$.rpxDir??Xw(),Y=$.verbose??!1;await Jw({rpxDir:w,verbose:Y}).catch((z)=>{N("daemon",`DNS reconcile before ensureDaemonRunning: ${z}`,Y)});let A=await e5(w);if(A!==null&&r0(A))return N("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)N("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await RM(w);await Aw.mkdir(w,{recursive:!0});let X=$.spawnCommand??MM();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");N("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=HM(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??Q0.cwd(),env:$.spawnEnv?{...Q0.env,...$.spawnEnv}:Q0.env});J.unref();let U=null;J.once("error",(z)=>{U=z});let B=$.startupTimeoutMs??5000,W=$.pollIntervalMs??50,j=Date.now()+B;while(Date.now()<j){if(U)throw U;let z=await e5(w);if(z!==null&&r0(z))return N("daemon",`daemon registered with pid=${z}`,Y),{pid:z,spawned:!0};await new Promise((G)=>setTimeout(G,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${B}ms (rpxDir=${w})`)}var bB=t(()=>{i$();V8();L8();O8();vY();S8();QB();OB();DB();bY();DY();e1();wY();X0()});import*as Cw from"node:fs/promises";import{homedir as IM}from"node:os";import*as uB from"node:path";function A6(){return uB.join(IM(),".stacks","rpx")}function vB($=A6()){return uB.join($,VM)}async function u8($=A6()){try{let w=await Cw.readFile(vB($),"utf8"),Y=JSON.parse(w);if(Y.version!==b8||!Array.isArray(Y.resolvers))return null;return{version:b8,resolvers:Y.resolvers.filter((A)=>typeof A==="string"),domains:Array.isArray(Y.domains)?Y.domains.filter((A)=>typeof A==="string"):[],ownerPid:typeof Y.ownerPid==="number"?Y.ownerPid:null,updatedAt:typeof Y.updatedAt==="string"?Y.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function X6($,w){await Cw.mkdir($,{recursive:!0}),await Cw.writeFile(vB($),`${JSON.stringify(w,null,2)}
266
- `,"utf8")}async function cB($){await Cw.rm(vB($),{force:!0})}function J6($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;if(!/^[a-z0-9.-]+$/.test(w))return null;return w}function CM($){let w=J6($);if(!w)return null;let Y=w.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function iB($){let w=new Set;for(let Y of $){let A=CM(Y);if(A)w.add(A)}return Array.from(w).sort()}function mB($){let w=new Set;for(let Y of $){let A=J6(Y);if(A)w.add(A)}return Array.from(w).sort()}var b8=1,VM="dns-state.json",Y6;var U6=t(()=>{Y6=["com","test","dev","app","page","local","localhost","example","invalid"]});var c8={};Gj(c8,{tearDownDevelopmentDns:()=>Vw,syncDevelopmentDnsFromRegistry:()=>iw,stopDnsServer:()=>gB,startDnsServer:()=>N6,setupResolver:()=>DM,setupDevelopmentDns:()=>pB,resolverFilePath:()=>YY,removeResolver:()=>PM,removeLegacyTldResolvers:()=>nB,reconcileStaleDevelopmentDns:()=>Jw,isRpxDevelopmentDnsAnswering:()=>q6,isDnsServerRunning:()=>OM,contentLooksLikeRpxResolver:()=>E6,RPX_RESOLVER_MARKER:()=>z6,DNS_PORT:()=>rY});import W6 from"node:dgram";import*as B6 from"node:fs/promises";import*as j6 from"node:path";import*as Uw from"node:process";function K6($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function F6($,w,Y=0){let A=[],X=w,J=0;while(!0){if(X>=$.length||++J>128)break;let U=$[X];if(U===0){X++;break}if((U&192)===192){if(X+1>=$.length||Y>=10)break;let B=$.readUInt16BE(X)&16383,{name:W}=F6($,B,Y+1);if(W)A.push(W);X+=2;break}if(X++,X+U>$.length)break;A.push($.subarray(X,X+U).toString("ascii")),X+=U}return{name:A.join("."),newOffset:X}}function QM($,w){let{name:Y,newOffset:A}=F6($,w),X=$.readUInt16BE(A),J=$.readUInt16BE(A+2);return{question:{name:Y,type:X,class:J},newOffset:A+4}}function pY($){let w=$.split("."),Y=[];for(let A of w)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function yM($,w,Y){let A=[],X=Buffer.alloc(12);X.writeUInt16BE($,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(pY(w.name));let J=Buffer.alloc(4);J.writeUInt16BE(w.type,0),J.writeUInt16BE(w.class,2),A.push(J),A.push(pY(w.name));let U=Buffer.alloc(10);if(U.writeUInt16BE(w.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),w.type===1){U.writeUInt16BE(4,8),A.push(U);let B=Y.split(".").map((W)=>Number.parseInt(W,10));A.push(Buffer.from(B))}else if(w.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,pY(w.name),J]);return Buffer.concat(A)}function LM($,w){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE($,0),A.writeUInt16BE(33155,2),A.writeUInt16BE(1,4),A.writeUInt16BE(0,6),A.writeUInt16BE(0,8),A.writeUInt16BE(0,10),Y.push(A),Y.push(pY(w.name));let X=Buffer.alloc(4);return X.writeUInt16BE(w.type,0),X.writeUInt16BE(w.class,2),Y.push(X),Buffer.concat(Y)}async function N6($,w){if(Uw.platform!=="darwin")return!1;let Y=mB($);if(Y.length===0)return!1;if(t0){for(let A of Y)v8.add(A);return N("dns","DNS server already running — merged domains",w),!0}return v8=new Set(Y),new Promise((A)=>{t0=W6.createSocket("udp4"),t0.on("error",(X)=>{N("dns",`DNS server error: ${X.message}`,w),t0?.close(),t0=null,A(!1)}),t0.on("message",(X,J)=>{try{let U=K6(X),{question:B}=QM(X,12);N("dns",`Query for ${B.name} type ${B.type} from ${J.address}`,w);let W=B.name.toLowerCase(),j=!1;for(let G of v8)if(W===G||W.endsWith(`.${G}`)){j=!0;break}let z;if(j&&(B.type===1||B.type===28))z=yM(U.id,B,"127.0.0.1"),N("dns",`Responding with localhost for ${B.name}`,w);else z=LM(U.id,B),N("dns",`NXDOMAIN for ${B.name}`,w);t0?.send(z,J.port,J.address)}catch(U){N("dns",`Error processing DNS query: ${U}`,w)}}),t0.on("listening",()=>{let X=t0?.address();N("dns",`DNS server listening on ${X?.address}:${X?.port}`,w),A(!0)});try{t0.bind(rY,"127.0.0.1")}catch(X){N("dns",`Failed to bind DNS server: ${X}`,w),A(!1)}})}function gB($){if(t0)N("dns","Stopping DNS server",$),t0.close(),t0=null,v8=new Set}function OM(){return t0!==null}async function q6($,w=500){let Y=$.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let X=W6.createSocket("udp4"),J=setTimeout(()=>{X.close(),A(!1)},w);X.on("message",(B)=>{clearTimeout(J),X.close();try{let W=K6(B);A(W.ancount>0)}catch{A(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),A(!1)});let U=_M(Y,1);X.send(U,rY,"127.0.0.1",(B)=>{if(B)clearTimeout(J),X.close(),A(!1)})})}function _M($,w){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([pY($),Buffer.from([0,w,0,1])]);return Buffer.concat([Y,A])}function SM(){return`${z6}
265
+ `;import{spawn as fM}from"node:child_process";import*as Aw from"node:fs/promises";import{homedir as RM}from"node:os";import*as nY from"node:path";import*as Q0 from"node:process";function Xw(){return nY.join(RM(),".stacks","rpx")}function w6($=Xw()){return nY.join($,"daemon.pid")}async function $6($=Xw()){try{let w=await Aw.readFile(w6($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function MM($=Xw()){await Aw.unlink(w6($)).catch(()=>{})}function IM(){let $=Q0.execPath,w=nY.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&Q0.argv[1])return[$,Q0.argv[1],"daemon:start"];return[$,"daemon:start"]}async function Y6($={}){let w=$.rpxDir??Xw(),Y=$.verbose??!1;await Jw({rpxDir:w,verbose:Y}).catch((z)=>{N("daemon",`DNS reconcile before ensureDaemonRunning: ${z}`,Y)});let A=await $6(w);if(A!==null&&r0(A))return N("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)N("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await MM(w);await Aw.mkdir(w,{recursive:!0});let X=$.spawnCommand??IM();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");N("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=fM(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??Q0.cwd(),env:$.spawnEnv?{...Q0.env,...$.spawnEnv}:Q0.env});J.unref();let U=null;J.once("error",(z)=>{U=z});let B=$.startupTimeoutMs??5000,W=$.pollIntervalMs??50,j=Date.now()+B;while(Date.now()<j){if(U)throw U;let z=await $6(w);if(z!==null&&r0(z))return N("daemon",`daemon registered with pid=${z}`,Y),{pid:z,spawned:!0};await new Promise((G)=>setTimeout(G,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${B}ms (rpxDir=${w})`)}var uB=t(()=>{i$();V8();L8();O8();vY();S8();yB();_B();xB();bY();kY();e1();wY();X0()});import*as Cw from"node:fs/promises";import{homedir as VM}from"node:os";import*as vB from"node:path";function X6(){return vB.join(VM(),".stacks","rpx")}function cB($=X6()){return vB.join($,CM)}async function u8($=X6()){try{let w=await Cw.readFile(cB($),"utf8"),Y=JSON.parse(w);if(Y.version!==b8||!Array.isArray(Y.resolvers))return null;return{version:b8,resolvers:Y.resolvers.filter((A)=>typeof A==="string"),domains:Array.isArray(Y.domains)?Y.domains.filter((A)=>typeof A==="string"):[],ownerPid:typeof Y.ownerPid==="number"?Y.ownerPid:null,updatedAt:typeof Y.updatedAt==="string"?Y.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function J6($,w){await Cw.mkdir($,{recursive:!0}),await Cw.writeFile(cB($),`${JSON.stringify(w,null,2)}
266
+ `,"utf8")}async function iB($){await Cw.rm(cB($),{force:!0})}function U6($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;if(!/^[a-z0-9.-]+$/.test(w))return null;return w}function QM($){let w=U6($);if(!w)return null;let Y=w.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function mB($){let w=new Set;for(let Y of $){let A=QM(Y);if(A)w.add(A)}return Array.from(w).sort()}function gB($){let w=new Set;for(let Y of $){let A=U6(Y);if(A)w.add(A)}return Array.from(w).sort()}var b8=1,CM="dns-state.json",A6;var W6=t(()=>{A6=["com","test","dev","app","page","local","localhost","example","invalid"]});var c8={};Kj(c8,{tearDownDevelopmentDns:()=>Vw,syncDevelopmentDnsFromRegistry:()=>mw,stopDnsServer:()=>dB,startDnsServer:()=>q6,setupResolver:()=>xM,setupDevelopmentDns:()=>rB,resolverFilePath:()=>YY,removeResolver:()=>bM,removeLegacyTldResolvers:()=>pB,reconcileStaleDevelopmentDns:()=>Jw,isRpxDevelopmentDnsAnswering:()=>E6,isDnsServerRunning:()=>_M,contentLooksLikeRpxResolver:()=>T6,RPX_RESOLVER_MARKER:()=>G6,DNS_PORT:()=>rY});import B6 from"node:dgram";import*as j6 from"node:fs/promises";import*as z6 from"node:path";import*as Uw from"node:process";function F6($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function N6($,w,Y=0){let A=[],X=w,J=0;while(!0){if(X>=$.length||++J>128)break;let U=$[X];if(U===0){X++;break}if((U&192)===192){if(X+1>=$.length||Y>=10)break;let B=$.readUInt16BE(X)&16383,{name:W}=N6($,B,Y+1);if(W)A.push(W);X+=2;break}if(X++,X+U>$.length)break;A.push($.subarray(X,X+U).toString("ascii")),X+=U}return{name:A.join("."),newOffset:X}}function yM($,w){let{name:Y,newOffset:A}=N6($,w),X=$.readUInt16BE(A),J=$.readUInt16BE(A+2);return{question:{name:Y,type:X,class:J},newOffset:A+4}}function pY($){let w=$.split("."),Y=[];for(let A of w)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function LM($,w,Y){let A=[],X=Buffer.alloc(12);X.writeUInt16BE($,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(pY(w.name));let J=Buffer.alloc(4);J.writeUInt16BE(w.type,0),J.writeUInt16BE(w.class,2),A.push(J),A.push(pY(w.name));let U=Buffer.alloc(10);if(U.writeUInt16BE(w.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),w.type===1){U.writeUInt16BE(4,8),A.push(U);let B=Y.split(".").map((W)=>Number.parseInt(W,10));A.push(Buffer.from(B))}else if(w.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,pY(w.name),J]);return Buffer.concat(A)}function OM($,w){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE($,0),A.writeUInt16BE(33155,2),A.writeUInt16BE(1,4),A.writeUInt16BE(0,6),A.writeUInt16BE(0,8),A.writeUInt16BE(0,10),Y.push(A),Y.push(pY(w.name));let X=Buffer.alloc(4);return X.writeUInt16BE(w.type,0),X.writeUInt16BE(w.class,2),Y.push(X),Buffer.concat(Y)}async function q6($,w){if(Uw.platform!=="darwin")return!1;let Y=gB($);if(Y.length===0)return!1;if(t0){for(let A of Y)v8.add(A);return N("dns","DNS server already running — merged domains",w),!0}return v8=new Set(Y),new Promise((A)=>{t0=B6.createSocket("udp4"),t0.on("error",(X)=>{N("dns",`DNS server error: ${X.message}`,w),t0?.close(),t0=null,A(!1)}),t0.on("message",(X,J)=>{try{let U=F6(X),{question:B}=yM(X,12);N("dns",`Query for ${B.name} type ${B.type} from ${J.address}`,w);let W=B.name.toLowerCase(),j=!1;for(let G of v8)if(W===G||W.endsWith(`.${G}`)){j=!0;break}let z;if(j&&(B.type===1||B.type===28))z=LM(U.id,B,"127.0.0.1"),N("dns",`Responding with localhost for ${B.name}`,w);else z=OM(U.id,B),N("dns",`NXDOMAIN for ${B.name}`,w);t0?.send(z,J.port,J.address)}catch(U){N("dns",`Error processing DNS query: ${U}`,w)}}),t0.on("listening",()=>{let X=t0?.address();N("dns",`DNS server listening on ${X?.address}:${X?.port}`,w),A(!0)});try{t0.bind(rY,"127.0.0.1")}catch(X){N("dns",`Failed to bind DNS server: ${X}`,w),A(!1)}})}function dB($){if(t0)N("dns","Stopping DNS server",$),t0.close(),t0=null,v8=new Set}function _M(){return t0!==null}async function E6($,w=500){let Y=$.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let X=B6.createSocket("udp4"),J=setTimeout(()=>{X.close(),A(!1)},w);X.on("message",(B)=>{clearTimeout(J),X.close();try{let W=F6(B);A(W.ancount>0)}catch{A(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),A(!1)});let U=SM(Y,1);X.send(U,rY,"127.0.0.1",(B)=>{if(B)clearTimeout(J),X.close(),A(!1)})})}function SM($,w){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([pY($),Buffer.from([0,w,0,1])]);return Buffer.concat([Y,A])}function ZM(){return`${G6}
267
267
  nameserver 127.0.0.1
268
268
  port ${rY}
269
- `}function YY($){return j6.join(G6,$)}function E6($){return $.includes("127.0.0.1")&&$.includes(String(rY))}async function ZM($){try{return await B6.readFile(YY($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function dB($){if(Uw.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),b1));if(!A()&&!Y()){N("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),N("dns","DNS cache flushed",$)}catch(X){N("dns",`Could not flush DNS cache: ${X}`,$)}}function T6($){if(!/^[a-z0-9.-]+$/.test($))throw Error(`refusing unsafe resolver basename: ${JSON.stringify($)}`)}async function hM($,w){T6($);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),b1)),A=SM().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${G6} && printf "%b" "${A}" > ${YY($)}'`;Y(X),N("dns",`Created ${YY($)}`,w)}async function kM($,w){T6($);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),b1));Y(`rm -f ${YY($)}`),N("dns",`Removed ${YY($)}`,w)}async function DM($,w){return pB({domains:w??[],verbose:$})}async function xM($,w){if(Uw.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),b1));if(!A()&&!Y())return N("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let X of $)await hM(X,w);return await dB(w),!0}catch(X){return N("dns",`Failed to create resolver file: ${X}`,w),!1}}async function lB($,w){if(Uw.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),b1));if(!A()&&!Y())return;try{for(let X of $)await kM(X,w);await dB(w)}catch(X){N("dns",`Failed to remove resolver files: ${X}`,w)}}async function nB($){if(Uw.platform!=="darwin")return[];let w=[];for(let Y of Y6){let A=await ZM(Y);if(A&&E6(A))await lB([Y],$),w.push(Y)}return w}async function pB($){let w=$.rpxDir??Xw(),Y=mB($.domains);if(Y.length===0)return!1;let A=iB(Y),X=await N6(Y,$.verbose);if(!X){let B=Y[0];if(B&&await q6(B))X=!0;else N("dns","Dev DNS server not available on 127.0.0.1:15353",$.verbose)}if(!X)return!1;if(!await xM(A,$.verbose))return!1;let U={version:b8,resolvers:A,domains:Y,ownerPid:$.ownerPid??Uw.pid,updatedAt:new Date().toISOString()};return await X6(w,U),!0}async function iw($,w={}){let Y=$.map((W)=>W.to).filter(Boolean),A=w.rpxDir??Xw(),X=iB(Y),B=((await u8(A))?.resolvers??[]).filter((W)=>!X.includes(W));if(B.length>0)await lB(B,w.verbose);if(X.length===0){gB(w.verbose),await cB(A);return}await pB({domains:Y,rpxDir:A,verbose:w.verbose,ownerPid:w.ownerPid??Uw.pid})}async function Vw($={}){let w=$.rpxDir??Xw();gB($.verbose);let A=(await u8(w))?.resolvers??[];await lB(A,$.verbose),await nB($.verbose),await cB(w)}async function PM($){await Vw({verbose:$})}async function Jw($={}){let w=$.rpxDir??Xw(),Y=await u8(w),A=Y?.ownerPid!=null&&r0(Y.ownerPid);if(Y&&!A){N("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,$.verbose),await Vw($);return}let X=await nB($.verbose);if(X.length>0)N("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,$.verbose);await dB($.verbose)}var rY=15353,z6="# managed-by: rpx",G6="/etc/resolver",t0=null,v8;var wY=t(()=>{bB();U6();e1();X0();v8=new Set});import{dirname as z4,join as G4}from"path";import*as x0 from"process";import{fileURLToPath as K4}from"url";import{existsSync as AK}from"node:fs";import BJ from"node:fs/promises";import Kj from"node:os";import jJ from"node:path";import Sw from"node:process";import{EventEmitter as XK}from"node:events";import Bw from"node:process";import Fj from"node:process";import FJ from"node:process";import YA from"node:process";import BY from"node:process";import Ej from"node:tty";import lK,{stdin as h4,stdout as k4}from"node:process";import Hj,{stdin as rK,stdout as tK}from"node:process";import aK from"node:readline";class Rj{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=Kj.homedir(),w=jJ.join($,".config","clapp");this.configPath=jJ.join(w,"telemetry.json")}async isEnabled(){if(Sw.env.DO_NOT_TRACK==="1"||Sw.env.DO_NOT_TRACK==="true")return!1;if(Sw.env.NO_TELEMETRY==="1"||Sw.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let A={event:$,...w,timestamp:Date.now(),platform:Kj.platform(),nodeVersion:Sw.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:Sw.env.DO_NOT_TRACK==="1"||Sw.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(AK(this.configPath)){let $=await BJ.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=jJ.dirname(this.configPath);await BJ.mkdir(w,{recursive:!0}),await BJ.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var R4=new Rj;function JK($,w={}){let Y={_:[]},A=w.alias||{},X=new Set(w.boolean||[]),J={};for(let B of Object.keys(A))for(let W of A[B])J[W]=B;for(let B of X)if(A[B])for(let W of A[B])X.add(W);function U(B,W){let j=J[B]||B;if(Y[j]=W,A[j])for(let z of A[j])Y[z]=W;if(J[B]&&A[J[B]])for(let z of A[J[B]])Y[z]=W;Y[B]=W}for(let B=0;B<$.length;B++){let W=$[B];if(W==="--"){Y._.push(...$.slice(B+1));break}if(W.startsWith("--")){let j=W.indexOf("=");if(j!==-1){let z=W.slice(2,j),G=W.slice(j+1);U(z,G)}else{let z=W.slice(2);if(z.startsWith("no-")){let K=z.slice(3);U(K,!1);continue}let G=J[z]||z;if(X.has(G)||X.has(z))U(z,!0);else{let K=$[B+1];if(K!==void 0&&!K.startsWith("-"))U(z,K),B++;else U(z,!0)}}}else if(W.startsWith("-")&&W.length>1){let j=W.slice(1);for(let z=0;z<j.length;z++){let G=j[z],K=J[G]||G;if(z===j.length-1&&!X.has(K)&&!X.has(G)){let F=$[B+1];if(F!==void 0&&!F.startsWith("-"))U(G,F),B++;else U(G,!0)}else U(G,!0)}}else Y._.push(W)}return Y}function KJ($){return $.replace(/[<[].+/,"").trim()}function UK($){let w=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(B)=>{let W=!1,j=B[1];if(j.startsWith("..."))j=j.slice(3),W=!0;return{required:B[0].startsWith("<"),value:j,variadic:W}},J;while(J=w.exec($))A.push(X(J));let U;while(U=Y.exec($))A.push(X(U));return A}function WK($){let w={alias:{},boolean:[]};for(let[Y,A]of $.entries()){if(A.names.length>1)w.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!$.some((J,U)=>{return U!==Y&&J.names.some((B)=>A.names.includes(B))&&typeof J.required==="boolean"}))w.boolean.push(A.names[0])}else w.boolean.push(A.names[0])}return w}function Nj($){return $.reduce((w,Y)=>w.length>=Y.length?w:Y,"")}function zJ($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function BK($){return $.replace(/([a-z])-([a-z])/g,(w,Y,A)=>{return Y+A.toUpperCase()})}function jK($,w,Y){let A=0,X=w.length,J=$,U;for(;A<X;++A)U=J[w[A]],J=J[w[A]]=A===X-1?Y:U!=null?U:!!~w[A+1].indexOf(".")||!(+w[A+1]>-1)?{}:[]}function zK($,w){for(let Y of Object.keys(w)){let A=w[Y];if(A.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof A.transformFunction==="function")$[Y]=$[Y].map(A.transformFunction)}}}function GK($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function Mj($){return $.split(".").map((w,Y)=>{return Y===0?BK(w):w}).join(".")}class wA extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
269
+ `}function YY($){return z6.join(K6,$)}function T6($){return $.includes("127.0.0.1")&&$.includes(String(rY))}async function hM($){try{return await j6.readFile(YY($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function lB($){if(Uw.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),u1));if(!A()&&!Y()){N("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),N("dns","DNS cache flushed",$)}catch(X){N("dns",`Could not flush DNS cache: ${X}`,$)}}function H6($){if(!/^[a-z0-9.-]+$/.test($))throw Error(`refusing unsafe resolver basename: ${JSON.stringify($)}`)}async function DM($,w){H6($);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),u1)),A=ZM().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${K6} && printf "%b" "${A}" > ${YY($)}'`;Y(X),N("dns",`Created ${YY($)}`,w)}async function kM($,w){H6($);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),u1));Y(`rm -f ${YY($)}`),N("dns",`Removed ${YY($)}`,w)}async function xM($,w){return rB({domains:w??[],verbose:$})}async function PM($,w){if(Uw.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),u1));if(!A()&&!Y())return N("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let X of $)await DM(X,w);return await lB(w),!0}catch(X){return N("dns",`Failed to create resolver file: ${X}`,w),!1}}async function nB($,w){if(Uw.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),u1));if(!A()&&!Y())return;try{for(let X of $)await kM(X,w);await lB(w)}catch(X){N("dns",`Failed to remove resolver files: ${X}`,w)}}async function pB($){if(Uw.platform!=="darwin")return[];let w=[];for(let Y of A6){let A=await hM(Y);if(A&&T6(A))await nB([Y],$),w.push(Y)}return w}async function rB($){let w=$.rpxDir??Xw(),Y=gB($.domains);if(Y.length===0)return!1;let A=mB(Y),X=await q6(Y,$.verbose);if(!X){let B=Y[0];if(B&&await E6(B))X=!0;else N("dns","Dev DNS server not available on 127.0.0.1:15353",$.verbose)}if(!X)return!1;if(!await PM(A,$.verbose))return!1;let U={version:b8,resolvers:A,domains:Y,ownerPid:$.ownerPid??Uw.pid,updatedAt:new Date().toISOString()};return await J6(w,U),!0}async function mw($,w={}){let Y=$.map((W)=>W.to).filter(Boolean),A=w.rpxDir??Xw(),X=mB(Y),B=((await u8(A))?.resolvers??[]).filter((W)=>!X.includes(W));if(B.length>0)await nB(B,w.verbose);if(X.length===0){dB(w.verbose),await iB(A);return}await rB({domains:Y,rpxDir:A,verbose:w.verbose,ownerPid:w.ownerPid??Uw.pid})}async function Vw($={}){let w=$.rpxDir??Xw();dB($.verbose);let A=(await u8(w))?.resolvers??[];await nB(A,$.verbose),await pB($.verbose),await iB(w)}async function bM($){await Vw({verbose:$})}async function Jw($={}){let w=$.rpxDir??Xw(),Y=await u8(w),A=Y?.ownerPid!=null&&r0(Y.ownerPid);if(Y&&!A){N("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,$.verbose),await Vw($);return}let X=await pB($.verbose);if(X.length>0)N("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,$.verbose);await lB($.verbose)}var rY=15353,G6="# managed-by: rpx",K6="/etc/resolver",t0=null,v8;var wY=t(()=>{uB();W6();e1();X0();v8=new Set});import{dirname as K4,join as F4}from"path";import*as x0 from"process";import{fileURLToPath as N4}from"url";import{existsSync as XK}from"node:fs";import BJ from"node:fs/promises";import Fj from"node:os";import jJ from"node:path";import Sw from"node:process";import{EventEmitter as JK}from"node:events";import Bw from"node:process";import Nj from"node:process";import FJ from"node:process";import YA from"node:process";import BY from"node:process";import Tj from"node:tty";import nK,{stdin as k4,stdout as x4}from"node:process";import fj,{stdin as tK,stdout as aK}from"node:process";import sK from"node:readline";class Mj{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=Fj.homedir(),w=jJ.join($,".config","clapp");this.configPath=jJ.join(w,"telemetry.json")}async isEnabled(){if(Sw.env.DO_NOT_TRACK==="1"||Sw.env.DO_NOT_TRACK==="true")return!1;if(Sw.env.NO_TELEMETRY==="1"||Sw.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let A={event:$,...w,timestamp:Date.now(),platform:Fj.platform(),nodeVersion:Sw.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:Sw.env.DO_NOT_TRACK==="1"||Sw.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(XK(this.configPath)){let $=await BJ.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=jJ.dirname(this.configPath);await BJ.mkdir(w,{recursive:!0}),await BJ.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var I4=new Mj;function UK($,w={}){let Y={_:[]},A=w.alias||{},X=new Set(w.boolean||[]),J={};for(let B of Object.keys(A))for(let W of A[B])J[W]=B;for(let B of X)if(A[B])for(let W of A[B])X.add(W);function U(B,W){let j=J[B]||B;if(Y[j]=W,A[j])for(let z of A[j])Y[z]=W;if(J[B]&&A[J[B]])for(let z of A[J[B]])Y[z]=W;Y[B]=W}for(let B=0;B<$.length;B++){let W=$[B];if(W==="--"){Y._.push(...$.slice(B+1));break}if(W.startsWith("--")){let j=W.indexOf("=");if(j!==-1){let z=W.slice(2,j),G=W.slice(j+1);U(z,G)}else{let z=W.slice(2);if(z.startsWith("no-")){let K=z.slice(3);U(K,!1);continue}let G=J[z]||z;if(X.has(G)||X.has(z))U(z,!0);else{let K=$[B+1];if(K!==void 0&&!K.startsWith("-"))U(z,K),B++;else U(z,!0)}}}else if(W.startsWith("-")&&W.length>1){let j=W.slice(1);for(let z=0;z<j.length;z++){let G=j[z],K=J[G]||G;if(z===j.length-1&&!X.has(K)&&!X.has(G)){let F=$[B+1];if(F!==void 0&&!F.startsWith("-"))U(G,F),B++;else U(G,!0)}else U(G,!0)}}else Y._.push(W)}return Y}function KJ($){return $.replace(/[<[].+/,"").trim()}function WK($){let w=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(B)=>{let W=!1,j=B[1];if(j.startsWith("..."))j=j.slice(3),W=!0;return{required:B[0].startsWith("<"),value:j,variadic:W}},J;while(J=w.exec($))A.push(X(J));let U;while(U=Y.exec($))A.push(X(U));return A}function BK($){let w={alias:{},boolean:[]};for(let[Y,A]of $.entries()){if(A.names.length>1)w.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!$.some((J,U)=>{return U!==Y&&J.names.some((B)=>A.names.includes(B))&&typeof J.required==="boolean"}))w.boolean.push(A.names[0])}else w.boolean.push(A.names[0])}return w}function qj($){return $.reduce((w,Y)=>w.length>=Y.length?w:Y,"")}function zJ($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function jK($){return $.replace(/([a-z])-([a-z])/g,(w,Y,A)=>{return Y+A.toUpperCase()})}function zK($,w,Y){let A=0,X=w.length,J=$,U;for(;A<X;++A)U=J[w[A]],J=J[w[A]]=A===X-1?Y:U!=null?U:!!~w[A+1].indexOf(".")||!(+w[A+1]>-1)?{}:[]}function GK($,w){for(let Y of Object.keys(w)){let A=w[Y];if(A.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof A.transformFunction==="function")$[Y]=$[Y].map(A.transformFunction)}}}function KK($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function Ij($){return $.split(".").map((w,Y)=>{return Y===0?jK(w):w}).join(".")}class wA extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
270
270
 
271
271
  Stack trace:
272
- ${this.stack}`;return this.message}}function KK(){let{env:$}=Fj,{TERM:w,TERM_PROGRAM:Y}=$;if(Fj.platform!=="win32")return w!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||w==="xterm-256color"||w==="alacritty"||w==="rxvt-unicode"||w==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var JA="\x1B",j0=`${JA}[`;var D$={to($,w){if(!w)return`${j0}${$+1}G`;return`${j0}${w+1};${$+1}H`},move($,w){let Y="";if($<0)Y+=`${j0}${-$}D`;else if($>0)Y+=`${j0}${$}C`;if(w<0)Y+=`${j0}${-w}A`;else if(w>0)Y+=`${j0}${w}B`;return Y},up:($=1)=>`${j0}${$}A`,down:($=1)=>`${j0}${$}B`,forward:($=1)=>`${j0}${$}C`,backward:($=1)=>`${j0}${$}D`,nextLine:($=1)=>`${j0}E`.repeat($),prevLine:($=1)=>`${j0}F`.repeat($),left:`${j0}G`,hide:`${j0}?25l`,show:`${j0}?25h`,save:`${JA}7`,restore:`${JA}8`};var GJ={screen:`${j0}2J`,up:($=1)=>`${j0}1J`.repeat($),down:($=1)=>`${j0}J`.repeat($),line:`${j0}2K`,lineEnd:`${j0}K`,lineStart:`${j0}1K`,lines($){let w="";for(let Y=0;Y<$;Y++)w+=this.line+(Y<$-1?D$.up():"");if($)w+=D$.left;return w}},C4={screen:`${JA}c`};function FK($,w){let Y=[];for(let A=0;A<=w.length;A++)Y[A]=[A];for(let A=0;A<=$.length;A++)Y[0][A]=A;for(let A=1;A<=w.length;A++)for(let X=1;X<=$.length;X++)if(w.charAt(A-1)===$.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[w.length][$.length]}function Ij($,w,Y=2,A=3){return w.map((X)=>({cmd:X,distance:FK($,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class Vj{rawName;description;name;names;isBoolean;required;config;negated;constructor($,w,Y){if(this.rawName=$,this.description=w,this.config=Object.assign({},Y),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=KJ($).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return Mj(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($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var y4=FJ.argv,NK=`${FJ.platform}-${FJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,qj=YA.argv,qK=`${YA.platform}-${YA.arch} node-${YA.version}`;class NJ{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,Y,A){this.rawName=$,this.description=w,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=KJ($);let X=KJ($),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=UK($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,Y){let A=new Vj($,w,Y);return this.options.push(A),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof qJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){return $=$.split(".")[0],!!this.options.find((w)=>{return w.names.includes($)})}outputHelp(){let{name:$,commands:w}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${$}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let W=Nj(w.map((F)=>F.rawName)),j=new Map,z=[];for(let F of w)if(F.namespace){if(!j.has(F.namespace))j.set(F.namespace,[]);j.get(F.namespace).push(F)}else z.push(F);let G="";if(z.length>0)G+=z.map((F)=>{return` ${zJ(F.rawName,W.length)} ${F.description}`}).join(`
272
+ ${this.stack}`;return this.message}}function FK(){let{env:$}=Nj,{TERM:w,TERM_PROGRAM:Y}=$;if(Nj.platform!=="win32")return w!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||w==="xterm-256color"||w==="alacritty"||w==="rxvt-unicode"||w==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var JA="\x1B",j0=`${JA}[`;var k$={to($,w){if(!w)return`${j0}${$+1}G`;return`${j0}${w+1};${$+1}H`},move($,w){let Y="";if($<0)Y+=`${j0}${-$}D`;else if($>0)Y+=`${j0}${$}C`;if(w<0)Y+=`${j0}${-w}A`;else if(w>0)Y+=`${j0}${w}B`;return Y},up:($=1)=>`${j0}${$}A`,down:($=1)=>`${j0}${$}B`,forward:($=1)=>`${j0}${$}C`,backward:($=1)=>`${j0}${$}D`,nextLine:($=1)=>`${j0}E`.repeat($),prevLine:($=1)=>`${j0}F`.repeat($),left:`${j0}G`,hide:`${j0}?25l`,show:`${j0}?25h`,save:`${JA}7`,restore:`${JA}8`};var GJ={screen:`${j0}2J`,up:($=1)=>`${j0}1J`.repeat($),down:($=1)=>`${j0}J`.repeat($),line:`${j0}2K`,lineEnd:`${j0}K`,lineStart:`${j0}1K`,lines($){let w="";for(let Y=0;Y<$;Y++)w+=this.line+(Y<$-1?k$.up():"");if($)w+=k$.left;return w}},y4={screen:`${JA}c`};function NK($,w){let Y=[];for(let A=0;A<=w.length;A++)Y[A]=[A];for(let A=0;A<=$.length;A++)Y[0][A]=A;for(let A=1;A<=w.length;A++)for(let X=1;X<=$.length;X++)if(w.charAt(A-1)===$.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[w.length][$.length]}function Vj($,w,Y=2,A=3){return w.map((X)=>({cmd:X,distance:NK($,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class Cj{rawName;description;name;names;isBoolean;required;config;negated;constructor($,w,Y){if(this.rawName=$,this.description=w,this.config=Object.assign({},Y),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=KJ($).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return Ij(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($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var O4=FJ.argv,qK=`${FJ.platform}-${FJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,Ej=YA.argv,EK=`${YA.platform}-${YA.arch} node-${YA.version}`;class NJ{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,Y,A){this.rawName=$,this.description=w,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=KJ($);let X=KJ($),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=WK($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,Y){let A=new Cj($,w,Y);return this.options.push(A),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof qJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){return $=$.split(".")[0],!!this.options.find((w)=>{return w.names.includes($)})}outputHelp(){let{name:$,commands:w}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${$}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let W=qj(w.map((F)=>F.rawName)),j=new Map,z=[];for(let F of w)if(F.namespace){if(!j.has(F.namespace))j.set(F.namespace,[]);j.get(F.namespace).push(F)}else z.push(F);let G="";if(z.length>0)G+=z.map((F)=>{return` ${zJ(F.rawName,W.length)} ${F.description}`}).join(`
273
273
  `);let K=Array.from(j.keys()).sort();for(let F of K){let T=j.get(F);if(G.length>0)G+=`
274
274
 
275
275
  `;G+=` ${F}:
276
276
  `,G+=T.map((q)=>{return` ${zJ(q.rawName,W.length-2)} ${q.description}`}).join(`
277
277
  `)}J.push({title:"Commands",body:G}),J.push({title:"For more info, run any command with the `--help` flag",body:w.map((F)=>` $ ${$}${F.displayName===""?"":` ${F.displayName}`} --help`).join(`
278
- `)})}let B=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)B=B.filter((W)=>W.name!=="version");if(B.length>0){let W=Nj(B.map((j)=>j.rawName));J.push({title:"Options",body:B.map((j)=>{return` ${zJ(j.rawName,W.length)} ${j.description} ${j.config.default===void 0?"":`(default: ${j.config.default})`}`}).join(`
278
+ `)})}let B=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)B=B.filter((W)=>W.name!=="version");if(B.length>0){let W=qj(B.map((j)=>j.rawName));J.push({title:"Options",body:B.map((j)=>{return` ${zJ(j.rawName,W.length)} ${j.description} ${j.config.default===void 0?"":`(default: ${j.config.default})`}`}).join(`
279
279
  `)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((W)=>{if(typeof W==="function")return W($);return W}).join(`
280
280
  `)});if(X)J=X(J)||J;console.log(J.map((W)=>{return W.title?`${W.title}:
281
281
  ${W.body}`:W.body}).join(`
282
282
 
283
- `))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?NK:qK}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let Y=this.args.filter((X)=>X.required).slice(this.cli.args.length),A=Y.map((X)=>`<${X.value}>`).join(" ");throw new wA(`Missing required argument${Y.length>1?"s":""}: ${A}
283
+ `))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?qK:EK}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let Y=this.args.filter((X)=>X.required).slice(this.cli.args.length),A=Y.map((X)=>`<${X.value}>`).join(" ");throw new wA(`Missing required argument${Y.length>1?"s":""}: ${A}
284
284
 
285
- Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys($))if(Y!=="--"&&!this.hasOption(Y)&&!w.hasOption(Y)){let X=[...w.options,...this.options].flatMap((W)=>W.names),J=Y.length>1?`--${Y}`:`-${Y}`,U=Ij(Y,X),B=`Unknown option \`${J}\``;if(U.length>0)B+=`
285
+ Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys($))if(Y!=="--"&&!this.hasOption(Y)&&!w.hasOption(Y)){let X=[...w.options,...this.options].flatMap((W)=>W.names),J=Y.length>1?`--${Y}`:`-${Y}`,U=Vj(Y,X),B=`Unknown option \`${J}\``;if(U.length>0)B+=`
286
286
 
287
287
  Did you mean one of these?`,U.forEach((W)=>{let j=W.length>1?`--${W}`:`-${W}`;B+=`
288
288
  • ${j}`});throw B+=`
289
289
 
290
290
  Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new wA(B)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,Y=[...w.options,...this.options];for(let A of Y){let X=$[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 wA(`Option \`${A.rawName}\` requires a value.
291
291
 
292
- Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class qJ extends NJ{constructor($){super("@@global@@","",{},$)}}var EK=NJ,jw={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 UY={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function TK(){return!0}function HK(){let $={};$.supportsColor=TK();function w(A,X=[]){let J=A===""?[]:[...X,A],U=function(W){if(!$.supportsColor)return W;let j="",z="";for(let G of J)if(G in UY&&UY[G]in jw){let K=UY[G];j+=jw[K][0],z=jw[K][1]+z}else if(G in jw)j+=jw[G][0],z=jw[G][1]+z;return j+W+z},B=[...Object.keys(jw),...Object.keys(UY)];for(let W of B)if(!(W in U))Object.defineProperty(U,W,{get(){return w(W,J)}});return U}let Y=[...Object.keys(jw),...Object.keys(UY)];for(let A of Y)if(!(A in $))Object.defineProperty($,A,{get(){return w(A)}});return $}var WY=HK();class EJ extends XK{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new qJ(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(Y)=>{if(console.log(`
292
+ Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class qJ extends NJ{constructor($){super("@@global@@","",{},$)}}var TK=NJ,jw={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 UY={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function HK(){return!0}function fK(){let $={};$.supportsColor=HK();function w(A,X=[]){let J=A===""?[]:[...X,A],U=function(W){if(!$.supportsColor)return W;let j="",z="";for(let G of J)if(G in UY&&UY[G]in jw){let K=UY[G];j+=jw[K][0],z=jw[K][1]+z}else if(G in jw)j+=jw[G][0],z=jw[G][1]+z;return j+W+z},B=[...Object.keys(jw),...Object.keys(UY)];for(let W of B)if(!(W in U))Object.defineProperty(U,W,{get(){return w(W,J)}});return U}let Y=[...Object.keys(jw),...Object.keys(UY)];for(let A of Y)if(!(A in $))Object.defineProperty($,A,{get(){return w(A)}});return $}var WY=fK();class EJ extends JK{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new qJ(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(Y)=>{if(console.log(`
293
293
 
294
- Received ${Y}, cleaning up...`),$)try{await $()}catch(A){console.error("Error during cleanup:",A)}Bw.exit(0)};return Bw.on("SIGINT",()=>w("SIGINT")),Bw.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,Y){if(!Y)Y={};let A=new EK($,w||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option($,w,Y){return this.globalCommand.option($,w,Y),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,w="-v, --version"){return this.globalCommand.version($,w),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:w},Y,A){if(this.args=$,this.options=w,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(WY.red(`
294
+ Received ${Y}, cleaning up...`),$)try{await $()}catch(A){console.error("Error during cleanup:",A)}Bw.exit(0)};return Bw.on("SIGINT",()=>w("SIGINT")),Bw.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,Y){if(!Y)Y={};let A=new TK($,w||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option($,w,Y){return this.globalCommand.option($,w,Y),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,w="-v, --version"){return this.globalCommand.version($,w),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:w},Y,A){if(this.args=$,this.options=w,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(WY.red(`
295
295
  ✗ Command "${$}" not found.
296
- `)),this.enableDidYouMean){let w=[];for(let A of this.commands){if(A.displayName)w.push(A.displayName);if(A.aliasNames)w.push(...A.aliasNames)}let Y=Ij($,w);if(Y.length>0)console.log(WY.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${WY.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(WY.dim("Run"),`${this.name} --help`,WY.dim("to see all available commands")),Bw.exit(1)}async parse($=qj,w={}){let{run:Y=!0,exitOnError:A=!1}=w;if(A)try{return await this.parse($,{run:Y})}catch(W){throw this.handleUsageError(W),W}if(this.rawArgs=$,!this.name)this.name=$[1]?GK($[1]):"cli";let X=!0,J=$.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let W of this.commands)if(W.isMatched(U)){let j=this.mri(J,W);X=!1;let z={...j,args:j.args.slice(1)};this.setParsedInfo(z,W,U),this.emit(`command:${U}`,W);break}}if(X){for(let W of this.commands)if(W.name===""){X=!1;let j=this.mri(J,W);this.setParsedInfo(j,W),this.emit("command:!",W);break}}if(X){let W=this.mri($.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 B={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 B}mri($,w){let Y=[...this.globalCommand.options,...w?w.options:[]],A=WK(Y),X=[],J=$.indexOf("--");if(J>-1)X=$.slice(J+1),$=$.slice(0,J);let U=JK($,A),B={_:U._};for(let K of Object.keys(U))if(K!=="_")B[Mj(K)]=U[K];let W=B._,j={"--":X},z=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,G=Object.create(null);for(let K of Y){if(!z&&K.config.default!==void 0)for(let F of K.names)j[F]=K.config.default;if(Array.isArray(K.config.type)){if(G[K.name]===void 0)G[K.name]={shouldTransform:!0,transformFunction:K.config.type[0]}}}for(let K of Object.keys(B))if(K!=="_"){let F=K.split(".");jK(j,F,B[K]),zK(j,G)}return{args:W,options:j}}async run($=qj){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let A=$,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
296
+ `)),this.enableDidYouMean){let w=[];for(let A of this.commands){if(A.displayName)w.push(A.displayName);if(A.aliasNames)w.push(...A.aliasNames)}let Y=Vj($,w);if(Y.length>0)console.log(WY.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${WY.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(WY.dim("Run"),`${this.name} --help`,WY.dim("to see all available commands")),Bw.exit(1)}async parse($=Ej,w={}){let{run:Y=!0,exitOnError:A=!1}=w;if(A)try{return await this.parse($,{run:Y})}catch(W){throw this.handleUsageError(W),W}if(this.rawArgs=$,!this.name)this.name=$[1]?KK($[1]):"cli";let X=!0,J=$.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let W of this.commands)if(W.isMatched(U)){let j=this.mri(J,W);X=!1;let z={...j,args:j.args.slice(1)};this.setParsedInfo(z,W,U),this.emit(`command:${U}`,W);break}}if(X){for(let W of this.commands)if(W.name===""){X=!1;let j=this.mri(J,W);this.setParsedInfo(j,W),this.emit("command:!",W);break}}if(X){let W=this.mri($.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 B={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 B}mri($,w){let Y=[...this.globalCommand.options,...w?w.options:[]],A=BK(Y),X=[],J=$.indexOf("--");if(J>-1)X=$.slice(J+1),$=$.slice(0,J);let U=UK($,A),B={_:U._};for(let K of Object.keys(U))if(K!=="_")B[Ij(K)]=U[K];let W=B._,j={"--":X},z=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,G=Object.create(null);for(let K of Y){if(!z&&K.config.default!==void 0)for(let F of K.names)j[F]=K.config.default;if(Array.isArray(K.config.type)){if(G[K.name]===void 0)G[K.name]={shouldTransform:!0,transformFunction:K.config.type[0]}}}for(let K of Object.keys(B))if(K!=="_"){let F=K.split(".");zK(j,F,B[K]),GK(j,G)}return{args:W,options:j}}async run($=Ej){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let A=$,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
297
297
  Run \`${this.name??"cli"} --help\` for usage.`;Bw.stderr.write(`${J}${X}${U}
298
- `),Bw.exit(A.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((B,W)=>{if(B.variadic)A.push($.slice(W));else A.push($[W])}),A.push(w);let X={command:Y,args:A,options:w};for(let B of Y.beforeHooks)await B(X);let J,U=async()=>{let B=Y.commandAction.apply(this,A);if(B instanceof Promise)J=await B;else J=B;return J};if(Y.middleware.length>0){let B=0,W=async()=>{if(B<Y.middleware.length){let j=Y.middleware[B++];await j({...X,next:W})}else await U()};await W()}else await U();for(let B of Y.afterHooks)await B(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return Bw.removeAllListeners("SIGINT"),Bw.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 Cj{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let w=this.cache.get($);if(!w){this.misses++;return}if(Date.now()-w.timestamp>w.ttl){this.cache.delete($),this.misses++;return}return this.hits++,w.value}set($,w,Y=5000){if(!this.enabled)return;this.cache.set($,{value:w,timestamp:Date.now(),ttl:Y})}has($){if(!this.enabled)return!1;let w=this.cache.get($);if(!w)return!1;if(Date.now()-w.timestamp>w.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[w,Y]of this.cache.entries())if($-Y.timestamp>Y.ttl)this.cache.delete(w)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var O4=new Cj;function fK(){if("FORCE_COLOR"in BY.env)return BY.env.FORCE_COLOR!=="0";if("NO_COLOR"in BY.env||BY.env.TERM==="dumb")return!1;if(BY.platform==="win32")return!0;return Ej.isatty(1)&&Ej.isatty(2)}var Qj=fK();function A0($,w){if(!Qj)return(Y)=>Y;return(Y)=>$+Y+w}var RK=A0("\x1B[0m","\x1B[0m"),MK=A0("\x1B[31m","\x1B[39m"),IK=A0("\x1B[32m","\x1B[39m"),VK=A0("\x1B[33m","\x1B[39m"),CK=A0("\x1B[34m","\x1B[39m"),QK=A0("\x1B[35m","\x1B[39m"),yK=A0("\x1B[36m","\x1B[39m"),LK=A0("\x1B[37m","\x1B[39m"),OK=A0("\x1B[90m","\x1B[39m"),_K=A0("\x1B[1m","\x1B[22m"),SK=A0("\x1B[3m","\x1B[23m"),ZK=A0("\x1B[4m","\x1B[24m"),hK=A0("\x1B[2m","\x1B[22m"),kK=A0("\x1B[7m","\x1B[27m"),DK=A0("\x1B[8m","\x1B[28m"),xK=A0("\x1B[9m","\x1B[29m"),PK=A0("\x1B[41m","\x1B[49m"),bK=A0("\x1B[42m","\x1B[49m"),uK=A0("\x1B[43m","\x1B[49m"),vK=A0("\x1B[44m","\x1B[49m"),cK=A0("\x1B[45m","\x1B[49m"),iK=A0("\x1B[46m","\x1B[49m"),mK=A0("\x1B[47m","\x1B[49m"),gK=Qj,dK={reset:RK,red:MK,green:IK,yellow:VK,blue:CK,magenta:QK,cyan:yK,white:LK,gray:OK,bold:_K,italic:SK,underline:ZK,dim:hK,inverse:kK,hidden:DK,strikethrough:xK,bgRed:PK,bgGreen:bK,bgYellow:uK,bgBlue:vK,bgMagenta:cK,bgCyan:iK,bgWhite:mK,isColorSupported:gK},AA=dK,nK=["up","down","left","right","space","enter","cancel"],XA={actions:new Set(nK),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function yj($,w){if(typeof $==="string")return XA.aliases.get($)===w;for(let Y of $){if(Y===void 0)continue;if(yj(Y,w))return!0}return!1}function pK($,w){if($===w)return[];let Y=$.split(`
298
+ `),Bw.exit(A.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((B,W)=>{if(B.variadic)A.push($.slice(W));else A.push($[W])}),A.push(w);let X={command:Y,args:A,options:w};for(let B of Y.beforeHooks)await B(X);let J,U=async()=>{let B=Y.commandAction.apply(this,A);if(B instanceof Promise)J=await B;else J=B;return J};if(Y.middleware.length>0){let B=0,W=async()=>{if(B<Y.middleware.length){let j=Y.middleware[B++];await j({...X,next:W})}else await U()};await W()}else await U();for(let B of Y.afterHooks)await B(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return Bw.removeAllListeners("SIGINT"),Bw.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 Qj{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let w=this.cache.get($);if(!w){this.misses++;return}if(Date.now()-w.timestamp>w.ttl){this.cache.delete($),this.misses++;return}return this.hits++,w.value}set($,w,Y=5000){if(!this.enabled)return;this.cache.set($,{value:w,timestamp:Date.now(),ttl:Y})}has($){if(!this.enabled)return!1;let w=this.cache.get($);if(!w)return!1;if(Date.now()-w.timestamp>w.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[w,Y]of this.cache.entries())if($-Y.timestamp>Y.ttl)this.cache.delete(w)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var S4=new Qj;function RK(){if("FORCE_COLOR"in BY.env)return BY.env.FORCE_COLOR!=="0";if("NO_COLOR"in BY.env||BY.env.TERM==="dumb")return!1;if(BY.platform==="win32")return!0;return Tj.isatty(1)&&Tj.isatty(2)}var yj=RK();function A0($,w){if(!yj)return(Y)=>Y;return(Y)=>$+Y+w}var MK=A0("\x1B[0m","\x1B[0m"),IK=A0("\x1B[31m","\x1B[39m"),VK=A0("\x1B[32m","\x1B[39m"),CK=A0("\x1B[33m","\x1B[39m"),QK=A0("\x1B[34m","\x1B[39m"),yK=A0("\x1B[35m","\x1B[39m"),LK=A0("\x1B[36m","\x1B[39m"),OK=A0("\x1B[37m","\x1B[39m"),_K=A0("\x1B[90m","\x1B[39m"),SK=A0("\x1B[1m","\x1B[22m"),ZK=A0("\x1B[3m","\x1B[23m"),hK=A0("\x1B[4m","\x1B[24m"),DK=A0("\x1B[2m","\x1B[22m"),kK=A0("\x1B[7m","\x1B[27m"),xK=A0("\x1B[8m","\x1B[28m"),PK=A0("\x1B[9m","\x1B[29m"),bK=A0("\x1B[41m","\x1B[49m"),uK=A0("\x1B[42m","\x1B[49m"),vK=A0("\x1B[43m","\x1B[49m"),cK=A0("\x1B[44m","\x1B[49m"),iK=A0("\x1B[45m","\x1B[49m"),mK=A0("\x1B[46m","\x1B[49m"),gK=A0("\x1B[47m","\x1B[49m"),dK=yj,lK={reset:MK,red:IK,green:VK,yellow:CK,blue:QK,magenta:yK,cyan:LK,white:OK,gray:_K,bold:SK,italic:ZK,underline:hK,dim:DK,inverse:kK,hidden:xK,strikethrough:PK,bgRed:bK,bgGreen:uK,bgYellow:vK,bgBlue:cK,bgMagenta:iK,bgCyan:mK,bgWhite:gK,isColorSupported:dK},AA=lK,pK=["up","down","left","right","space","enter","cancel"],XA={actions:new Set(pK),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function Lj($,w){if(typeof $==="string")return XA.aliases.get($)===w;for(let Y of $){if(Y===void 0)continue;if(Lj(Y,w))return!0}return!1}function rK($,w){if($===w)return[];let Y=$.split(`
299
299
  `),A=w.split(`
300
- `),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var D4=lK.platform.startsWith("win"),Tj=Symbol("clapp:cancel");function $A($,w){let Y=$;if(Y.isTTY)Y.setRawMode(w)}function sK($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function oK($){return sK($).length}function fj($,w,Y){if(!w||w<1)return $;let A=Y?.hard??!1,X=Y?.trim??!0,J=$.split(`
301
- `),U=[];for(let B of J){if(oK(B)<=w){U.push(X?B.trimEnd():B);continue}if(A){let W="",j=0,z=0;while(z<B.length){let G=B.slice(z).match(/^\x1b\[[0-9;]*m/);if(G){W+=G[0],z+=G[0].length;continue}if(j>=w)U.push(X?W.trimEnd():W),W="",j=0;W+=B[z],j++,z++}if(W)U.push(X?W.trimEnd():W)}else U.push(X?B.trimEnd():B)}return U.join(`
302
- `)}class TJ{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=rK,output:A=tK,render:X,signal:J,...U}=$;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=w,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber($,w){let Y=this._subscribers.get($)??[];Y.push(w),this._subscribers.set($,Y)}on($,w){return this.setSubscriber($,{cb:w}),this}once($,w){return this.setSubscriber($,{cb:w,once:!0}),this}emit($,...w){let Y=this._subscribers.get($)??[],A=[];for(let X of Y)if(X.cb(...w),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(Tj);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=aK.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),$A(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(D$.show),this.output.off("resize",this.render),$A(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(D$.show),this.output.off("resize",this.render),$A(this.input,!1),$(Tj)})})}_isActionKey($,w){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,w){if(this.userInput=$??"",this.emit("userInput",this.userInput),w&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,w){if(this._track&&w.name!=="return"){if(w.name&&this._isActionKey($,w))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=w.name==="tab"||w.name==="escape"||w.name==="backspace"||w.name==="delete"||w.name==="enter"||w.name==="return"||w.name&&["up","down","left","right"].includes(w.name);if($&&!Y&&$.length===1&&$>=" ")this._manualLine+=$;else if(w.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let A=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(A)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&XA.aliases.has(w.name))this.emit("cursor",XA.aliases.get(w.name));if(XA.actions.has(w.name))this.emit("cursor",w.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),w),w?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(yj([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
303
- `),$A(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 $=fj(this._prevFrame,Hj.stdout.columns,{hard:!0,trim:!1}).split(`
304
- `).length-1;this.output.write(D$.move(-999,$*-1))}render(){let $=fj(this._render(this)??"",Hj.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(D$.hide);else{let w=pK(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let Y=w[0];this.output.write(D$.move(0,Y)),this.output.write(GJ.lines(1));let A=$.split(`
305
- `);this.output.write(A[Y]),this._prevFrame=$,this.output.write(D$.move(0,A.length-Y-1));return}if(w&&w?.length>1){let Y=w[0];this.output.write(D$.move(0,Y)),this.output.write(GJ.down());let X=$.split(`
300
+ `),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var P4=nK.platform.startsWith("win"),Hj=Symbol("clapp:cancel");function $A($,w){let Y=$;if(Y.isTTY)Y.setRawMode(w)}function oK($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function eK($){return oK($).length}function Rj($,w,Y){if(!w||w<1)return $;let A=Y?.hard??!1,X=Y?.trim??!0,J=$.split(`
301
+ `),U=[];for(let B of J){if(eK(B)<=w){U.push(X?B.trimEnd():B);continue}if(A){let W="",j=0,z=0;while(z<B.length){let G=B.slice(z).match(/^\x1b\[[0-9;]*m/);if(G){W+=G[0],z+=G[0].length;continue}if(j>=w)U.push(X?W.trimEnd():W),W="",j=0;W+=B[z],j++,z++}if(W)U.push(X?W.trimEnd():W)}else U.push(X?B.trimEnd():B)}return U.join(`
302
+ `)}class TJ{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=tK,output:A=aK,render:X,signal:J,...U}=$;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=w,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber($,w){let Y=this._subscribers.get($)??[];Y.push(w),this._subscribers.set($,Y)}on($,w){return this.setSubscriber($,{cb:w}),this}once($,w){return this.setSubscriber($,{cb:w,once:!0}),this}emit($,...w){let Y=this._subscribers.get($)??[],A=[];for(let X of Y)if(X.cb(...w),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(Hj);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=sK.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),$A(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(k$.show),this.output.off("resize",this.render),$A(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(k$.show),this.output.off("resize",this.render),$A(this.input,!1),$(Hj)})})}_isActionKey($,w){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,w){if(this.userInput=$??"",this.emit("userInput",this.userInput),w&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,w){if(this._track&&w.name!=="return"){if(w.name&&this._isActionKey($,w))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=w.name==="tab"||w.name==="escape"||w.name==="backspace"||w.name==="delete"||w.name==="enter"||w.name==="return"||w.name&&["up","down","left","right"].includes(w.name);if($&&!Y&&$.length===1&&$>=" ")this._manualLine+=$;else if(w.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let A=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(A)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&XA.aliases.has(w.name))this.emit("cursor",XA.aliases.get(w.name));if(XA.actions.has(w.name))this.emit("cursor",w.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),w),w?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(Lj([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
303
+ `),$A(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 $=Rj(this._prevFrame,fj.stdout.columns,{hard:!0,trim:!1}).split(`
304
+ `).length-1;this.output.write(k$.move(-999,$*-1))}render(){let $=Rj(this._render(this)??"",fj.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(k$.hide);else{let w=rK(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let Y=w[0];this.output.write(k$.move(0,Y)),this.output.write(GJ.lines(1));let A=$.split(`
305
+ `);this.output.write(A[Y]),this._prevFrame=$,this.output.write(k$.move(0,A.length-Y-1));return}if(w&&w?.length>1){let Y=w[0];this.output.write(k$.move(0,Y)),this.output.write(GJ.down());let X=$.split(`
306
306
  `).slice(Y);this.output.write(X.join(`
307
- `)),this._prevFrame=$;return}this.output.write(GJ.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function eK($,w){if($===void 0)return 0;if(w.length===0)return 0;let A=w.findIndex((X)=>X.value===$);return A!==-1?A:0}function $7($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function w7($,w){if(!w)return;if($)return w;return w[0]}class Y7 extends TJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#A;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return AA.inverse(AA.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...Y]=this.userInput.slice(this._cursor);return`${$}${AA.inverse(w)}${Y.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#A=$.filter??$7;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let A of Y){let X=w.findIndex((J)=>J.value===A);if(X!==-1)this.toggleSelected(A),this.#$=X}this.focusedValue=this.options[this.#$]?.value,this.on("key",(A,X)=>this.#X(A,X)),this.on("userInput",(A)=>this.#J(A))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#X($,w){let Y=w.name==="up",A=w.name==="down",X=w.name==="return";if(Y||A){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=w7(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#J($){if($!==this.#Y){this.#Y=$;let w=this.options;if($)this.filteredOptions=w.filter((Y)=>this.#A($,Y));else this.filteredOptions=[...w];if(this.#$=eK(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class A7 extends TJ{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return w.every((A)=>Y.includes(A.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),Y=this.getGroupItems(w);if(this.isGroupSelected(w))this.value=this.value.filter((A)=>Y.findIndex((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 w=this.value.includes($.value);this.value=w?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((X)=>({...X,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let A=this.options[this.cursor]?.group===!0;if(!this.#$&&A)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let A=this.options[this.cursor]?.group===!0;if(!this.#$&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var X7=KK();var e=($,w)=>X7?$:w,b4=e("◆","*"),u4=e("■","x"),v4=e("▲","x"),c4=e("◇","o"),i4=e("┌","T"),J7=e("│","|"),m4=e("└","—"),g4=e("●",">"),d4=e("○"," "),l4=e("◻","[•]"),n4=e("◼","[+]"),p4=e("◻","[ ]"),r4=e("▪","•"),t4=e("─","-"),a4=e("╮","+"),s4=e("├","+"),o4=e("╯","+"),e4=e("●","•"),$I=e("◆","*"),wI=e("▲","!"),YI=e("■","x");var AI={light:e("─","-"),heavy:e("━","="),block:e("█","#")};function U7(){return`${AA.gray(J7)} `}var XI=U7();WU();import{homedir as BU}from"node:os";import{join as jU,resolve as qN}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",t9={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:jU(BU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:jU(BU(),".stacks","ssl","stacks.localhost.crt"),keyPath:jU(BU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},zU=null;async function a9(){if(!zU)zU=await UU({name:"rpx",cwd:qN(__dirname,".."),defaultConfig:t9});return zU}var W1=t9;import{existsSync as EN,readdirSync as TN,readFileSync as HN,statSync as fN}from"node:fs";import{homedir as o9}from"node:os";import{isAbsolute as RN,join as j1}from"node:path";var e9=["~/Code"],$z=["localhost","test"],MN=1800000,GU={dirExists:($)=>{try{return fN($).isDirectory()}catch{return!1}},fileExists:($)=>{try{return EN($)}catch{return!1}},readText:($)=>{try{return HN($,"utf8")}catch{return null}}};function KU($,w){if($==="~")return w;if($.startsWith("~/"))return j1(w,$.slice(2));return $}function IN($){let w=$.indexOf(":");return(w===-1?$:$.slice(0,w)).toLowerCase()}function dA($){return $.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function VN($,w){for(let Y of w){let A=`.${Y}`;if($.endsWith(A)){let X=$.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 CN($,w){let Y=w.readText(j1($,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=w.readText(j1($,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function QN($){let w=$.selfRegisters??!1;return{command:$.command,env:$.env,urlEnv:$.urlEnv,selfRegisters:w,routes:$.routes??(w?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function yN($,w){let Y=CN($,w);if(Y?.command)return QN(Y);let A=w.fileExists(j1($,"buddy")),X=w.readText(j1($,"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 LN($,w={}){let Y={dirExists:w.dirExists??GU.dirExists,fileExists:w.fileExists??GU.fileExists,readText:w.readText??GU.readText},A=w.detect??yN,X=w.homeDir??o9(),J=$.tlds??$z,U=($.roots??e9).map((K)=>KU(K,X)),B=$.idleTimeoutMs??MN,W=new Map;for(let K of $.sites??[])W.set(K.to,K);let j=(K)=>K.idleTimeoutMs??B;function z(K){let F=gA(W,K);if(!F)return null;let T=RN(F.dir)?F.dir:KU(F.dir,X),q=F.selfRegisters??!1,E=F.routes??[];if(!q&&E.length===0)E=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let f=s9({...F.env??{}},void 0,K);return{host:K,id:dA(K),dir:T,command:F.command,env:f,routes:E,selfRegisters:q,idleTimeoutMs:j(F),source:"config"}}function G(K){let F=VN(K,J);if(!F)return null;for(let T of U){let q=j1(T,F);if(!Y.dirExists(q))continue;let E=A(q,Y);if(!E)continue;let f=E.selfRegisters??!1;return{host:K,id:dA(K),dir:q,command:E.command,env:s9({...E.env??{}},E.urlEnv,K),routes:f?[]:E.routes??[],selfRegisters:f,idleTimeoutMs:B,source:"discovered"}}return null}return{resolve(K){let F=IN(K);if(!F)return null;return z(F)??G(F)}}}function ON($){try{return TN($,{withFileTypes:!0}).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}function wz($,w={}){let Y=w.homeDir??o9(),A=$.tlds??$z,X=($.roots??e9).map((G)=>KU(G,Y)),J=w.readdir??ON,U=LN($,w),B=[],W=new Set,j=(G)=>{if(G&&!W.has(G.host))W.add(G.host),B.push(G)};for(let G of $.sites??[])if(!G.to.includes("*"))j(U.resolve(G.to));let z=A[0]??"localhost";for(let G of X)for(let K of J(G))j(U.resolve(`${K}.${z}`));return B}function s9($,w,Y){if(!w)return $;let A=`https://${Y}`;for(let X of w)if($[X]===void 0)$[X]=A;return $}i$();V8();L8();O8();vY();S8();QB();OB();DB();bY();DY();e1();wY();X0();import{spawn as M6}from"node:child_process";import*as b0 from"node:fs/promises";import{homedir as I6}from"node:os";import*as O$ from"node:path";import*as C from"node:process";var bM=5000;function w$(){return O$.join(I6(),".stacks","rpx")}function yw($=w$()){return O$.join($,"daemon.pid")}async function Qw($=w$()){try{let w=await b0.readFile(yw($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function d8($=w$()){let w=await Qw($);return w!==null&&r0(w)}async function V6($=w$()){await b0.mkdir($,{recursive:!0});let w=yw($);while(!0){try{let A=await b0.open(w,"wx");try{await A.write(`${C.pid}
308
- `)}finally{await A.close()}return w}catch(A){if(A.code!=="EEXIST")throw A}let Y=await Qw($);if(Y!==null&&r0(Y))throw Error(`rpx daemon already running (pid=${Y})`);await b0.unlink(w).catch(()=>{})}}async function AY($=w$()){await b0.unlink(yw($)).catch(()=>{})}var m8=new Map;function g8($){for(let[w,Y]of m8)if(!$.has(w))d1(Y),m8.delete(w)}function C6($){let w=$.cleanUrls??!1,Y=Q$($.path),A=l1($.auth);if($.static)return{static:PY($.static,w),cleanUrls:w,basePath:Y,auth:A};let X=$.from??"localhost:1",J=Rw(X),U=new URL(J.startsWith("http")?J:`http://${J}`),B=m8.get($.id);if(!B)B=m1(X,$.loadBalancer),g1(B),m8.set($.id,B);return{sourceHost:U.host,upstreamPool:B,cleanUrls:w,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites,basePath:Y,auth:A}}function uM($){return $.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??$[0]??"rpx.localhost"}async function i8($,w,Y=[],A=!1){let X=await y$(w,$.verbose),J=[...new Set([...X.map((z)=>z.to).filter(Boolean),...Y])],U=uM(J),B=[...new Set([U,...J,"rpx.localhost"])],W=RB(J,U,$.verbose);if(typeof $.https==="object"&&typeof W.https==="object")W.https={...W.https,...$.https};let j=await Yw(W);if(j&&(A||!uX(M8,B)))N("daemon",`regenerating shared cert for host(s): ${B.join(", ")}`,$.verbose),I8(),j=null;if(!j)N("daemon","no usable cert on disk, generating one via tlsx",$.verbose),await i1({...W,forceRegenerate:!0}),j=await Yw(W);if(!j)throw Error("failed to bootstrap TLS for rpx daemon");return j}async function vM($,w,Y,A){let X=C.env.SUDO_PASSWORD,J=C.env.HOME??I6(),U=[C.execPath,...C.argv.slice(1)],B=[`HOME=${J}`,`PATH=${C.env.PATH??""}`];if(A)B.push("RPX_VERBOSE=1");for(let[T,q]of Object.entries(C.env))if(q!==void 0&&T!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(T))B.push(`${T}=${q}`);let W=X?["-S","-p","","env",...B,...U]:["-n","env",...B,...U];N("daemon",`elevating daemon via sudo for privileged ports ${w}/${Y}`,A);let j=M6("sudo",W,{detached:!0,stdio:["pipe","ignore","ignore"]}),z=null,G=null;if(j.once("error",(T)=>{z=T}),j.once("exit",(T)=>{G=T??0}),X&&j.stdin)j.stdin.write(`${X}
309
- `),j.stdin.end();j.unref();let K=yw($),F=Date.now()+15000;while(Date.now()<F){if(z)throw z;let T=await Qw($);if(T!==null&&r0(T)){if(A)R.success(`rpx daemon elevated to root (pid=${T}, https on :${w})`);return{httpsPort:w,httpPort:Y,pidPath:K,done:Promise.resolve(),stop:async()=>{try{C.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(G!==null&&G!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${G}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((q)=>setTimeout(q,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}var H6=!1;function rB(){if(H6)return;H6=!0,C.on("uncaughtException",($)=>{R.error(`rpx daemon: uncaught exception (continuing): ${$?.stack??$}`)}),C.on("unhandledRejection",($)=>{R.error(`rpx daemon: unhandled rejection (continuing): ${$}`)})}function Q6($,w,Y){let A;try{A=new URL($.url)}catch{return new Response("Bad Request",{status:400})}let X=($.headers.get("host")??A.hostname).split(":")[0];if(A.pathname.startsWith("/.well-known/acme-challenge/")){if(w){let J=w.challengeStore.handlePath(A.pathname);if(J!==void 0)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(Y){let J=uY(Y,A.pathname);if(J!=null)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(w)return new Response("challenge not found",{status:404})}if(w&&!w.hasCert(X))w.ensureCert(X).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${X}${A.pathname}${A.search}`}})}async function y6($={}){rB();let w=$.verbose??!1,Y=$.rpxDir??w$(),A=$.registryDir??O$.join(Y,"registry.d"),X=$.httpsPort??443,J=$.httpPort??80,U=$.hostname??"0.0.0.0",B=$.gcIntervalMs??bM;if(C.env.RPX_DAEMON_WORKER==="1")return mM({rpxDir:C.env.RPX_WORKER_RPXDIR??Y,registryDir:C.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(C.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:C.env.RPX_WORKER_HOSTNAME??U,verbose:C.env.RPX_WORKER_VERBOSE==="1"||w});let W=X>0&&X<1024||J>0&&J<1024,j=typeof C.getuid==="function"&&C.getuid()===0;if(C.platform!=="win32"&&W&&!j)return vM(Y,X,J,w);let z=Math.max(1,$.workers??(Number.parseInt(C.env.RPX_WORKERS??"",10)||1));if(z>1){if($.onDemandSites?.enabled)R.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return gM($,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:w,gcIntervalMs:B,workers:z})}let G=await V6(Y),K=new Map,F=(y,S)=>t1(K,y,S);function T(y){K=r1(y.map((V$)=>({host:V$.to,path:V$.path,route:C6(V$)}))),g8(new Set(y.map((V$)=>V$.id)));let S=Array.from(K.keys());N("daemon",`routing table now covers ${S.length} host(s): ${S.join(", ")||"<empty>"}`,w)}await o1(A,w).catch((y)=>{N("daemon",`initial gc failed: ${y}`,w)});let q=await y$(A,w);T(q),await Jw({rpxDir:Y,verbose:w}).catch((y)=>{N("daemon",`DNS reconcile on start failed: ${y}`,w)}),await iw(q,{rpxDir:Y,verbose:w,ownerPid:C.pid}).catch((y)=>{N("daemon",`DNS setup on start failed: ${y}`,w)});let E=[];if($.productionCerts){if(E=await a1($.productionCerts,w),w&&E.length>0)R.info(`SNI: serving ${E.length} real cert(s): ${E.map((y)=>y.serverName).join(", ")}`)}let f=new Set,M=null,Q;if($.onDemandSites?.enabled){if(M=new P8({resolver:LB($.onDemandSites),registryDir:A,rpxDir:Y,verbose:w,startupTimeoutMs:$.onDemandSites.startupTimeoutMs,isHostRoutable:(y)=>_8(K,y)!==void 0,onSiteActivating:(y)=>{_w(y)}}),Q=async(y)=>{let S=await M.onRequest(y);switch(S.kind){case"ready":return{retry:!0};case"starting":return xB({host:S.host,sinceMs:S.sinceMs,logTail:S.logTail});case"failed":return PB({host:S.host,error:S.error,logTail:S.logTail});case"unknown":default:return}},w)R.info("rpx: on-demand sites enabled")}let V=n1(F,w,Q),H=p1(w),I=null;if(E.length===0)I=await i8($,A);let O=$.onDemandTls,Z=O?.enabled?new iY({config:O,certsDir:O.certsDir??$.productionCerts?.certsDir??O$.join(Y,"on-demand-certs"),initial:E,verbose:w,onCertAdded:(y)=>{lw(y)}}):null;function P0(y){if(y.length>0)return y.map((S)=>({serverName:S.serverName,cert:S.cert,key:S.key}));return{key:I.key,cert:I.cert,ca:I.ca,requestCert:!1,rejectUnauthorized:!1}}function Z$(y){return Bun.serve({port:X,hostname:U,reusePort:P1(),tls:P0(y),fetch(S,V$){return V(S,V$)},websocket:H,error(S){return N("daemon",`https server error: ${S}`,w),new Response(`Server Error: ${S.message}`,{status:500})}})}let h$=(y)=>[...new Set(y.map((S)=>S.to).filter(Boolean))],dw=(y)=>{if(!I)return E;return fB([...h$(y),...f,"rpx.localhost"],I)},Ww=Z$(Z?Z.sniEntries():E.length>0?E:dw(q)),Lw=null,Ow=!1;async function lw(y){if(I$)return;if(Lw=y,Ow)return;Ow=!0;try{while(!I$&&Lw){let S=Lw;Lw=null,N("daemon",`rebuilding :443 with ${S.length} SNI cert(s)`,w),Ww.stop(!1);let V$,UJ=!1,zj=60,a6=500;for(let WJ=0;!I$&&!UJ;WJ++)try{Ww=Z$(S),UJ=!0;break}catch(s6){if(V$=s6,WJ>=zj)break;await new Promise((o6)=>setTimeout(o6,Math.min(25*2**Math.min(WJ,4),a6)))}if(!UJ)R.error(`rpx: CRITICAL — could not rebind :443 after ${zj} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${V$?.message}`)}}finally{Ow=!1}}let k$=null;if(J>0)k$=Bun.serve({port:J,hostname:U,fetch(y){return Q6(y,Z,$.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(w)R.success(`rpx daemon listening on https://${U}:${X}${k$?` (http→https on :${J})`:""}`),R.info(`pid file: ${G}`),R.info(`registry: ${A}`);async function h(y){if(I$||E.length>0||Z||!I)return;try{I=await i8($,A,[...f]),await lw(dw(y))}catch(S){N("daemon",`TLS sync on registry change failed: ${S}`,w)}}async function _w(y){if(I$||E.length>0||Z||!I||!y)return;if(f.has(y))return;f.add(y);try{I=await i8($,A,[...f],!0);let S=await y$(A,w);await lw(dw(S))}catch(S){N("daemon",`dev cert refresh for ${y} failed: ${S}`,w)}}let XJ=dY((y)=>{T(y),h(y),iw(y,{rpxDir:Y,verbose:w,ownerPid:C.pid}).catch((S)=>{N("daemon",`DNS sync on registry change failed: ${S}`,w)})},{dir:A,verbose:w}),nw=setInterval(()=>{o1(A,w).then((y)=>{if(y>0)N("daemon",`gc reaped ${y} stale entries`,w)}).catch((y)=>{N("daemon",`periodic gc failed: ${y}`,w)})},B);if(typeof nw.unref==="function")nw.unref();let I$=!1,JY,pw=new Promise((y)=>{JY=y});async function JJ(){if(I$)return pw;if(I$=!0,clearInterval(nw),XJ.close(),await M?.stopAll().catch((y)=>{N("daemon",`site supervisor stopAll failed: ${y}`,w)}),Ww.stop(!1),k$?.stop(!1),await Vw({rpxDir:Y,verbose:w}).catch((y)=>{N("daemon",`DNS teardown failed: ${y}`,w)}),g8(new Set),await AY(Y),w)R.info("rpx daemon stopped");return JY(),pw}let jj=(y)=>{N("daemon",`received ${y}, shutting down`,w),JJ().catch(()=>{})};return C.once("SIGINT",jj),C.once("SIGTERM",jj),{stop:JJ,done:pw,httpsPort:typeof Ww.port==="number"?Ww.port:X,httpPort:k$&&typeof k$.port==="number"?k$.port:J,pidPath:G,ensureCert:(y)=>Z?Z.ensureCert(y):Promise.resolve(!1),listSites:()=>M?.list()??[]}}function tB($){return O$.join($,"cluster-sni.json")}async function f6($,w,Y){let A=tB($),X=`${A}.${C.pid}.tmp`;await b0.writeFile(X,JSON.stringify({sni:w,dev:Y}),"utf8"),await b0.rename(X,A)}async function R6($){try{return JSON.parse(await b0.readFile(tB($),"utf8"))}catch{return{sni:[],dev:null}}}function cM($){if($.sni.length>0)return $.sni.map((w)=>({serverName:w.serverName,cert:w.cert,key:w.key}));if($.dev)return{key:$.dev.key,cert:$.dev.cert,ca:$.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function iM(){let $=C.execPath,w=C.env.RPX_WORKER_BIN;if(w)return[$,w,"daemon:start"];let Y=O$.basename($).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&C.argv[1])return[$,C.argv[1],"daemon:start"];return[$,"daemon:start"]}async function mM($){rB();let{rpxDir:w,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=$,U=new Map,B=(H,I)=>t1(U,H,I),W=(H)=>{U=r1(H.map((I)=>({host:I.to,path:I.path,route:C6(I)}))),g8(new Set(H.map((I)=>I.id)))};W(await y$(Y,J));let j=n1(B,J),z=p1(J),G=!1,K=(H)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:cM(H),fetch(I,O){return j(I,O)},websocket:z,error(I){return N("daemon",`worker https error: ${I}`,J),new Response(`Server Error: ${I.message}`,{status:500})}}),F=K(await R6(w));async function T(){if(G)return;let H=await R6(w),I=null;for(let Z=0;Z<20&&!G;Z++)try{I=K(H);break}catch{await new Promise((P0)=>setTimeout(P0,25))}if(!I){N("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let O=F;F=I,O.stop(!1)}let q=dY((H)=>W(H),{dir:Y,verbose:J}),E=()=>{T().catch(()=>{})};C.on("SIGHUP",E);let f,M=new Promise((H)=>{f=H});async function Q(){if(G)return M;return G=!0,C.off("SIGHUP",E),q.close(),F.stop(!1),g8(new Set),f(),M}let V=()=>{Q().then(()=>C.exit(0)).catch(()=>C.exit(0))};if(C.once("SIGTERM",V),C.once("SIGINT",V),J)R.success(`rpx worker (pid ${C.pid}) serving :${A}`);return{stop:Q,done:M,httpsPort:typeof F.port==="number"?F.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function gM($,w){rB();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:B,gcIntervalMs:W,workers:j}=w,z=await V6(Y),G=[];if($.productionCerts)G=await a1($.productionCerts,B);let K=null;if(G.length===0)K=await i8($,A);let F=K?{key:K.key,cert:K.cert,ca:Array.isArray(K.ca)?K.ca.join(`
310
- `):K.ca}:null,T=!1,q=[];function E(h){for(let _w of q)try{_w.kill(h)}catch{}}async function f(h){await f6(Y,h,F),E("SIGHUP")}let M=$.onDemandTls,Q=M?.enabled?new iY({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??O$.join(Y,"on-demand-certs"),initial:G,verbose:B,onCertAdded:(h)=>{f(h)}}):null;await f6(Y,Q?Q.sniEntries():G,F);let V=await y$(A,B);await Jw({rpxDir:Y,verbose:B}).catch((h)=>{N("daemon",`DNS reconcile on start failed: ${h}`,B)}),await iw(V,{rpxDir:Y,verbose:B,ownerPid:C.pid}).catch((h)=>{N("daemon",`DNS setup on start failed: ${h}`,B)}),await o1(A,B).catch(()=>{});let H=dY((h)=>{iw(h,{rpxDir:Y,verbose:B,ownerPid:C.pid}).catch((_w)=>{N("daemon",`DNS sync on registry change failed: ${_w}`,B)})},{dir:A,verbose:B}),I=setInterval(()=>{o1(A,B).catch(()=>{})},W);I.unref?.();let O=null;if(J>0)O=Bun.serve({port:J,hostname:U,fetch(h){return Q6(h,Q,$.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let Z=10,P0=60000,Z$=30000,h$=0,dw=Date.now();function Ww(){if(T)return;let h={...C.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:B?"1":"0"},_w=Bun.spawn(iM(),{env:h,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(XJ,nw){if(T)return;let I$=q.indexOf(XJ);if(I$!==-1)q.splice(I$,1);let JY=Date.now();if(JY-dw>P0)dw=JY,h$=0;if(h$++,h$>Z){R.error(`rpx: worker keeps exiting (code ${nw}); giving up after ${Z} restarts in ${Math.round(P0/1000)}s`);return}let pw=Math.min(Z$,100*2**Math.min(h$,8));N("daemon",`worker exited (code ${nw}); respawning in ${pw}ms (restart ${h$}/${Z})`,B),setTimeout(Ww,pw).unref?.()}});q.push(_w)}for(let h=0;h<j;h++)Ww();if(B)R.success(`rpx coordinator listening on https://${U}:${X} via ${j} worker(s)${O?` (http→https on :${J})`:""}`),R.info(`pid file: ${z}`);let Lw,Ow=new Promise((h)=>{Lw=h});async function lw(){if(T)return Ow;if(T=!0,clearInterval(I),H.close(),O?.stop(!1),E("SIGTERM"),await Promise.race([Promise.all(q.map((h)=>h.exited)),new Promise((h)=>setTimeout(h,3000))]),E("SIGKILL"),await Vw({rpxDir:Y,verbose:B}).catch((h)=>{N("daemon",`DNS teardown failed: ${h}`,B)}),await AY(Y),await b0.unlink(tB(Y)).catch(()=>{}),B)R.info("rpx coordinator stopped");return Lw(),Ow}let k$=(h)=>{N("daemon",`coordinator received ${h}, shutting down`,B),lw().catch(()=>{})};return C.once("SIGINT",k$),C.once("SIGTERM",k$),{stop:lw,done:Ow,httpsPort:X,httpPort:J,pidPath:z,ensureCert:(h)=>Q?Q.ensureCert(h):Promise.resolve(!1),listSites:()=>[]}}function dM(){let $=C.execPath,w=O$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&C.argv[1])return[$,C.argv[1],"daemon:start"];return[$,"daemon:start"]}async function L6($={}){let w=$.rpxDir??w$(),Y=$.verbose??!1;await Jw({rpxDir:w,verbose:Y}).catch((z)=>{N("daemon",`DNS reconcile before ensureDaemonRunning: ${z}`,Y)});let A=await Qw(w);if(A!==null&&r0(A))return N("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)N("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await AY(w);await b0.mkdir(w,{recursive:!0});let X=$.spawnCommand??dM();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");N("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=M6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??C.cwd(),env:$.spawnEnv?{...C.env,...$.spawnEnv}:C.env});J.unref();let U=null;J.once("error",(z)=>{U=z});let B=$.startupTimeoutMs??5000,W=$.pollIntervalMs??50,j=Date.now()+B;while(Date.now()<j){if(U)throw U;let z=await Qw(w);if(z!==null&&r0(z))return N("daemon",`daemon registered with pid=${z}`,Y),{pid:z,spawned:!0};await new Promise((G)=>setTimeout(G,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${B}ms (rpxDir=${w})`)}async function O6($={}){let w=$.rpxDir??w$(),Y=$.verbose??!1,A=$.timeoutMs??5000,X=$.pollIntervalMs??50,J=$.forceAfterTimeout??!0,U=await Qw(w);if(U===null||!r0(U)){if(U!==null)await AY(w);return await Jw({rpxDir:w,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{C.kill(U,"SIGTERM")}catch(W){if(W.code==="ESRCH")return await AY(w),{stopped:!1,pid:U,forced:!1};throw W}let B=Date.now()+A;while(Date.now()<B){if(!r0(U))return N("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`);N("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{C.kill(U,"SIGKILL")}catch(W){if(W.code!=="ESRCH")throw W}return await AY(w),await Vw({rpxDir:w,verbose:Y}).catch((W)=>{N("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function _6($={}){let w=$.rpxDir??w$();if(await d8(w))return;await Jw({rpxDir:w,verbose:$.verbose})}i$();X0();import{spawn as lM}from"node:child_process";import*as l8 from"node:process";class S6{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){N("start",`Process ${$} is already running`,Y);return}let[A,...X]=w.command.split(" "),J=w.cwd||l8.cwd();N("start",`Starting process ${$}:`,Y),N("start",` Command: ${A} ${X.join(" ")}`,Y),N("start",` Working directory: ${J}`,Y),N("start",` Environment variables: ${R$(w.env)}`,Y);let U=lM(A,X,{cwd:J,env:{...l8.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((B,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)N("start",`Process ${$} failed to start: ${j}`,Y),this.processes.delete($),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)N("start",`Process ${$} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete($),W(Error(`Process ${$} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{N("process",`[${$}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{N("process",`[${$}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else N("start",`Process ${$} started successfully`,Y),B()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){N("start",`No process found for ${$}`,w);return}return N("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),N("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){N("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){N("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,N("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var n8=new S6;X0();import*as p0 from"node:fs/promises";import{homedir as nM}from"node:os";import*as aB from"node:path";import*as sB from"node:process";var pM=/^[a-zA-Z0-9._-]+$/;function mw(){return aB.join(nM(),".stacks","rpx","registry.d")}function XY($){return typeof $==="string"&&$.length>0&&$.length<=128&&pM.test($)}function oB($,w){if(!XY(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return aB.join($,`${w}.json`)}function Z6($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0||Array.isArray(w.from)&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&XY(w.id)&&(A||X)&&typeof w.to==="string"&&w.to.length>0&&J&&Y&&typeof w.createdAt==="string"}async function rM($){await p0.mkdir($,{recursive:!0})}async function h6($,w=mw(),Y){if(!Z6($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await rM(w);let A=oB(w,$.id),X=`${A}.tmp.${sB.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),N("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function k6($,w=mw(),Y){let A=oB(w,$);try{await p0.unlink(A),N("registry",`removed entry ${$}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function eB($,w=mw(),Y){let A=oB(w,$);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!Z6(J))return N("registry",`entry ${$} 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 N("registry",`entry ${$} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function $j($=mw(),w){let Y;try{Y=await p0.readdir($)}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(!XY(J))continue;let U=await eB(J,$,w);if(U)A.push(U)}return A}i$();import{execSync as A4}from"node:child_process";import*as YJ from"node:http";import*as i6 from"node:net";import*as J0 from"node:process";var p8=($,w)=>(Y)=>`\x1B[${$}m${Y}\x1B[${w}m`,_$={bold:p8(1,22),dim:p8(2,22),green:p8(32,39),cyan:p8(36,39)};VW();bB();i$();e1();X0();import*as D6 from"node:fs";import*as x6 from"node:path";import*as S$ from"node:process";function tM($,w){let A=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function wj($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,Y=$.registryDir,A=new Set,X=$.proxies.map((K)=>{let F=K.id??tM(K.to,K.path);if(!mY(F))throw Error(`invalid registry id "${F}" derived from to="${K.to}"`);if(A.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return A.add(F),{...K,id:F}}),J=new Date().toISOString();for(let K of X)await x8({id:K.id,from:K.from,to:K.to,path:K.path,pid:$.persistent?void 0:S$.pid,cwd:S$.cwd(),createdAt:J,cleanUrls:K.cleanUrls,changeOrigin:K.changeOrigin,pathRewrites:K.pathRewrites,static:K.static,loadBalancer:K.loadBalancer},Y,w);let U=await w6({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let K of X){let F=K.static?`static ${typeof K.static==="string"?K.static:K.static.dir}`:K.from;R.success(`https://${K.to} → ${F}`)}if(R.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let B=!1,W=Y??L$(),j=X.map((K)=>K.id),z=async()=>{if(B)return;B=!0;for(let K of j)await gY(K,Y,w).catch((F)=>{N("runner",`removeEntry(${K}) failed: ${F}`,w)})},G=(K)=>{N("runner",`received ${K}, unregistering ${j.length} entries`,w),z().finally(()=>S$.exit(0))};S$.once("SIGINT",G),S$.once("SIGTERM",G),S$.once("exit",()=>{if(B)return;for(let K of j)try{D6.unlinkSync(x6.join(W,`${K}.json`))}catch{}}),await new Promise(()=>{})}X0();import{exec as aM}from"node:child_process";import gw from"node:fs";import b6 from"node:os";import Aj from"node:path";import*as aY from"node:process";import{promisify as sM}from"node:util";var tY=sM(aM);function P6($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var G$=aY.platform==="win32"?Aj.join(aY.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",Yj=!1;async function r8($){if(aY.platform==="win32")throw Error("Administrator privileges required on Windows");if(E8()){let{stdout:A}=await tY($);return A}let w=uw(),Y=$.replace(/'/g,"'\\''");try{if(w){let{stdout:A}=await tY(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`);return Yj=!0,A}if(Yj)try{let{stdout:A}=await tY(`sudo -n sh -c '${Y}'`);return A}catch(A){N("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await tY(`sudo -n sh -c '${Y}'`);return Yj=!0,A}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(A){throw Error(`Failed to execute sudo command: ${A.message}`)}}async function sY($,w){let Y=$.filter((X)=>!P6(X)),A=$.filter((X)=>P6(X));if(A.length>0)N("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,w);if(Y.length===0)return;N("hosts",`Adding hosts: ${Y.join(", ")}`,w),N("hosts",`Using hosts file at: ${G$}`,w);try{let X;try{X=await gw.promises.readFile(G$,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{X=await r8(`cat "${G$}"`)}catch(W){throw console.log(" Could not read hosts file — skipping hosts setup"),N("hosts",`sudo read also failed: ${W}`,w),Error(`Cannot read hosts file: ${W}`)}}let J=Y.filter((W)=>{let j=`127.0.0.1 ${W}`,z=`::1 ${W}`;return!X.includes(j)&&!X.includes(z)});if(J.length===0){N("hosts","All hosts already exist in hosts file",w);return}let U=J.map((W)=>`
307
+ `)),this._prevFrame=$;return}this.output.write(GJ.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function $7($,w){if($===void 0)return 0;if(w.length===0)return 0;let A=w.findIndex((X)=>X.value===$);return A!==-1?A:0}function w7($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function Y7($,w){if(!w)return;if($)return w;return w[0]}class A7 extends TJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#A;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return AA.inverse(AA.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...Y]=this.userInput.slice(this._cursor);return`${$}${AA.inverse(w)}${Y.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#A=$.filter??w7;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let A of Y){let X=w.findIndex((J)=>J.value===A);if(X!==-1)this.toggleSelected(A),this.#$=X}this.focusedValue=this.options[this.#$]?.value,this.on("key",(A,X)=>this.#X(A,X)),this.on("userInput",(A)=>this.#J(A))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#X($,w){let Y=w.name==="up",A=w.name==="down",X=w.name==="return";if(Y||A){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=Y7(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#J($){if($!==this.#Y){this.#Y=$;let w=this.options;if($)this.filteredOptions=w.filter((Y)=>this.#A($,Y));else this.filteredOptions=[...w];if(this.#$=$7(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class X7 extends TJ{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return w.every((A)=>Y.includes(A.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),Y=this.getGroupItems(w);if(this.isGroupSelected(w))this.value=this.value.filter((A)=>Y.findIndex((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 w=this.value.includes($.value);this.value=w?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((X)=>({...X,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let A=this.options[this.cursor]?.group===!0;if(!this.#$&&A)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let A=this.options[this.cursor]?.group===!0;if(!this.#$&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var J7=FK();var e=($,w)=>J7?$:w,v4=e("◆","*"),c4=e("■","x"),i4=e("▲","x"),m4=e("◇","o"),g4=e("┌","T"),U7=e("│","|"),d4=e("└","—"),l4=e("●",">"),n4=e("○"," "),p4=e("◻","[•]"),r4=e("◼","[+]"),t4=e("◻","[ ]"),a4=e("▪","•"),s4=e("─","-"),o4=e("╮","+"),e4=e("├","+"),$I=e("╯","+"),wI=e("●","•"),YI=e("◆","*"),AI=e("▲","!"),XI=e("■","x");var JI={light:e("─","-"),heavy:e("━","="),block:e("█","#")};function W7(){return`${AA.gray(U7)} `}var UI=W7();WU();import{homedir as BU}from"node:os";import{join as jU,resolve as EN}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",a9={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:jU(BU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:jU(BU(),".stacks","ssl","stacks.localhost.crt"),keyPath:jU(BU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},zU=null;async function s9(){if(!zU)zU=await UU({name:"rpx",cwd:EN(__dirname,".."),defaultConfig:a9});return zU}var B1=a9;import{existsSync as TN,readdirSync as HN,readFileSync as fN,statSync as RN}from"node:fs";import{homedir as e9}from"node:os";import{isAbsolute as MN,join as z1}from"node:path";var $z=["~/Code"],wz=["localhost","test"],IN=1800000,GU={dirExists:($)=>{try{return RN($).isDirectory()}catch{return!1}},fileExists:($)=>{try{return TN($)}catch{return!1}},readText:($)=>{try{return fN($,"utf8")}catch{return null}}};function KU($,w){if($==="~")return w;if($.startsWith("~/"))return z1(w,$.slice(2));return $}function VN($){let w=$.indexOf(":");return(w===-1?$:$.slice(0,w)).toLowerCase()}function dA($){return $.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function CN($,w){for(let Y of w){let A=`.${Y}`;if($.endsWith(A)){let X=$.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 QN($,w){let Y=w.readText(z1($,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=w.readText(z1($,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function yN($){let w=$.selfRegisters??!1;return{command:$.command,env:$.env,urlEnv:$.urlEnv,selfRegisters:w,routes:$.routes??(w?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function LN($,w){let Y=QN($,w);if(Y?.command)return yN(Y);let A=w.fileExists(z1($,"buddy")),X=w.readText(z1($,"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 ON($,w={}){let Y={dirExists:w.dirExists??GU.dirExists,fileExists:w.fileExists??GU.fileExists,readText:w.readText??GU.readText},A=w.detect??LN,X=w.homeDir??e9(),J=$.tlds??wz,U=($.roots??$z).map((K)=>KU(K,X)),B=$.idleTimeoutMs??IN,W=new Map;for(let K of $.sites??[])W.set(K.to,K);let j=(K)=>K.idleTimeoutMs??B;function z(K){let F=gA(W,K);if(!F)return null;let T=MN(F.dir)?F.dir:KU(F.dir,X),q=F.selfRegisters??!1,E=F.routes??[];if(!q&&E.length===0)E=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let f=o9({...F.env??{}},void 0,K);return{host:K,id:dA(K),dir:T,command:F.command,env:f,routes:E,selfRegisters:q,idleTimeoutMs:j(F),source:"config"}}function G(K){let F=CN(K,J);if(!F)return null;for(let T of U){let q=z1(T,F);if(!Y.dirExists(q))continue;let E=A(q,Y);if(!E)continue;let f=E.selfRegisters??!1;return{host:K,id:dA(K),dir:q,command:E.command,env:o9({...E.env??{}},E.urlEnv,K),routes:f?[]:E.routes??[],selfRegisters:f,idleTimeoutMs:B,source:"discovered"}}return null}return{resolve(K){let F=VN(K);if(!F)return null;return z(F)??G(F)}}}function _N($){try{return HN($,{withFileTypes:!0}).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}function Yz($,w={}){let Y=w.homeDir??e9(),A=$.tlds??wz,X=($.roots??$z).map((G)=>KU(G,Y)),J=w.readdir??_N,U=ON($,w),B=[],W=new Set,j=(G)=>{if(G&&!W.has(G.host))W.add(G.host),B.push(G)};for(let G of $.sites??[])if(!G.to.includes("*"))j(U.resolve(G.to));let z=A[0]??"localhost";for(let G of X)for(let K of J(G))j(U.resolve(`${K}.${z}`));return B}function o9($,w,Y){if(!w)return $;let A=`https://${Y}`;for(let X of w)if($[X]===void 0)$[X]=A;return $}i$();V8();L8();O8();vY();S8();yB();_B();xB();bY();kY();e1();wY();X0();import{spawn as I6}from"node:child_process";import*as b0 from"node:fs/promises";import{homedir as V6}from"node:os";import*as O$ from"node:path";import*as C from"node:process";var uM=5000;function w$(){return O$.join(V6(),".stacks","rpx")}function yw($=w$()){return O$.join($,"daemon.pid")}async function Qw($=w$()){try{let w=await b0.readFile(yw($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function d8($=w$()){let w=await Qw($);return w!==null&&r0(w)}async function C6($=w$()){await b0.mkdir($,{recursive:!0});let w=yw($);while(!0){try{let A=await b0.open(w,"wx");try{await A.write(`${C.pid}
308
+ `)}finally{await A.close()}return w}catch(A){if(A.code!=="EEXIST")throw A}let Y=await Qw($);if(Y!==null&&r0(Y))throw Error(`rpx daemon already running (pid=${Y})`);await b0.unlink(w).catch(()=>{})}}async function AY($=w$()){await b0.unlink(yw($)).catch(()=>{})}var m8=new Map;function g8($){for(let[w,Y]of m8)if(!$.has(w))cw(Y),m8.delete(w)}function vM($,w){let Y=MB(w??"localhost:1");if($.upstreams.length!==Y.length)return!1;return $.upstreams.every((A,X)=>A.url===Y[X])}function Q6($){let w=$.cleanUrls??!1,Y=Q$($.path),A=l1($.auth);if($.static)return{static:PY($.static,w),cleanUrls:w,basePath:Y,auth:A};let X=$.from??"localhost:1",J=Rw(X),U=new URL(J.startsWith("http")?J:`http://${J}`),B=m8.get($.id);if(B&&!vM(B,X))cw(B),B=void 0;if(!B)B=g1(X,$.loadBalancer),d1(B),m8.set($.id,B);return{sourceHost:U.host,upstreamPool:B,cleanUrls:w,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites,basePath:Y,auth:A}}function cM($){return $.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??$[0]??"rpx.localhost"}async function i8($,w,Y=[],A=!1){let X=await y$(w,$.verbose),J=[...new Set([...X.map((z)=>z.to).filter(Boolean),...Y])],U=cM(J),B=[...new Set([U,...J,"rpx.localhost"])],W=RB(J,U,$.verbose);if(typeof $.https==="object"&&typeof W.https==="object")W.https={...W.https,...$.https};let j=await Yw(W);if(j&&(A||!uX(M8,B)))N("daemon",`regenerating shared cert for host(s): ${B.join(", ")}`,$.verbose),I8(),j=null;if(!j)N("daemon","no usable cert on disk, generating one via tlsx",$.verbose),await m1({...W,forceRegenerate:!0}),j=await Yw(W);if(!j)throw Error("failed to bootstrap TLS for rpx daemon");return j}async function iM($,w,Y,A){let X=C.env.SUDO_PASSWORD,J=C.env.HOME??V6(),U=[C.execPath,...C.argv.slice(1)],B=[`HOME=${J}`,`PATH=${C.env.PATH??""}`];if(A)B.push("RPX_VERBOSE=1");for(let[T,q]of Object.entries(C.env))if(q!==void 0&&T!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(T))B.push(`${T}=${q}`);let W=X?["-S","-p","","env",...B,...U]:["-n","env",...B,...U];N("daemon",`elevating daemon via sudo for privileged ports ${w}/${Y}`,A);let j=I6("sudo",W,{detached:!0,stdio:["pipe","ignore","ignore"]}),z=null,G=null;if(j.once("error",(T)=>{z=T}),j.once("exit",(T)=>{G=T??0}),X&&j.stdin)j.stdin.write(`${X}
309
+ `),j.stdin.end();j.unref();let K=yw($),F=Date.now()+15000;while(Date.now()<F){if(z)throw z;let T=await Qw($);if(T!==null&&r0(T)){if(A)R.success(`rpx daemon elevated to root (pid=${T}, https on :${w})`);return{httpsPort:w,httpPort:Y,pidPath:K,done:Promise.resolve(),stop:async()=>{try{C.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(G!==null&&G!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${G}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((q)=>setTimeout(q,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}var f6=!1;function tB(){if(f6)return;f6=!0,C.on("uncaughtException",($)=>{R.error(`rpx daemon: uncaught exception (continuing): ${$?.stack??$}`)}),C.on("unhandledRejection",($)=>{R.error(`rpx daemon: unhandled rejection (continuing): ${$}`)})}function y6($,w,Y){let A;try{A=new URL($.url)}catch{return new Response("Bad Request",{status:400})}let X=($.headers.get("host")??A.hostname).split(":")[0];if(A.pathname.startsWith("/.well-known/acme-challenge/")){if(w){let J=w.challengeStore.handlePath(A.pathname);if(J!==void 0)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(Y){let J=uY(Y,A.pathname);if(J!=null)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(w)return new Response("challenge not found",{status:404})}if(w&&!w.hasCert(X))w.ensureCert(X).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${X}${A.pathname}${A.search}`}})}async function L6($={}){tB();let w=$.verbose??!1,Y=$.rpxDir??w$(),A=$.registryDir??O$.join(Y,"registry.d"),X=$.httpsPort??443,J=$.httpPort??80,U=$.hostname??"0.0.0.0",B=$.gcIntervalMs??uM;if(C.env.RPX_DAEMON_WORKER==="1")return dM({rpxDir:C.env.RPX_WORKER_RPXDIR??Y,registryDir:C.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(C.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:C.env.RPX_WORKER_HOSTNAME??U,verbose:C.env.RPX_WORKER_VERBOSE==="1"||w});let W=X>0&&X<1024||J>0&&J<1024,j=typeof C.getuid==="function"&&C.getuid()===0;if(C.platform!=="win32"&&W&&!j)return iM(Y,X,J,w);let z=Math.max(1,$.workers??(Number.parseInt(C.env.RPX_WORKERS??"",10)||1));if(z>1){if($.onDemandSites?.enabled)R.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return lM($,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:w,gcIntervalMs:B,workers:z})}let G=await C6(Y),K=new Map,F=(y,S)=>t1(K,y,S);function T(y){K=r1(y.map((V$)=>({host:V$.to,path:V$.path,route:Q6(V$)}))),g8(new Set(y.map((V$)=>V$.id)));let S=Array.from(K.keys());N("daemon",`routing table now covers ${S.length} host(s): ${S.join(", ")||"<empty>"}`,w)}await o1(A,w).catch((y)=>{N("daemon",`initial gc failed: ${y}`,w)});let q=await y$(A,w);T(q),await Jw({rpxDir:Y,verbose:w}).catch((y)=>{N("daemon",`DNS reconcile on start failed: ${y}`,w)}),await mw(q,{rpxDir:Y,verbose:w,ownerPid:C.pid}).catch((y)=>{N("daemon",`DNS setup on start failed: ${y}`,w)});let E=[];if($.productionCerts){if(E=await a1($.productionCerts,w),w&&E.length>0)R.info(`SNI: serving ${E.length} real cert(s): ${E.map((y)=>y.serverName).join(", ")}`)}let f=new Set,M=null,Q;if($.onDemandSites?.enabled){if(M=new P8({resolver:OB($.onDemandSites),registryDir:A,rpxDir:Y,verbose:w,startupTimeoutMs:$.onDemandSites.startupTimeoutMs,isHostRoutable:(y)=>_8(K,y)!==void 0,onSiteActivating:(y)=>{_w(y)}}),Q=async(y)=>{let S=await M.onRequest(y);switch(S.kind){case"ready":return{retry:!0};case"starting":return PB({host:S.host,sinceMs:S.sinceMs,logTail:S.logTail});case"failed":return bB({host:S.host,error:S.error,logTail:S.logTail});case"unknown":default:return}},w)R.info("rpx: on-demand sites enabled")}let V=n1(F,w,Q),H=p1(w),I=null;if(E.length===0)I=await i8($,A);let O=$.onDemandTls,Z=O?.enabled?new iY({config:O,certsDir:O.certsDir??$.productionCerts?.certsDir??O$.join(Y,"on-demand-certs"),initial:E,verbose:w,onCertAdded:(y)=>{nw(y)}}):null;function P0(y){if(y.length>0)return y.map((S)=>({serverName:S.serverName,cert:S.cert,key:S.key}));return{key:I.key,cert:I.cert,ca:I.ca,requestCert:!1,rejectUnauthorized:!1}}function Z$(y){return Bun.serve({port:X,hostname:U,reusePort:b1(),tls:P0(y),fetch(S,V$){return V(S,V$)},websocket:H,error(S){return N("daemon",`https server error: ${S}`,w),new Response(`Server Error: ${S.message}`,{status:500})}})}let h$=(y)=>[...new Set(y.map((S)=>S.to).filter(Boolean))],lw=(y)=>{if(!I)return E;return fB([...h$(y),...f,"rpx.localhost"],I)},Ww=Z$(Z?Z.sniEntries():E.length>0?E:lw(q)),Lw=null,Ow=!1;async function nw(y){if(I$)return;if(Lw=y,Ow)return;Ow=!0;try{while(!I$&&Lw){let S=Lw;Lw=null,N("daemon",`rebuilding :443 with ${S.length} SNI cert(s)`,w),Ww.stop(!1);let V$,UJ=!1,Gj=60,s6=500;for(let WJ=0;!I$&&!UJ;WJ++)try{Ww=Z$(S),UJ=!0;break}catch(o6){if(V$=o6,WJ>=Gj)break;await new Promise((e6)=>setTimeout(e6,Math.min(25*2**Math.min(WJ,4),s6)))}if(!UJ)R.error(`rpx: CRITICAL — could not rebind :443 after ${Gj} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${V$?.message}`)}}finally{Ow=!1}}let D$=null;if(J>0)D$=Bun.serve({port:J,hostname:U,fetch(y){return y6(y,Z,$.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if(w)R.success(`rpx daemon listening on https://${U}:${X}${D$?` (http→https on :${J})`:""}`),R.info(`pid file: ${G}`),R.info(`registry: ${A}`);async function h(y){if(I$||E.length>0||Z||!I)return;try{I=await i8($,A,[...f]),await nw(lw(y))}catch(S){N("daemon",`TLS sync on registry change failed: ${S}`,w)}}async function _w(y){if(I$||E.length>0||Z||!I||!y)return;if(f.has(y))return;f.add(y);try{I=await i8($,A,[...f],!0);let S=await y$(A,w);await nw(lw(S))}catch(S){N("daemon",`dev cert refresh for ${y} failed: ${S}`,w)}}let XJ=dY((y)=>{T(y),h(y),mw(y,{rpxDir:Y,verbose:w,ownerPid:C.pid}).catch((S)=>{N("daemon",`DNS sync on registry change failed: ${S}`,w)})},{dir:A,verbose:w}),pw=setInterval(()=>{o1(A,w).then((y)=>{if(y>0)N("daemon",`gc reaped ${y} stale entries`,w)}).catch((y)=>{N("daemon",`periodic gc failed: ${y}`,w)})},B);if(typeof pw.unref==="function")pw.unref();let I$=!1,JY,rw=new Promise((y)=>{JY=y});async function JJ(){if(I$)return rw;if(I$=!0,clearInterval(pw),XJ.close(),await M?.stopAll().catch((y)=>{N("daemon",`site supervisor stopAll failed: ${y}`,w)}),Ww.stop(!1),D$?.stop(!1),await Vw({rpxDir:Y,verbose:w}).catch((y)=>{N("daemon",`DNS teardown failed: ${y}`,w)}),g8(new Set),await AY(Y),w)R.info("rpx daemon stopped");return JY(),rw}let zj=(y)=>{N("daemon",`received ${y}, shutting down`,w),JJ().catch(()=>{})};return C.once("SIGINT",zj),C.once("SIGTERM",zj),{stop:JJ,done:rw,httpsPort:typeof Ww.port==="number"?Ww.port:X,httpPort:D$&&typeof D$.port==="number"?D$.port:J,pidPath:G,ensureCert:(y)=>Z?Z.ensureCert(y):Promise.resolve(!1),listSites:()=>M?.list()??[]}}function aB($){return O$.join($,"cluster-sni.json")}async function R6($,w,Y){let A=aB($),X=`${A}.${C.pid}.tmp`;await b0.writeFile(X,JSON.stringify({sni:w,dev:Y}),"utf8"),await b0.rename(X,A)}async function M6($){try{return JSON.parse(await b0.readFile(aB($),"utf8"))}catch{return{sni:[],dev:null}}}function mM($){if($.sni.length>0)return $.sni.map((w)=>({serverName:w.serverName,cert:w.cert,key:w.key}));if($.dev)return{key:$.dev.key,cert:$.dev.cert,ca:$.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function gM(){let $=C.execPath,w=C.env.RPX_WORKER_BIN;if(w)return[$,w,"daemon:start"];let Y=O$.basename($).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&C.argv[1])return[$,C.argv[1],"daemon:start"];return[$,"daemon:start"]}async function dM($){tB();let{rpxDir:w,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=$,U=new Map,B=(H,I)=>t1(U,H,I),W=(H)=>{U=r1(H.map((I)=>({host:I.to,path:I.path,route:Q6(I)}))),g8(new Set(H.map((I)=>I.id)))};W(await y$(Y,J));let j=n1(B,J),z=p1(J),G=!1,K=(H)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:mM(H),fetch(I,O){return j(I,O)},websocket:z,error(I){return N("daemon",`worker https error: ${I}`,J),new Response(`Server Error: ${I.message}`,{status:500})}}),F=K(await M6(w));async function T(){if(G)return;let H=await M6(w),I=null;for(let Z=0;Z<20&&!G;Z++)try{I=K(H);break}catch{await new Promise((P0)=>setTimeout(P0,25))}if(!I){N("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let O=F;F=I,O.stop(!1)}let q=dY((H)=>W(H),{dir:Y,verbose:J}),E=()=>{T().catch(()=>{})};C.on("SIGHUP",E);let f,M=new Promise((H)=>{f=H});async function Q(){if(G)return M;return G=!0,C.off("SIGHUP",E),q.close(),F.stop(!1),g8(new Set),f(),M}let V=()=>{Q().then(()=>C.exit(0)).catch(()=>C.exit(0))};if(C.once("SIGTERM",V),C.once("SIGINT",V),J)R.success(`rpx worker (pid ${C.pid}) serving :${A}`);return{stop:Q,done:M,httpsPort:typeof F.port==="number"?F.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function lM($,w){tB();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:B,gcIntervalMs:W,workers:j}=w,z=await C6(Y),G=[];if($.productionCerts)G=await a1($.productionCerts,B);let K=null;if(G.length===0)K=await i8($,A);let F=K?{key:K.key,cert:K.cert,ca:Array.isArray(K.ca)?K.ca.join(`
310
+ `):K.ca}:null,T=!1,q=[];function E(h){for(let _w of q)try{_w.kill(h)}catch{}}async function f(h){await R6(Y,h,F),E("SIGHUP")}let M=$.onDemandTls,Q=M?.enabled?new iY({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??O$.join(Y,"on-demand-certs"),initial:G,verbose:B,onCertAdded:(h)=>{f(h)}}):null;await R6(Y,Q?Q.sniEntries():G,F);let V=await y$(A,B);await Jw({rpxDir:Y,verbose:B}).catch((h)=>{N("daemon",`DNS reconcile on start failed: ${h}`,B)}),await mw(V,{rpxDir:Y,verbose:B,ownerPid:C.pid}).catch((h)=>{N("daemon",`DNS setup on start failed: ${h}`,B)}),await o1(A,B).catch(()=>{});let H=dY((h)=>{mw(h,{rpxDir:Y,verbose:B,ownerPid:C.pid}).catch((_w)=>{N("daemon",`DNS sync on registry change failed: ${_w}`,B)})},{dir:A,verbose:B}),I=setInterval(()=>{o1(A,B).catch(()=>{})},W);I.unref?.();let O=null;if(J>0)O=Bun.serve({port:J,hostname:U,fetch(h){return y6(h,Q,$.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let Z=10,P0=60000,Z$=30000,h$=0,lw=Date.now();function Ww(){if(T)return;let h={...C.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:B?"1":"0"},_w=Bun.spawn(gM(),{env:h,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(XJ,pw){if(T)return;let I$=q.indexOf(XJ);if(I$!==-1)q.splice(I$,1);let JY=Date.now();if(JY-lw>P0)lw=JY,h$=0;if(h$++,h$>Z){R.error(`rpx: worker keeps exiting (code ${pw}); giving up after ${Z} restarts in ${Math.round(P0/1000)}s`);return}let rw=Math.min(Z$,100*2**Math.min(h$,8));N("daemon",`worker exited (code ${pw}); respawning in ${rw}ms (restart ${h$}/${Z})`,B),setTimeout(Ww,rw).unref?.()}});q.push(_w)}for(let h=0;h<j;h++)Ww();if(B)R.success(`rpx coordinator listening on https://${U}:${X} via ${j} worker(s)${O?` (http→https on :${J})`:""}`),R.info(`pid file: ${z}`);let Lw,Ow=new Promise((h)=>{Lw=h});async function nw(){if(T)return Ow;if(T=!0,clearInterval(I),H.close(),O?.stop(!1),E("SIGTERM"),await Promise.race([Promise.all(q.map((h)=>h.exited)),new Promise((h)=>setTimeout(h,3000))]),E("SIGKILL"),await Vw({rpxDir:Y,verbose:B}).catch((h)=>{N("daemon",`DNS teardown failed: ${h}`,B)}),await AY(Y),await b0.unlink(aB(Y)).catch(()=>{}),B)R.info("rpx coordinator stopped");return Lw(),Ow}let D$=(h)=>{N("daemon",`coordinator received ${h}, shutting down`,B),nw().catch(()=>{})};return C.once("SIGINT",D$),C.once("SIGTERM",D$),{stop:nw,done:Ow,httpsPort:X,httpPort:J,pidPath:z,ensureCert:(h)=>Q?Q.ensureCert(h):Promise.resolve(!1),listSites:()=>[]}}function nM(){let $=C.execPath,w=O$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&C.argv[1])return[$,C.argv[1],"daemon:start"];return[$,"daemon:start"]}async function O6($={}){let w=$.rpxDir??w$(),Y=$.verbose??!1;await Jw({rpxDir:w,verbose:Y}).catch((z)=>{N("daemon",`DNS reconcile before ensureDaemonRunning: ${z}`,Y)});let A=await Qw(w);if(A!==null&&r0(A))return N("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)N("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await AY(w);await b0.mkdir(w,{recursive:!0});let X=$.spawnCommand??nM();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");N("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=I6(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??C.cwd(),env:$.spawnEnv?{...C.env,...$.spawnEnv}:C.env});J.unref();let U=null;J.once("error",(z)=>{U=z});let B=$.startupTimeoutMs??5000,W=$.pollIntervalMs??50,j=Date.now()+B;while(Date.now()<j){if(U)throw U;let z=await Qw(w);if(z!==null&&r0(z))return N("daemon",`daemon registered with pid=${z}`,Y),{pid:z,spawned:!0};await new Promise((G)=>setTimeout(G,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${B}ms (rpxDir=${w})`)}async function _6($={}){let w=$.rpxDir??w$(),Y=$.verbose??!1,A=$.timeoutMs??5000,X=$.pollIntervalMs??50,J=$.forceAfterTimeout??!0,U=await Qw(w);if(U===null||!r0(U)){if(U!==null)await AY(w);return await Jw({rpxDir:w,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{C.kill(U,"SIGTERM")}catch(W){if(W.code==="ESRCH")return await AY(w),{stopped:!1,pid:U,forced:!1};throw W}let B=Date.now()+A;while(Date.now()<B){if(!r0(U))return N("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`);N("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{C.kill(U,"SIGKILL")}catch(W){if(W.code!=="ESRCH")throw W}return await AY(w),await Vw({rpxDir:w,verbose:Y}).catch((W)=>{N("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function S6($={}){let w=$.rpxDir??w$();if(await d8(w))return;await Jw({rpxDir:w,verbose:$.verbose})}i$();X0();import{spawn as pM}from"node:child_process";import*as l8 from"node:process";class Z6{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){N("start",`Process ${$} is already running`,Y);return}let[A,...X]=w.command.split(" "),J=w.cwd||l8.cwd();N("start",`Starting process ${$}:`,Y),N("start",` Command: ${A} ${X.join(" ")}`,Y),N("start",` Working directory: ${J}`,Y),N("start",` Environment variables: ${R$(w.env)}`,Y);let U=pM(A,X,{cwd:J,env:{...l8.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((B,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)N("start",`Process ${$} failed to start: ${j}`,Y),this.processes.delete($),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)N("start",`Process ${$} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete($),W(Error(`Process ${$} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{N("process",`[${$}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{N("process",`[${$}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else N("start",`Process ${$} started successfully`,Y),B()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){N("start",`No process found for ${$}`,w);return}return N("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),N("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){N("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){N("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,N("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var n8=new Z6;X0();import*as p0 from"node:fs/promises";import{homedir as rM}from"node:os";import*as sB from"node:path";import*as oB from"node:process";var tM=/^[a-zA-Z0-9._-]+$/;function gw(){return sB.join(rM(),".stacks","rpx","registry.d")}function XY($){return typeof $==="string"&&$.length>0&&$.length<=128&&tM.test($)}function eB($,w){if(!XY(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return sB.join($,`${w}.json`)}function h6($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0||Array.isArray(w.from)&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&XY(w.id)&&(A||X)&&typeof w.to==="string"&&w.to.length>0&&J&&Y&&typeof w.createdAt==="string"}async function aM($){await p0.mkdir($,{recursive:!0})}async function D6($,w=gw(),Y){if(!h6($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await aM(w);let A=eB(w,$.id),X=`${A}.tmp.${oB.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),N("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function k6($,w=gw(),Y){let A=eB(w,$);try{await p0.unlink(A),N("registry",`removed entry ${$}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function $j($,w=gw(),Y){let A=eB(w,$);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!h6(J))return N("registry",`entry ${$} 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 N("registry",`entry ${$} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function wj($=gw(),w){let Y;try{Y=await p0.readdir($)}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(!XY(J))continue;let U=await $j(J,$,w);if(U)A.push(U)}return A}i$();import{execSync as J4}from"node:child_process";import*as YJ from"node:http";import*as m6 from"node:net";import*as J0 from"node:process";var p8=($,w)=>(Y)=>`\x1B[${$}m${Y}\x1B[${w}m`,_$={bold:p8(1,22),dim:p8(2,22),green:p8(32,39),cyan:p8(36,39)};VW();uB();i$();e1();X0();import*as x6 from"node:fs";import*as P6 from"node:path";import*as S$ from"node:process";function sM($,w){let A=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function Yj($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,Y=$.registryDir,A=new Set,X=$.proxies.map((K)=>{let F=K.id??sM(K.to,K.path);if(!mY(F))throw Error(`invalid registry id "${F}" derived from to="${K.to}"`);if(A.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return A.add(F),{...K,id:F}}),J=new Date().toISOString();for(let K of X)await x8({id:K.id,from:K.from,to:K.to,path:K.path,pid:$.persistent?void 0:S$.pid,cwd:S$.cwd(),createdAt:J,cleanUrls:K.cleanUrls,changeOrigin:K.changeOrigin,pathRewrites:K.pathRewrites,static:K.static,loadBalancer:K.loadBalancer},Y,w);let U=await Y6({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let K of X){let F=K.static?`static ${typeof K.static==="string"?K.static:K.static.dir}`:K.from;R.success(`https://${K.to} → ${F}`)}if(R.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let B=!1,W=Y??L$(),j=X.map((K)=>K.id),z=async()=>{if(B)return;B=!0;for(let K of j)await gY(K,Y,w).catch((F)=>{N("runner",`removeEntry(${K}) failed: ${F}`,w)})},G=(K)=>{N("runner",`received ${K}, unregistering ${j.length} entries`,w),z().finally(()=>S$.exit(0))};S$.once("SIGINT",G),S$.once("SIGTERM",G),S$.once("exit",()=>{if(B)return;for(let K of j)try{x6.unlinkSync(P6.join(W,`${K}.json`))}catch{}}),await new Promise(()=>{})}X0();import{exec as oM}from"node:child_process";import dw from"node:fs";import u6 from"node:os";import Xj from"node:path";import*as aY from"node:process";import{promisify as eM}from"node:util";var tY=eM(oM);function b6($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var G$=aY.platform==="win32"?Xj.join(aY.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",Aj=!1;async function r8($){if(aY.platform==="win32")throw Error("Administrator privileges required on Windows");if(E8()){let{stdout:A}=await tY($);return A}let w=uw(),Y=$.replace(/'/g,"'\\''");try{if(w){let{stdout:A}=await tY(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`);return Aj=!0,A}if(Aj)try{let{stdout:A}=await tY(`sudo -n sh -c '${Y}'`);return A}catch(A){N("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await tY(`sudo -n sh -c '${Y}'`);return Aj=!0,A}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(A){throw Error(`Failed to execute sudo command: ${A.message}`)}}async function sY($,w){let Y=$.filter((X)=>!b6(X)),A=$.filter((X)=>b6(X));if(A.length>0)N("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,w);if(Y.length===0)return;N("hosts",`Adding hosts: ${Y.join(", ")}`,w),N("hosts",`Using hosts file at: ${G$}`,w);try{let X;try{X=await dw.promises.readFile(G$,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{X=await r8(`cat "${G$}"`)}catch(W){throw console.log(" Could not read hosts file — skipping hosts setup"),N("hosts",`sudo read also failed: ${W}`,w),Error(`Cannot read hosts file: ${W}`)}}let J=Y.filter((W)=>{let j=`127.0.0.1 ${W}`,z=`::1 ${W}`;return!X.includes(j)&&!X.includes(z)});if(J.length===0){N("hosts","All hosts already exist in hosts file",w);return}let U=J.map((W)=>`
311
311
  # Added by rpx
312
312
  127.0.0.1 ${W}
313
313
  ::1 ${W}`).join(`
314
- `),B=Aj.join(b6.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await gw.promises.writeFile(B,X+U,"utf8"),await r8(`cat "${B}" | tee "${G$}" > /dev/null`),console.log(` Hosts updated: ${J.join(", ")}`)}catch(W){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),J.forEach((j)=>{console.log(` 127.0.0.1 ${j}`),console.log(` ::1 ${j}`)}),console.log(` Or run: sudo nano ${G$}`)}finally{try{await gw.promises.unlink(B)}catch{}}}catch(X){N("hosts",`Failed to manage hosts file: ${X.message}`,w)}}async function u6($,w){N("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let Y;try{Y=await gw.promises.readFile(G$,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{Y=await r8(`cat "${G$}"`)}catch(W){throw N("hosts",`sudo read also failed: ${W}`,w),Error(`Cannot read hosts file: ${W}`)}}let A=Y.split(`
314
+ `),B=Xj.join(u6.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await dw.promises.writeFile(B,X+U,"utf8"),await r8(`cat "${B}" | tee "${G$}" > /dev/null`),console.log(` Hosts updated: ${J.join(", ")}`)}catch(W){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),J.forEach((j)=>{console.log(` 127.0.0.1 ${j}`),console.log(` ::1 ${j}`)}),console.log(` Or run: sudo nano ${G$}`)}finally{try{await dw.promises.unlink(B)}catch{}}}catch(X){N("hosts",`Failed to manage hosts file: ${X.message}`,w)}}async function v6($,w){N("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let Y;try{Y=await dw.promises.readFile(G$,"utf-8")}catch{N("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{Y=await r8(`cat "${G$}"`)}catch(W){throw N("hosts",`sudo read also failed: ${W}`,w),Error(`Cannot read hosts file: ${W}`)}}let A=Y.split(`
315
315
  `),X=!1,J=A.filter((W)=>{if($.some((z)=>W.includes(` ${z}`)&&(W.includes("127.0.0.1")||W.includes("::1"))))return X=!0,!1;if(W.trim()==="# Added by rpx")return X=!0,!1;return!0});if(!X){N("hosts","No matching hosts found to remove",w);return}while(J[J.length-1]?.trim()==="")J.pop();let U=`${J.join(`
316
316
  `)}
317
- `,B=Aj.join(b6.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await gw.promises.writeFile(B,U,"utf8"),await r8(`cat "${B}" | tee "${G$}" > /dev/null`),N("hosts","Hosts removed successfully",w)}catch(W){N("hosts","Could not clean up hosts file automatically",w)}finally{try{await gw.promises.unlink(B)}catch(W){N("hosts",`Failed to remove temporary file: ${W}`,w)}}}catch(Y){N("hosts",`Failed to clean up hosts file: ${Y.message}`,w)}}async function oY($,w){N("hosts",`Checking hosts: ${$}`,w);let Y;try{Y=await gw.promises.readFile(G$,"utf-8")}catch(A){N("hosts",`Error reading hosts file: ${A}`,w);try{let X=uw(),J;if(X)J=`echo '${X}' | sudo -S cat "${G$}" 2>/dev/null`;else J=`sudo -n cat "${G$}" 2>/dev/null || cat "${G$}" 2>/dev/null || echo ""`;let{stdout:U}=await tY(J);Y=U}catch(X){return N("hosts",`Cannot read hosts file, assuming entries don't exist: ${X}`,w),$.map(()=>!1)}}return $.map((A)=>{let X=`127.0.0.1 ${A}`,J=`::1 ${A}`;return Y.includes(X)||Y.includes(J)})}V8();SB();i$();X0();import{spawn as oM}from"node:child_process";import*as t8 from"node:process";class a8{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){N("start",`Process ${$} is already running`,Y);return}let[A,...X]=w.command.split(" "),J=w.cwd||t8.cwd();N("start",`Starting process ${$}:`,Y),N("start",` Command: ${A} ${X.join(" ")}`,Y),N("start",` Working directory: ${J}`,Y),N("start",` Environment variables: ${R$(w.env)}`,Y);let U=oM(A,X,{cwd:J,env:{...t8.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((B,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)N("start",`Process ${$} failed to start: ${j}`,Y),this.processes.delete($),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)N("start",`Process ${$} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete($),W(Error(`Process ${$} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{N("process",`[${$}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{N("process",`[${$}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else N("start",`Process ${$} started successfully`,Y),B()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){N("start",`No process found for ${$}`,w);return}return N("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),N("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){N("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){N("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,N("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var l_=new a8;import{timingSafeEqual as eM}from"node:crypto";function $4($,w){if($==null)return!1;let Y=Buffer.from($),A=Buffer.from(w);if(Y.length!==A.length)return!1;return eM(Y,A)}function s8($){return $.toLowerCase().replace(/\.$/,"")}var w4=["/.well-known/acme-challenge/"];function Y4($){let w=$.headers.get("host");if(w)return s8(w.split(":")[0]);try{return s8(new URL($.url).hostname)}catch{return""}}function v6($){let w=$.header.toLowerCase(),Y=new Set,A=[];for(let W of $.hosts){let j=s8(W);if(j.startsWith("*."))A.push(j);else Y.add(j)}let X=$.exemptPaths??w4,J=$.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
318
- `,U=(W)=>{let j=s8(W);return Y.has(j)||A.some((z)=>NY(j,z))},B=(W)=>{let j=Y4(W);if(!U(j))return;let z="/";try{z=new URL(W.url).pathname}catch{}if(X.some((G)=>z.startsWith(G)))return;if($4(W.headers.get(w),$.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return B.protects=U,B}L8();O8();DY();vY();S8();bY();X0();var e8=new a8,X4="0.12.0",J4=new h8("0.0.0.0"),$J=new Set,wJ=new Set,Xj=!1,o8=null,Jj=null;async function AJ($){if(Xj)return N("cleanup","Cleanup already in progress, skipping",$?.verbose),Jj||Promise.resolve();Xj=!0,N("cleanup","Starting cleanup process",$?.verbose),Jj=new Promise((w)=>{o8=w});try{await e8.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],Y=Array.from($J).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),N("cleanup","Bun server stopped",$?.verbose),X();else if(typeof J.close==="function")J.close(()=>{N("cleanup","Server closed successfully",$?.verbose),X()});else X()}catch(U){N("cleanup",`Error stopping server: ${U}`,$?.verbose),X()}}));w.push(...Y),$J.clear();for(let A of wJ)d1(A);if(wJ.clear(),$?.hosts&&$.domains?.length){N("cleanup","Cleaning up hosts file entries",$?.verbose),N("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let A=$.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(N("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,$?.verbose),A.length>0)R.info("Cleaning up hosts file entries..."),w.push(u6(A,$?.verbose).then(()=>{N("cleanup",`Removed hosts entries for ${A.join(", ")}`,$?.verbose)}).catch((X)=>{N("cleanup",`Failed to remove hosts entries: ${X}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if($?.certs&&$.domains?.length){N("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let A=$.domains.map(async(X)=>{try{await f5(X,$?.verbose),N("cleanup",`Removed certificates for ${X}`,$?.verbose)}catch(J){N("cleanup",`Failed to remove certificates for ${X}: ${J}`,$?.verbose),R.warn(`Failed to clean up certificates for ${X}:`,J)}});w.push(...A)}await Promise.allSettled(w),N("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){N("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(o8)o8();o8=null,Xj=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(J0.env.NODE_ENV!=="test"&&J0.env.BUN_ENV!=="test"&&!w)J0.exit(0)}return Jj}var Uj=!1;function m6($){if(Uj){N("signal",`Received second ${$} signal, forcing exit`,!0),J0.exit(1);return}Uj=!0,N("signal",`Received ${$} signal, initiating cleanup`,!0),AJ().catch((w)=>{N("signal",`Cleanup failed after ${$}: ${w}`,!0),J0.exit(1)}).finally(()=>{Uj=!1})}J0.once("SIGINT",()=>m6("SIGINT"));J0.once("SIGTERM",()=>m6("SIGTERM"));J0.on("uncaughtException",($)=>{R.error("Uncaught exception (continuing):",$)});J0.on("unhandledRejection",($)=>{R.error("Unhandled rejection (continuing):",$)});async function eY($,w,Y,A=5){N("connection",`Testing connection to ${$}:${w} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(J0.env.RPX_BYPASS_CONNECTION_TEST==="true"){N("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((B,W)=>{let j=i6.connect({host:$,port:w,timeout:3000});j.once("connect",()=>{N("connection",`Successfully connected to ${$}:${w}`,Y),j.end(),B()}),j.once("timeout",()=>{N("connection",`Connection to ${$}:${w} timed out`,Y),j.destroy(),W(Error("Connection timed out"))}),j.once("error",(z)=>{N("connection",`Failed to connect to ${$}:${w}: ${z}`,Y),j.destroy(),W(z)})});try{await U()}catch(B){let W=B;if(Date.now()-J>X){N("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return N("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),eY($,w,Y,A-1);if(A>0)try{N("connection",`Trying HTTP request to ${$}:${w}`,Y),await new Promise((z,G)=>{let K=YJ.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(F)=>{N("connection",`Received HTTP response with status: ${F.statusCode}`,Y),z()});K.on("error",(F)=>G(F)),K.on("timeout",()=>{K.destroy(),G(Error("HTTP request timed out"))}),K.end()}),N("connection",`HTTP request to ${$}:${w} succeeded`,Y);return}catch(z){return N("connection",`HTTP request to ${$}:${w} failed: ${z}`,Y),N("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((G)=>setTimeout(G,2000)),eY($,w,Y,A-1)}let j=`Failed to connect to ${$}:${w} after ${5-A} attempts: ${W.message}`;N("connection",`${j}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),R.warn(j),R.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function g6($){N("server",`Starting server with options: ${R$($)}`,$.verbose);let w=Rw($.from),Y=new URL(w.startsWith("http")?w:`http://${w}`),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(Bj($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){N("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await oY(J,$.verbose))[0]){R.info(`Adding ${A.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await sY(J,$.verbose)}catch(W){if(R.error("Failed to add hosts entry:",W.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${A.hostname}`),R.warn(`::1 ${A.hostname}`),J0.platform==="win32")R.warn("On Windows:"),R.warn("1. Run notepad as administrator"),R.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else R.warn("On Unix systems:"),R.warn("sudo nano /etc/hosts")}}else N("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(B){R.error("Failed to check hosts file:",B.message)}}try{await eY(Y.hostname,X,$.verbose)}catch(B){N("server",`Connection test failed: ${B}`,$.verbose),R.error(B.message),R.warn("Continuing with proxy setup despite connection test failure..."),R.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=ZY({...$,to:A.hostname});if(U=await Yw({...$,to:A.hostname,https:$.https}),!U){if(N("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await i1({...$,from:Y.toString(),to:A.hostname,https:$.https}),U=await Yw({...$,to:A.hostname,https:$.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(B){throw N("server",`SSL setup failed: ${B}`,$.verbose),B}N("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await W4({...$,from:w,originalFrom:$.from||w,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function U4($,w,Y,A,X,J,U,B,W,j,z,G){N("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,U);let K=m1(z??A.host,G);g1(K);let F=[{host:w,route:{sourceHost:A.host,upstreamPool:K,cleanUrls:B||!1,changeOrigin:W||!1,basePath:"/",auth:j}}];if(!Wj({routeEntries:F,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw d1(K),Error(`Failed to start proxy server for ${w} on port ${Y}`);wJ.add(K),j4({from:$,to:w,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:B,verbose:U})}async function W4($){N("setup",`Setting up reverse proxy: ${R$($)}`,$.verbose);let{from:w,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:B,vitePluginUsage:W,changeOrigin:j,cleanUrls:z}=$,G=80,K=443,F="0.0.0.0",T=$.portManager||J4,q=Bj($);try{if(q&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await oY([A],U))[0]){R.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await sY([A],U),R.success(`Added ${A} to your hosts file.`)}catch(V){R.error(`Failed to add ${A} to your hosts file: ${V}`),R.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(q&&J0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await oY([A],U))[0]){N("hosts",`${A} not found in hosts file, adding...`,U);try{await sY([A],U)}catch(V){N("hosts",`Failed to add ${A} to hosts file: ${V}`,U)}}}if(J&&!T.usedPorts.has(G)){if(!await Iw(G,F,U))N("setup","Starting HTTP redirect server",U),d6(U),T.usedPorts.add(G);else if(N("setup","Port 80 is in use, skipping HTTP redirect",U),U)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let E=J?K:G,f=await Iw(E,F,U),M;if(f){if(N("setup",`Port ${E} is already in use`,U),U)R.warn(`Port ${E} is already in use. This may be another instance of rpx or another service.`);if(E===443){if(M=await T.getNextAvailablePort(3443,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at https://${A}:${M}`)}else if(M=await T.getNextAvailablePort(E+1000,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at http://${A}:${M}`)}else M=E,T.usedPorts.add(M),N("setup",`Using standard ${E===443?"HTTPS":"HTTP"} port ${E} for ${A}`,U);await U4(w,A,M,X,J,W,U,z,j,l1($.auth),Y,$.loadBalancer)}catch(E){N("setup",`Setup failed: ${E}`,U),R.error(`Failed to setup reverse proxy: ${E.message}`),AJ({domains:[A],hosts:typeof B==="boolean"?B:B?.hosts,certs:typeof B==="boolean"?B:B?.certs,verbose:U,vitePluginUsage:W})}}function d6($,w=80,Y=443,A){N("redirect",`Starting HTTP redirect server on port ${w}`,$);let X=YJ.createServer((J,U)=>{if(A&&J.url){let z=J.url.split("?",1)[0],G=uY(A,z);if(G!=null){N("redirect",`Serving ACME challenge ${z}`,$),U.writeHead(200,{"content-type":"text/plain"}),U.end(G);return}}let B=J.headers.host||"",W=B.includes(":")?B.slice(0,B.indexOf(":")):B,j=Y===443?W:`${W}:${Y}`;N("redirect",`Redirecting request from ${B}${J.url} to https://${j}`,$),U.writeHead(301,{Location:`https://${j}${J.url}`}),U.end()}).listen(w);$J.add(X),N("redirect","HTTP redirect server started",$)}function l6($){let w={...IW,...$};if(N("proxy",`Starting proxy with options: ${R$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}wj({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((W)=>{R.error(`Failed to register with rpx daemon: ${W.message}`),J0.exit(1)});return}let Y=w.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=J0.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)&&w?.verbose)R.warn(`The .${A} TLD may not work reliably for local development`),R.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),R.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (wY(),c8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:w.verbose}).then((j)=>{if(j)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(A))R.success(`DNS server started for .${A} domains`);else R.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else N("dns",`Could not start DNS server - ${Y} may not resolve in browser`,w.verbose)})}).catch((W)=>{N("dns",`Failed to start DNS server: ${W}`,w.verbose)});let B={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:ZY(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};N("proxy",`Server options: ${R$(B)}`,w.verbose),g6(B).catch((W)=>{N("proxy",`Failed to start proxy: ${W}`,w.verbose),R.error(`Failed to start proxy: ${W.message}`),AJ({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function B4($){return $?.verbose||!1}function Bj($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function n6($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let Y=B4(w),A=Bj(w);if(N("config",`Starting with config: ${R$(w,2)}`,Y),N("config",`Is multi-proxy? ${"proxies"in w}`,Y),N("config",`Hosts management enabled? ${A}`,Y),w.viaDaemon){let I="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((O)=>({id:O.id,from:O.from,to:O.to,path:O.path,cleanUrls:O.cleanUrls??w.cleanUrls,changeOrigin:O.changeOrigin??w.changeOrigin,pathRewrites:O.pathRewrites})):[{id:w.id,from:w.from,to:w.to??"rpx.localhost",path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await wj({proxies:I,verbose:Y});return}if("proxies"in w&&Array.isArray(w.proxies)){N("servers",`Found ${w.proxies.length} proxies in config`,Y);for(let H of w.proxies)if(H.start){let I=`${H.from}-${H.to}`;try{N("watch",`Starting command for ${I} with command: ${H.start.command}`,Y),R.info(`Starting command for ${I}...`),await e8.startProcess(I,H.start,Y);let O=Rw(H.from),Z=new URL(O.startsWith("http")?O:`http://${O}`),P0=Z.hostname||"localhost",Z$=Number(Z.port)||80;try{await eY(P0,Z$,Y),N("watch",`Dev server is ready at ${P0}:${Z$}`,Y)}catch(h$){N("watch",`Connection check failed, but continuing with proxy setup: ${h$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(O){throw N("watch",`Failed to start command for ${I}: ${O}`,Y),Error(`Failed to start command for ${I}: ${O}`)}}else N("watch",`No start command for proxy ${H.from} -> ${H.to}`,Y)}else if("start"in w&&w.start){N("watch","Found start command in single proxy config",Y);let H=`${w.from}-${w.to}`;try{if(w.start)N("watch",`Starting command: ${w.start.command}`,Y),await e8.startProcess(H,w.start,Y);let I=Rw(w.from),O=new URL(I.startsWith("http")?I:`http://${I}`),Z=O.hostname||"localhost",P0=Number(O.port)||80;try{await eY(Z,P0,Y),N("watch",`Dev server is ready at ${Z}:${P0}`,Y)}catch(Z$){N("watch",`Connection check failed, but continuing with proxy setup: ${Z$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw N("watch",`Failed to run start command: ${I}`,Y),Error(`Failed to run start command: ${I}`)}}else N("watch","No start command found in config",Y);let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(J0.platform!=="win32"&&(w.https||A)){if(!uw())try{N("sudo","Pre-acquiring sudo credentials for privileged operations",Y),A4("sudo -v",{stdio:"inherit"})}catch{N("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if(w.productionCerts){if(J=await a1(w.productionCerts,Y),J.length>0)N("ssl",`Using ${J.length} production SNI cert(s): ${J.map((H)=>H.serverName).join(", ")}`,Y)}if(w.https){let H=J.length>0?null:await Yw(w);if(!H&&J.length===0){if(N("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,w.verbose),await i1(w),H=await Yw(w),!H)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else N("ssl",`Using existing and trusted certificates for ${X}`,w.verbose);w._cachedSSLConfig=H}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({...H,https:w.https,cleanup:w.cleanup,cleanUrls:H.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:H.changeOrigin??w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,auth:"auth"in w?w.auth:void 0,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig}],B=U.map((H)=>H.to||"rpx.localhost"),W=J.length>0?J:w._cachedSSLConfig??null,j=B.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),z=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"],K=[...new Set(j.map((H)=>H.split(".").pop()?.toLowerCase()))],F=K.filter((H)=>!!H&&z.includes(H));if(F.length>0&&Y)R.warn(`The following TLDs may not work reliably for local development: ${F.map((H)=>`.${H}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&J0.platform==="darwin"&&j.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (wY(),c8));if(await H({domains:j,verbose:Y})){if(Y)if(K.every((Z)=>!!Z&&G.includes(Z)))R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains`);else R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains (hosts file entries also added)`)}else N("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{N("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (wY(),c8));await H({verbose:w.verbose})}catch(H){N("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await e8.stopAll(w.verbose)}catch(H){N("cleanup",`Error stopping processes: ${H}`,w.verbose)}await AJ({domains:B,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};J0.on("SIGINT",T),J0.on("SIGTERM",T);let q=w.singlePortMode===!0,E=w.httpsPort??443,f=w.httpPort??80,M=w.originGuard?v6(w.originGuard):null,Q=!!W&&(U.length>1||q||J.length>0),V=!W&&q&&U.length>0;if(Q&&W){N("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${E}`,Y);let H=await c6(U,A,Y);if(!await Iw(f,"0.0.0.0",Y))d6(Y,f,E,w.acmeChallengeWebroot);if(await Iw(E,"0.0.0.0",Y)){if(N("proxies",`Port ${E} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${E} is in use. Shared HTTPS proxy cannot start.`);return}if(!Wj({routeEntries:H,listenPort:E,sslConfig:W,originGuard:M,verbose:Y})){R.error(`Shared HTTPS proxy failed to bind :${E}; not exiting`);return}}else if(V){N("proxies",`Creating shared HTTP server for ${U.length} domains on port ${f}`,Y);let H=await c6(U,A,Y);if(await Iw(f,"0.0.0.0",Y)){if(N("proxies",`Port ${f} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${f} is in use. Shared HTTP proxy cannot start.`);return}if(!Wj({routeEntries:H,listenPort:f,sslConfig:null,originGuard:M,verbose:Y})){R.error(`Shared HTTP proxy failed to bind :${f}; not exiting`);return}}else for(let H of U)try{let I=H.to||"rpx.localhost";N("proxy",`Starting proxy for ${I} with SSL config: ${!!W}`,H.verbose),await g6({from:H.from||"localhost:5173",to:I,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:w._cachedSSLConfig,changeOrigin:H.changeOrigin||!1,loadBalancer:H.loadBalancer,auth:H.auth,path:H.path,pathRewrites:H.pathRewrites})}catch(I){N("proxies",`Failed to start proxy for ${H.to}: ${I}`,H.verbose),R.error(`Failed to start proxy for ${H.to}:`,I)}}async function c6($,w,Y){let A=[],X=new Set;for(let J of $){let U=J.to||"rpx.localhost",B=J.cleanUrls||!1,W=J.path,j=Q$(W),z=l1(J.auth);if(J.redirect){let G=D5(J.redirect);A.push({host:U,path:W,route:{redirect:G,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → redirect ${G.status} ${G.to}${z?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:PY(J.static,B),cleanUrls:B,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${z?" (auth)":""}`,Y);else{let G=Rw(J.from),K=new URL(G.startsWith("http")?G:`http://${G}`),F=m1(J.from??K.host,J.loadBalancer);g1(F),wJ.add(F),A.push({host:U,path:W,route:{sourceHost:K.host,upstreamPool:F,cleanUrls:B,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → ${K.host}${z?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),w&&!B1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await oY([U],Y))[0])await sY([U],Y)}catch{N("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function Wj($){let{routeEntries:w,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=$,U=r1(w),B=n1((z,G)=>t1(U,z,G),J),W=X?(z,G)=>X(z)??B(z,G):B,j=p1(J);try{let z=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:P1(),...A?{tls:Array.isArray(A)?A.map((G)=>({serverName:G.serverName,key:G.key,cert:G.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(G,K){return W(G,K)},websocket:j,error(G){return N("server",`Shared proxy server error: ${G}`,J),new Response(`Server Error: ${G.message}`,{status:500})}});return $J.add(z),N("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),z}catch(z){return N("proxies",`Failed to start shared proxy: ${z}`,J),console.error("Failed to start shared proxy:",z),null}}function j4($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${_$.green(_$.bold("rpx"))} ${_$.green(`v${X4}`)}`),console.log(` ${_$.green("➜")} ${_$.dim($?.from??"")} ${_$.dim("➜")} ${_$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${_$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${_$.green("➜")} Clean URLs enabled`)}WB();var MS=new bw("rpx",{showTags:!1});function p6($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}x0.chdir(G4(z4(K4(import.meta.url)),".."));var u0=new EJ("rpx"),r6="0.12.0";u0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async($)=>{if(!$?.from||!$.to)return n6(W1);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,singlePortMode:$.singlePortMode||!1,httpPort:$.httpPort!==void 0?Number($.httpPort):void 0,httpsPort:$.httpsPort!==void 0?Number($.httpsPort):void 0,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let Y={command:$.startCommand};if($.startCwd)Y.cwd=$.startCwd;if($.startEnv)try{Y.env=JSON.parse($.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),x0.exit(1)}w.start=Y}return l6(w)});u0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let Y=p6(W1)?W1.proxies.find((A)=>A.to===$||`${A.from}-${A.to}`===$):W1.to===$?W1:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${$}`),x0.exit(1);try{await n8.startProcess($,Y.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(A){console.error(`Failed to start dev server for ${$}:`,A),x0.exit(1)}});u0.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 ${$}`)}catch(Y){console.error(`Failed to stop dev server for ${$}:`,Y),x0.exit(1)}});u0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await n8.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),x0.exit(1)}});async function t6($){let Y={...(await a9().catch(()=>null))?.onDemand??{},enabled:!0};if($){let A=$.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}u0.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($)=>{try{let w=$.onDemand?await t6($.roots):void 0;await(await y6({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,onDemandSites:w,verbose:$.verbose??!0})).done,x0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),x0.exit(1)}});u0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,Y=await O6({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});u0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??w$(),Y=await Qw(w),A=await d8(w),X=$.registryDir,J=await $j(X).catch(()=>[]);if($.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:yw(w),rpxDir:w,registryDir:X??mw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${yw(w)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${yw(w)}`);if(console.log(`registry: ${X??mw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let B=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${B})`)}});u0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),x0.exit(1);if(!XY($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),x0.exit(1);try{await h6({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),x0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await L6({rpxDir:$.rpxDir,verbose:$.verbose}),Y=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${Y} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),x0.exit(1)}});u0.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(!XY($))console.error(`invalid id: ${JSON.stringify($)}`),x0.exit(1);let Y=await eB($,w.registryDir,w.verbose);if(!Y){console.log(`no registry entry for id=${$}`);return}await k6($,w.registryDir,w.verbose),console.log(`unregistered ${Y.to} (id=${$})`)});u0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??w$();if(await d8(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await _6({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});u0.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($)=>{let w=await t6($.roots),Y=wz(w),A=await $j($.registryDir).catch(()=>[]),X=new Set(A.map((B)=>B.to)),J=Y.map((B)=>({host:B.host,dir:B.dir,command:B.command,source:B.source,live:X.has(B.host)}));if($.json){console.log(JSON.stringify(J,null,2));return}let U=w.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}) \u2014 scanned ${U.join(", ")}:`);for(let B of J)console.log(` ${B.live?"\u25CF":"\u25CB"} https://${B.host} ${B.live?"(live)":"(idle)"}`),console.log(` ${B.command} ${B.dir}`)});u0.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("fs/promises"),{join:A}=await import("path"),X=w.rpxDir??w$(),J=A(X,"sites",`${dA($.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${$} (it may not have been booted yet) \u2014 looked in ${J}`);return}let B=w.lines===void 0?void 0:typeof w.lines==="string"?Number.parseInt(w.lines,10):w.lines,W=U.split(`
317
+ `,B=Xj.join(u6.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await dw.promises.writeFile(B,U,"utf8"),await r8(`cat "${B}" | tee "${G$}" > /dev/null`),N("hosts","Hosts removed successfully",w)}catch(W){N("hosts","Could not clean up hosts file automatically",w)}finally{try{await dw.promises.unlink(B)}catch(W){N("hosts",`Failed to remove temporary file: ${W}`,w)}}}catch(Y){N("hosts",`Failed to clean up hosts file: ${Y.message}`,w)}}async function oY($,w){N("hosts",`Checking hosts: ${$}`,w);let Y;try{Y=await dw.promises.readFile(G$,"utf-8")}catch(A){N("hosts",`Error reading hosts file: ${A}`,w);try{let X=uw(),J;if(X)J=`echo '${X}' | sudo -S cat "${G$}" 2>/dev/null`;else J=`sudo -n cat "${G$}" 2>/dev/null || cat "${G$}" 2>/dev/null || echo ""`;let{stdout:U}=await tY(J);Y=U}catch(X){return N("hosts",`Cannot read hosts file, assuming entries don't exist: ${X}`,w),$.map(()=>!1)}}return $.map((A)=>{let X=`127.0.0.1 ${A}`,J=`::1 ${A}`;return Y.includes(X)||Y.includes(J)})}V8();ZB();i$();X0();import{spawn as $4}from"node:child_process";import*as t8 from"node:process";class a8{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){N("start",`Process ${$} is already running`,Y);return}let[A,...X]=w.command.split(" "),J=w.cwd||t8.cwd();N("start",`Starting process ${$}:`,Y),N("start",` Command: ${A} ${X.join(" ")}`,Y),N("start",` Working directory: ${J}`,Y),N("start",` Environment variables: ${R$(w.env)}`,Y);let U=$4(A,X,{cwd:J,env:{...t8.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((B,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)N("start",`Process ${$} failed to start: ${j}`,Y),this.processes.delete($),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)N("start",`Process ${$} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete($),W(Error(`Process ${$} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{N("process",`[${$}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{N("process",`[${$}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),W(Error(`Process ${$} was killed during startup`));else N("start",`Process ${$} started successfully`,Y),B()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){N("start",`No process found for ${$}`,w);return}return N("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),N("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){N("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){N("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){N("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,N("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var p_=new a8;import{timingSafeEqual as w4}from"node:crypto";function Y4($,w){if($==null)return!1;let Y=Buffer.from($),A=Buffer.from(w);if(Y.length!==A.length)return!1;return w4(Y,A)}function s8($){return $.toLowerCase().replace(/\.$/,"")}var A4=["/.well-known/acme-challenge/"];function X4($){let w=$.headers.get("host");if(w)return s8(w.split(":")[0]);try{return s8(new URL($.url).hostname)}catch{return""}}function c6($){let w=$.header.toLowerCase(),Y=new Set,A=[];for(let W of $.hosts){let j=s8(W);if(j.startsWith("*."))A.push(j);else Y.add(j)}let X=$.exemptPaths??A4,J=$.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
318
+ `,U=(W)=>{let j=s8(W);return Y.has(j)||A.some((z)=>NY(j,z))},B=(W)=>{let j=X4(W);if(!U(j))return;let z="/";try{z=new URL(W.url).pathname}catch{}if(X.some((G)=>z.startsWith(G)))return;if(Y4(W.headers.get(w),$.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return B.protects=U,B}L8();O8();kY();vY();S8();bY();X0();var e8=new a8,U4="0.12.0",W4=new h8("0.0.0.0"),$J=new Set,wJ=new Set,Jj=!1,o8=null,Uj=null;async function AJ($){if(Jj)return N("cleanup","Cleanup already in progress, skipping",$?.verbose),Uj||Promise.resolve();Jj=!0,N("cleanup","Starting cleanup process",$?.verbose),Uj=new Promise((w)=>{o8=w});try{await e8.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],Y=Array.from($J).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),N("cleanup","Bun server stopped",$?.verbose),X();else if(typeof J.close==="function")J.close(()=>{N("cleanup","Server closed successfully",$?.verbose),X()});else X()}catch(U){N("cleanup",`Error stopping server: ${U}`,$?.verbose),X()}}));w.push(...Y),$J.clear();for(let A of wJ)cw(A);if(wJ.clear(),$?.hosts&&$.domains?.length){N("cleanup","Cleaning up hosts file entries",$?.verbose),N("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let A=$.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(N("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,$?.verbose),A.length>0)R.info("Cleaning up hosts file entries..."),w.push(v6(A,$?.verbose).then(()=>{N("cleanup",`Removed hosts entries for ${A.join(", ")}`,$?.verbose)}).catch((X)=>{N("cleanup",`Failed to remove hosts entries: ${X}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if($?.certs&&$.domains?.length){N("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let A=$.domains.map(async(X)=>{try{await R5(X,$?.verbose),N("cleanup",`Removed certificates for ${X}`,$?.verbose)}catch(J){N("cleanup",`Failed to remove certificates for ${X}: ${J}`,$?.verbose),R.warn(`Failed to clean up certificates for ${X}:`,J)}});w.push(...A)}await Promise.allSettled(w),N("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){N("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(o8)o8();o8=null,Jj=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(J0.env.NODE_ENV!=="test"&&J0.env.BUN_ENV!=="test"&&!w)J0.exit(0)}return Uj}var Wj=!1;function g6($){if(Wj){N("signal",`Received second ${$} signal, forcing exit`,!0),J0.exit(1);return}Wj=!0,N("signal",`Received ${$} signal, initiating cleanup`,!0),AJ().catch((w)=>{N("signal",`Cleanup failed after ${$}: ${w}`,!0),J0.exit(1)}).finally(()=>{Wj=!1})}J0.once("SIGINT",()=>g6("SIGINT"));J0.once("SIGTERM",()=>g6("SIGTERM"));J0.on("uncaughtException",($)=>{R.error("Uncaught exception (continuing):",$)});J0.on("unhandledRejection",($)=>{R.error("Unhandled rejection (continuing):",$)});async function eY($,w,Y,A=5){N("connection",`Testing connection to ${$}:${w} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(J0.env.RPX_BYPASS_CONNECTION_TEST==="true"){N("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((B,W)=>{let j=m6.connect({host:$,port:w,timeout:3000});j.once("connect",()=>{N("connection",`Successfully connected to ${$}:${w}`,Y),j.end(),B()}),j.once("timeout",()=>{N("connection",`Connection to ${$}:${w} timed out`,Y),j.destroy(),W(Error("Connection timed out"))}),j.once("error",(z)=>{N("connection",`Failed to connect to ${$}:${w}: ${z}`,Y),j.destroy(),W(z)})});try{await U()}catch(B){let W=B;if(Date.now()-J>X){N("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return N("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),eY($,w,Y,A-1);if(A>0)try{N("connection",`Trying HTTP request to ${$}:${w}`,Y),await new Promise((z,G)=>{let K=YJ.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(F)=>{N("connection",`Received HTTP response with status: ${F.statusCode}`,Y),z()});K.on("error",(F)=>G(F)),K.on("timeout",()=>{K.destroy(),G(Error("HTTP request timed out"))}),K.end()}),N("connection",`HTTP request to ${$}:${w} succeeded`,Y);return}catch(z){return N("connection",`HTTP request to ${$}:${w} failed: ${z}`,Y),N("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((G)=>setTimeout(G,2000)),eY($,w,Y,A-1)}let j=`Failed to connect to ${$}:${w} after ${5-A} attempts: ${W.message}`;N("connection",`${j}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),R.warn(j),R.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function d6($){N("server",`Starting server with options: ${R$($)}`,$.verbose);let w=Rw($.from),Y=new URL(w.startsWith("http")?w:`http://${w}`),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(jj($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){N("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await oY(J,$.verbose))[0]){R.info(`Adding ${A.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await sY(J,$.verbose)}catch(W){if(R.error("Failed to add hosts entry:",W.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${A.hostname}`),R.warn(`::1 ${A.hostname}`),J0.platform==="win32")R.warn("On Windows:"),R.warn("1. Run notepad as administrator"),R.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else R.warn("On Unix systems:"),R.warn("sudo nano /etc/hosts")}}else N("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(B){R.error("Failed to check hosts file:",B.message)}}try{await eY(Y.hostname,X,$.verbose)}catch(B){N("server",`Connection test failed: ${B}`,$.verbose),R.error(B.message),R.warn("Continuing with proxy setup despite connection test failure..."),R.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=ZY({...$,to:A.hostname});if(U=await Yw({...$,to:A.hostname,https:$.https}),!U){if(N("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await m1({...$,from:Y.toString(),to:A.hostname,https:$.https}),U=await Yw({...$,to:A.hostname,https:$.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(B){throw N("server",`SSL setup failed: ${B}`,$.verbose),B}N("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await j4({...$,from:w,originalFrom:$.from||w,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function B4($,w,Y,A,X,J,U,B,W,j,z,G){N("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,U);let K=g1(z??A.host,G);d1(K);let F=[{host:w,route:{sourceHost:A.host,upstreamPool:K,cleanUrls:B||!1,changeOrigin:W||!1,basePath:"/",auth:j}}];if(!Bj({routeEntries:F,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw cw(K),Error(`Failed to start proxy server for ${w} on port ${Y}`);wJ.add(K),G4({from:$,to:w,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:B,verbose:U})}async function j4($){N("setup",`Setting up reverse proxy: ${R$($)}`,$.verbose);let{from:w,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:B,vitePluginUsage:W,changeOrigin:j,cleanUrls:z}=$,G=80,K=443,F="0.0.0.0",T=$.portManager||W4,q=jj($);try{if(q&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await oY([A],U))[0]){R.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await sY([A],U),R.success(`Added ${A} to your hosts file.`)}catch(V){R.error(`Failed to add ${A} to your hosts file: ${V}`),R.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(q&&J0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await oY([A],U))[0]){N("hosts",`${A} not found in hosts file, adding...`,U);try{await sY([A],U)}catch(V){N("hosts",`Failed to add ${A} to hosts file: ${V}`,U)}}}if(J&&!T.usedPorts.has(G)){if(!await Iw(G,F,U))N("setup","Starting HTTP redirect server",U),l6(U),T.usedPorts.add(G);else if(N("setup","Port 80 is in use, skipping HTTP redirect",U),U)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let E=J?K:G,f=await Iw(E,F,U),M;if(f){if(N("setup",`Port ${E} is already in use`,U),U)R.warn(`Port ${E} is already in use. This may be another instance of rpx or another service.`);if(E===443){if(M=await T.getNextAvailablePort(3443,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at https://${A}:${M}`)}else if(M=await T.getNextAvailablePort(E+1000,!0),N("setup",`Using port ${M} instead of ${E}`,U),U)R.info(`Using port ${M} instead. Access your site at http://${A}:${M}`)}else M=E,T.usedPorts.add(M),N("setup",`Using standard ${E===443?"HTTPS":"HTTP"} port ${E} for ${A}`,U);await B4(w,A,M,X,J,W,U,z,j,l1($.auth),Y,$.loadBalancer)}catch(E){N("setup",`Setup failed: ${E}`,U),R.error(`Failed to setup reverse proxy: ${E.message}`),AJ({domains:[A],hosts:typeof B==="boolean"?B:B?.hosts,certs:typeof B==="boolean"?B:B?.certs,verbose:U,vitePluginUsage:W})}}function l6($,w=80,Y=443,A){N("redirect",`Starting HTTP redirect server on port ${w}`,$);let X=YJ.createServer((J,U)=>{if(A&&J.url){let z=J.url.split("?",1)[0],G=uY(A,z);if(G!=null){N("redirect",`Serving ACME challenge ${z}`,$),U.writeHead(200,{"content-type":"text/plain"}),U.end(G);return}}let B=J.headers.host||"",W=B.includes(":")?B.slice(0,B.indexOf(":")):B,j=Y===443?W:`${W}:${Y}`;N("redirect",`Redirecting request from ${B}${J.url} to https://${j}`,$),U.writeHead(301,{Location:`https://${j}${J.url}`}),U.end()}).listen(w);$J.add(X),N("redirect","HTTP redirect server started",$)}function n6($){let w={...IW,...$};if(N("proxy",`Starting proxy with options: ${R$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}Yj({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((W)=>{R.error(`Failed to register with rpx daemon: ${W.message}`),J0.exit(1)});return}let Y=w.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=J0.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)&&w?.verbose)R.warn(`The .${A} TLD may not work reliably for local development`),R.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),R.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (wY(),c8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:w.verbose}).then((j)=>{if(j)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(A))R.success(`DNS server started for .${A} domains`);else R.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else N("dns",`Could not start DNS server - ${Y} may not resolve in browser`,w.verbose)})}).catch((W)=>{N("dns",`Failed to start DNS server: ${W}`,w.verbose)});let B={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:ZY(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};N("proxy",`Server options: ${R$(B)}`,w.verbose),d6(B).catch((W)=>{N("proxy",`Failed to start proxy: ${W}`,w.verbose),R.error(`Failed to start proxy: ${W.message}`),AJ({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function z4($){return $?.verbose||!1}function jj($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function p6($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let Y=z4(w),A=jj(w);if(N("config",`Starting with config: ${R$(w,2)}`,Y),N("config",`Is multi-proxy? ${"proxies"in w}`,Y),N("config",`Hosts management enabled? ${A}`,Y),w.viaDaemon){let I="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((O)=>({id:O.id,from:O.from,to:O.to,path:O.path,cleanUrls:O.cleanUrls??w.cleanUrls,changeOrigin:O.changeOrigin??w.changeOrigin,pathRewrites:O.pathRewrites})):[{id:w.id,from:w.from,to:w.to??"rpx.localhost",path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await Yj({proxies:I,verbose:Y});return}if("proxies"in w&&Array.isArray(w.proxies)){N("servers",`Found ${w.proxies.length} proxies in config`,Y);for(let H of w.proxies)if(H.start){let I=`${H.from}-${H.to}`;try{N("watch",`Starting command for ${I} with command: ${H.start.command}`,Y),R.info(`Starting command for ${I}...`),await e8.startProcess(I,H.start,Y);let O=Rw(H.from),Z=new URL(O.startsWith("http")?O:`http://${O}`),P0=Z.hostname||"localhost",Z$=Number(Z.port)||80;try{await eY(P0,Z$,Y),N("watch",`Dev server is ready at ${P0}:${Z$}`,Y)}catch(h$){N("watch",`Connection check failed, but continuing with proxy setup: ${h$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(O){throw N("watch",`Failed to start command for ${I}: ${O}`,Y),Error(`Failed to start command for ${I}: ${O}`)}}else N("watch",`No start command for proxy ${H.from} -> ${H.to}`,Y)}else if("start"in w&&w.start){N("watch","Found start command in single proxy config",Y);let H=`${w.from}-${w.to}`;try{if(w.start)N("watch",`Starting command: ${w.start.command}`,Y),await e8.startProcess(H,w.start,Y);let I=Rw(w.from),O=new URL(I.startsWith("http")?I:`http://${I}`),Z=O.hostname||"localhost",P0=Number(O.port)||80;try{await eY(Z,P0,Y),N("watch",`Dev server is ready at ${Z}:${P0}`,Y)}catch(Z$){N("watch",`Connection check failed, but continuing with proxy setup: ${Z$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(I){throw N("watch",`Failed to run start command: ${I}`,Y),Error(`Failed to run start command: ${I}`)}}else N("watch","No start command found in config",Y);let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(J0.platform!=="win32"&&(w.https||A)){if(!uw())try{N("sudo","Pre-acquiring sudo credentials for privileged operations",Y),J4("sudo -v",{stdio:"inherit"})}catch{N("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if(w.productionCerts){if(J=await a1(w.productionCerts,Y),J.length>0)N("ssl",`Using ${J.length} production SNI cert(s): ${J.map((H)=>H.serverName).join(", ")}`,Y)}if(w.https){let H=J.length>0?null:await Yw(w);if(!H&&J.length===0){if(N("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,w.verbose),await m1(w),H=await Yw(w),!H)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else N("ssl",`Using existing and trusted certificates for ${X}`,w.verbose);w._cachedSSLConfig=H}let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({...H,https:w.https,cleanup:w.cleanup,cleanUrls:H.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:H.changeOrigin??w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,auth:"auth"in w?w.auth:void 0,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig}],B=U.map((H)=>H.to||"rpx.localhost"),W=J.length>0?J:w._cachedSSLConfig??null,j=B.filter((H)=>H&&!H.includes("localhost")&&!H.includes("127.0.0.1")),z=["dev","app","page","new","day","foo"],G=["test","localhost","local","example","invalid"],K=[...new Set(j.map((H)=>H.split(".").pop()?.toLowerCase()))],F=K.filter((H)=>!!H&&z.includes(H));if(F.length>0&&Y)R.warn(`The following TLDs may not work reliably for local development: ${F.map((H)=>`.${H}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&J0.platform==="darwin"&&j.length>0){let{setupDevelopmentDns:H}=await Promise.resolve().then(() => (wY(),c8));if(await H({domains:j,verbose:Y})){if(Y)if(K.every((Z)=>!!Z&&G.includes(Z)))R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains`);else R.success(`DNS server started for ${K.map((Z)=>`.${Z}`).join(", ")} domains (hosts file entries also added)`)}else N("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{N("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:H}=await Promise.resolve().then(() => (wY(),c8));await H({verbose:w.verbose})}catch(H){N("cleanup",`Error stopping DNS server: ${H}`,w.verbose)}try{await e8.stopAll(w.verbose)}catch(H){N("cleanup",`Error stopping processes: ${H}`,w.verbose)}await AJ({domains:B,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};J0.on("SIGINT",T),J0.on("SIGTERM",T);let q=w.singlePortMode===!0,E=w.httpsPort??443,f=w.httpPort??80,M=w.originGuard?c6(w.originGuard):null,Q=!!W&&(U.length>1||q||J.length>0),V=!W&&q&&U.length>0;if(Q&&W){N("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${E}`,Y);let H=await i6(U,A,Y);if(!await Iw(f,"0.0.0.0",Y))l6(Y,f,E,w.acmeChallengeWebroot);if(await Iw(E,"0.0.0.0",Y)){if(N("proxies",`Port ${E} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${E} is in use. Shared HTTPS proxy cannot start.`);return}if(!Bj({routeEntries:H,listenPort:E,sslConfig:W,originGuard:M,verbose:Y})){R.error(`Shared HTTPS proxy failed to bind :${E}; not exiting`);return}}else if(V){N("proxies",`Creating shared HTTP server for ${U.length} domains on port ${f}`,Y);let H=await i6(U,A,Y);if(await Iw(f,"0.0.0.0",Y)){if(N("proxies",`Port ${f} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${f} is in use. Shared HTTP proxy cannot start.`);return}if(!Bj({routeEntries:H,listenPort:f,sslConfig:null,originGuard:M,verbose:Y})){R.error(`Shared HTTP proxy failed to bind :${f}; not exiting`);return}}else for(let H of U)try{let I=H.to||"rpx.localhost";N("proxy",`Starting proxy for ${I} with SSL config: ${!!W}`,H.verbose),await d6({from:H.from||"localhost:5173",to:I,cleanUrls:H.cleanUrls||!1,https:H.https||!1,cleanup:H.cleanup||!1,vitePluginUsage:H.vitePluginUsage||!1,verbose:H.verbose||!1,_cachedSSLConfig:w._cachedSSLConfig,changeOrigin:H.changeOrigin||!1,loadBalancer:H.loadBalancer,auth:H.auth,path:H.path,pathRewrites:H.pathRewrites})}catch(I){N("proxies",`Failed to start proxy for ${H.to}: ${I}`,H.verbose),R.error(`Failed to start proxy for ${H.to}:`,I)}}async function i6($,w,Y){let A=[],X=new Set;for(let J of $){let U=J.to||"rpx.localhost",B=J.cleanUrls||!1,W=J.path,j=Q$(W),z=l1(J.auth);if(J.redirect){let G=x5(J.redirect);A.push({host:U,path:W,route:{redirect:G,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → redirect ${G.status} ${G.to}${z?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:PY(J.static,B),cleanUrls:B,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${z?" (auth)":""}`,Y);else{let G=Rw(J.from),K=new URL(G.startsWith("http")?G:`http://${G}`),F=g1(J.from??K.host,J.loadBalancer);d1(F),wJ.add(F),A.push({host:U,path:W,route:{sourceHost:K.host,upstreamPool:F,cleanUrls:B,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:j,auth:z}}),N("proxies",`Route: ${U}${W??""} → ${K.host}${z?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),w&&!j1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await oY([U],Y))[0])await sY([U],Y)}catch{N("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function Bj($){let{routeEntries:w,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=$,U=r1(w),B=n1((z,G)=>t1(U,z,G),J),W=X?(z,G)=>X(z)??B(z,G):B,j=p1(J);try{let z=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:b1(),...A?{tls:Array.isArray(A)?A.map((G)=>({serverName:G.serverName,key:G.key,cert:G.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(G,K){return W(G,K)},websocket:j,error(G){return N("server",`Shared proxy server error: ${G}`,J),new Response(`Server Error: ${G.message}`,{status:500})}});return $J.add(z),N("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),z}catch(z){return N("proxies",`Failed to start shared proxy: ${z}`,J),console.error("Failed to start shared proxy:",z),null}}function G4($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${_$.green(_$.bold("rpx"))} ${_$.green(`v${U4}`)}`),console.log(` ${_$.green("➜")} ${_$.dim($?.from??"")} ${_$.dim("➜")} ${_$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${_$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${_$.green("➜")} Clean URLs enabled`)}WB();var VS=new bw("rpx",{showTags:!1});function r6($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}x0.chdir(F4(K4(N4(import.meta.url)),".."));var u0=new EJ("rpx"),t6="0.12.0";u0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async($)=>{if(!$?.from||!$.to)return p6(B1);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,singlePortMode:$.singlePortMode||!1,httpPort:$.httpPort!==void 0?Number($.httpPort):void 0,httpsPort:$.httpsPort!==void 0?Number($.httpsPort):void 0,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let Y={command:$.startCommand};if($.startCwd)Y.cwd=$.startCwd;if($.startEnv)try{Y.env=JSON.parse($.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),x0.exit(1)}w.start=Y}return n6(w)});u0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let Y=r6(B1)?B1.proxies.find((A)=>A.to===$||`${A.from}-${A.to}`===$):B1.to===$?B1:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${$}`),x0.exit(1);try{await n8.startProcess($,Y.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(A){console.error(`Failed to start dev server for ${$}:`,A),x0.exit(1)}});u0.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 ${$}`)}catch(Y){console.error(`Failed to stop dev server for ${$}:`,Y),x0.exit(1)}});u0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await n8.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),x0.exit(1)}});async function a6($){let Y={...(await s9().catch(()=>null))?.onDemand??{},enabled:!0};if($){let A=$.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}u0.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($)=>{try{let w=$.onDemand?await a6($.roots):void 0;await(await L6({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,onDemandSites:w,verbose:$.verbose??!0})).done,x0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),x0.exit(1)}});u0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,Y=await _6({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});u0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??w$(),Y=await Qw(w),A=await d8(w),X=$.registryDir,J=await wj(X).catch(()=>[]);if($.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:yw(w),rpxDir:w,registryDir:X??gw(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${yw(w)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${yw(w)}`);if(console.log(`registry: ${X??gw()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let B=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${B})`)}});u0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),x0.exit(1);if(!XY($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),x0.exit(1);try{await D6({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),x0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await O6({rpxDir:$.rpxDir,verbose:$.verbose}),Y=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${Y} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),x0.exit(1)}});u0.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(!XY($))console.error(`invalid id: ${JSON.stringify($)}`),x0.exit(1);let Y=await $j($,w.registryDir,w.verbose);if(!Y){console.log(`no registry entry for id=${$}`);return}await k6($,w.registryDir,w.verbose),console.log(`unregistered ${Y.to} (id=${$})`)});u0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??w$();if(await d8(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await S6({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});u0.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($)=>{let w=await a6($.roots),Y=Yz(w),A=await wj($.registryDir).catch(()=>[]),X=new Set(A.map((B)=>B.to)),J=Y.map((B)=>({host:B.host,dir:B.dir,command:B.command,source:B.source,live:X.has(B.host)}));if($.json){console.log(JSON.stringify(J,null,2));return}let U=w.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}) \u2014 scanned ${U.join(", ")}:`);for(let B of J)console.log(` ${B.live?"\u25CF":"\u25CB"} https://${B.host} ${B.live?"(live)":"(idle)"}`),console.log(` ${B.command} ${B.dir}`)});u0.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("fs/promises"),{join:A}=await import("path"),X=w.rpxDir??w$(),J=A(X,"sites",`${dA($.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${$} (it may not have been booted yet) \u2014 looked in ${J}`);return}let B=w.lines===void 0?void 0:typeof w.lines==="string"?Number.parseInt(w.lines,10):w.lines,W=U.split(`
319
319
  `);x0.stdout.write((B&&B>0?W.slice(-B):W).join(`
320
- `))});u0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(r6)});u0.version(r6);u0.help();u0.run();
320
+ `))});u0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(t6)});u0.version(t6);u0.help();u0.run();