@stacksjs/rpx 0.11.34 → 0.11.36

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,22 @@
1
1
  #!/usr/bin/env bun
2
- // @bun
3
- #!/usr/bin/env bun
4
- import{createRequire as q6}from"node:module";var G6=Object.defineProperty;var K6=(w)=>w;function F6(w,$){this[w]=K6.bind(null,$)}var fB=(w,$)=>{for(var Y in $)G6(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:F6.bind($,Y)})};var t=(w,$)=>()=>(w&&($=w(w=0)),$);var b=q6(import.meta.url);import{existsSync as DB,statSync as xB}from"fs";import{existsSync as HK,mkdirSync as L4,readdirSync as _4,readFileSync as RK,writeFileSync as S4}from"fs";import{homedir as $1}from"os";import{dirname as h4,resolve as Xw}from"path";import gA from"process";import{existsSync as PB,statSync as bB}from"fs";import{existsSync as pJ,mkdirSync as MK,readdirSync as IK,writeFileSync as VK}from"fs";import{homedir as Y1}from"os";import{dirname as uB,resolve as m0}from"path";import u$ from"process";import{join as CK,relative as yK,resolve as cB}from"path";import SA from"process";import{existsSync as Mj,mkdirSync as g4,readdirSync as d4,writeFileSync as l4}from"fs";import{homedir as OJ}from"os";import{dirname as r4,resolve as i0}from"path";import qY from"process";import{join as OK,relative as LK,resolve as vB}from"path";import ZA from"process";import{existsSync as Ij,mkdirSync as e4,readdirSync as wI,writeFileSync as $I}from"fs";import{dirname as AI,resolve as kA}from"path";import rJ from"process";import{Buffer as N$}from"buffer";import{createCipheriv as _K,createDecipheriv as SK,randomBytes as LJ}from"crypto";import{closeSync as _J,createReadStream as iB,createWriteStream as ZK,existsSync as SJ,fsyncSync as mB,openSync as gB,writeFileSync as kK}from"fs";import{access as hK,constants as dB,mkdir as DK,readdir as jA,rename as lB,stat as A1,unlink as zA,writeFile as ZJ}from"fs/promises";import{join as X1}from"path";import O0 from"process";import{pipeline as xK}from"stream/promises";import{createGzip as nB}from"zlib";import J1 from"process";import mw from"process";import{Buffer as vw}from"buffer";import{createCipheriv as PK,createDecipheriv as bK,randomBytes as kJ}from"crypto";import{closeSync as hJ,createReadStream as pB,createWriteStream as uK,existsSync as GA,fsyncSync as rB,openSync as tB,writeFileSync as cK}from"fs";import{access as vK,constants as aB,mkdir as iK,readdir as KA,rename as sB,stat as U1,unlink as FA,writeFile as DJ}from"fs/promises";import{isAbsolute as mK,join as Q1,resolve as gK}from"path";import h from"process";import{pipeline as dK}from"stream/promises";import{createGzip as oB}from"zlib";import W1 from"process";import gw from"process";import qA from"process";import{existsSync as NA}from"fs";import{resolve as xJ}from"path";import{existsSync as lK}from"fs";import{existsSync as nK,readdirSync as pK}from"fs";import{extname as PJ,resolve as eB}from"path";import rK from"process";import{join as tK,relative as aK,resolve as wj}from"path";import hA from"process";import{Buffer as iw}from"buffer";import{createCipheriv as sK,createDecipheriv as oK,randomBytes as bJ}from"crypto";import{closeSync as uJ,createReadStream as $j,createWriteStream as eK,existsSync as EA,fsyncSync as Yj,openSync as Aj,writeFileSync as w7}from"fs";import{access as $7,constants as Xj,mkdir as Y7,readdir as fA,rename as Jj,stat as B1,unlink as TA,writeFile as cJ}from"fs/promises";import{isAbsolute as A7,join as j1,resolve as X7}from"path";import D from"process";import{pipeline as J7}from"stream/promises";import{createGzip as Uj}from"zlib";import z1 from"process";import dw from"process";import RA from"process";import{existsSync as MA}from"fs";import{resolve as lJ}from"path";import{existsSync as CF}from"fs";class Hj{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!DB(w))return!0;return xB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=DB(Y)?xB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Rj{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function W7(w,$){this[w]=Q7.bind(null,$)}class UU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!PB(w))return!0;return bB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=PB(Y)?bB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class QU{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function z7(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function G7(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function K7(w){return w.getStats().size*2}function WU(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&w0($[0])&&"id"in $[0]&&$[0].id===3&&w0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(w0($)&&w0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(w0(w)&&"arr"in w&&Array.isArray(w.arr)&&w0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&w0($[0])&&w0(w[0])){let A=[...$];for(let X of w)if(w0(X)&&"name"in X){if(!A.find((U)=>w0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(w0(X)&&"path"in X){if(!A.find((U)=>w0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>DA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!w0($)||!w0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(w0(X)&&w0(Y[A]))Y[A]=WU(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((Q)=>w0(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(w0(U)&&"path"in U){if(!J.find((Q)=>w0(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>DA(W,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 DA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!DA(w[Y],$[Y]))return!1;return!0}if(w0(w)&&w0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!DA(w[X],$[X]))return!1}return!0}return!1}function w0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function F7(w,$){if(!Ij(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return WU($,A)}catch{return null}}catch{return null}}async function q7({name:w="",cwd:$,defaultConfig:Y}){let A=$||rJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let W of X){let Q=kA(A,`${U}${W}`),B=await F7(Q,Y);if(B!==null)return B}try{let U=kA(A,"package.json");if(Ij(U)){let Q=(await import(U))[w];if(Q&&typeof Q==="object"&&!Array.isArray(Q))try{return WU(Y,Q)}catch{}}}catch{}return Y}function N7(w,$={}){let Y=ZA.cwd();while(Y.includes("storage"))Y=vB(Y,"..");let A=vB(Y,w||"");if($?.relative)return LK(ZA.cwd(),A);return A}async function E7(){try{let w=await q7({name:"clarity",defaultConfig:CA,cwd:ZA.cwd(),endpoint:"",headers:{}});return{...CA,...w}}catch{return CA}}function Q0(){if(mw.env.NODE_ENV==="test"||mw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function f7(){if(mw.env.NODE_ENV==="test"||mw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof mw<"u"){let w=mw.type;if(w==="renderer"||w==="worker")return!1;return!!(mw.versions&&(mw.versions.node||mw.versions.bun))}return!1}class Cj{async format(w){let $=await f7(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:J1.pid,hostname:$(),environment:J1.env.NODE_ENV||"development",platform:J1.platform,version:J1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:J1.env.NODE_ENV||J1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...aJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Cj,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...yA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...yA};return{...yA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:aJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await hK(this.config.logDirectory,dB.F_OK|dB.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await DK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:N$.from(w);try{if(!SJ(this.currentLogFile))await ZJ(this.currentLogFile,"",{mode:420});if(X=gB(this.currentLogFile,"a",420),kK(X,Q,{flag:"a"}),mB(X),X!==void 0)_J(X),X=void 0;if((await A1(this.currentLogFile)).size===0){if(await ZJ(this.currentLogFile,Q,{flag:"w",mode:420}),(await A1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;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(X!==void 0)try{_J(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return X1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return X1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return X1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(Q0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return LJ(16).toString("hex")}generateKey(){return LJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=LJ(16),A=_K("aes-256-gcm",$,Y),X=N$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:N$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=nB(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(N$.from(N$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(Q0())return;let w=await A1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await jA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await A1(Y).catch(()=>null))try{if(await lB(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await zA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await ZJ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await A1(Y).catch(()=>null))await lB(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await jA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await zA(X1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=iB(w),A=ZK($),X=nB();await xK(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),SJ(this.currentLogFile))try{let w=gB(this.currentLogFile,"r+");mB(w),_J(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!Q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await jA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await zA(X1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?a.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=O0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${a.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!Q0()){let B=xj[w],j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z),W){let G=W.split(`
5
- `);for(let K of G)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:a.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!Q0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let Q=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
6
- `;if(W)Q+=`${W}
7
- `;Q=Q.replace(this.ANSI_PATTERN,""),await this.writeToFile(Q)}time(w){let $=performance.now();if(this.fancy&&!Q0()){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(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
8
- `,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!Q0()){let j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:a.green(""),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!Q0())console.error(B.trim());await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new xA($,{...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(!SJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return iB(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=N$.isBuffer(w)?w:N$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),W=SK("aes-256-gcm",Y,X);return W.setAuthTag(J),N$.concat([W.update(U),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return Q0()}isServerMode(){return!Q0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!Q0()){let J=w.split(`
9
- `),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,Q=`└${"─".repeat(U)}┘`,B=J.map((j)=>{let z=" ".repeat(U-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:a.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(Q),showTimestamp:!1}))}else if(!Q0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
10
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(Q0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${a.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();O0.stdin.removeListener("data",Y);try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!1)}catch{}O0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!0)}catch{}O0.stdin.resume(),O0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,W=0;if(Y=w.replace(U,(Q,B)=>{if(B==="%")return"%";if(W>=$.length)return Q;let j=$[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return Q}}),W<$.length)Y+=` ${$.slice(W).map((Q)=>typeof Q==="object"?JSON.stringify(Q,null,2):String(Q)).join(" ")}`}if(this.fancy&&!Q0()){let U=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",W=a.blue("◐");console.error(`${W} ${U} ${a.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
11
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||Q0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),W!==void 0)this.activeProgressBar.message=W;let Q=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Q)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())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,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;O0.stdout.write(`${"\r".padEnd(O0.stdout.columns||80)}\r`),this.log(W,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||Q0()||!O0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=a.green("━".repeat(A)),U=a.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=$||Y===100?a.green("✓"):a.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=O0.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,O0.stdout.write(w.lastRenderedLine),$)O0.stdout.write(`
12
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||Q0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(Q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await jA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=X1(this.config.logDirectory,A);if(w.before)try{if((await A1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await 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($){console.error("Error during log clearing process:",$)}}}function VA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&d($[0])&&"id"in $[0]&&$[0].id===3&&d($[1])&&"id"in $[1]&&$[1].id===4)return $;if(d($)&&d(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(d(w)&&"arr"in w&&Array.isArray(w.arr)&&d($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&d($[0])&&d(w[0])){let A=[...$];for(let X of w)if(d(X)&&"name"in X){if(!A.find((U)=>d(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(d(X)&&"path"in X){if(!A.find((U)=>d(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>PA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!d($)||!d(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(d(X)&&d(Y[A]))Y[A]=VA(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((Q)=>d(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(d(U)&&"path"in U){if(!J.find((Q)=>d(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>PA(W,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 BU(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:VA(w,$);if(Array.isArray(w))return Y==="replace"?$:VA(w,$);if(!d($)||!d(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=VA(U,J);else if(d(J)&&d(U))A[X]=BU(U,J,Y);else A[X]=J}return A}function PA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!PA(w[Y],$[Y]))return!1;return!0}if(d(w)&&d($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!PA(w[X],$[X]))return!1}return!0}return!1}function d(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function HA(w,$,Y="replace"){if(!Mj(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return BU($,X,Y)}catch{return null}}catch{return null}}function T7(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${z.map(G).join("_")}`,E=`${A}_${z.map((q)=>q.toUpperCase()).join("_")}`;if(Y)_0.info(`Checking environment variable ${K} for config ${w}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))Q[B]=J(j,z);else{let q=qY.env[K]||qY.env[E];if(q!==void 0){if(Y)_0.info(`Using environment variable ${q?K:E} for config ${w}.${z.join(".")}`);if(typeof j==="number")Q[B]=Number(q);else if(typeof j==="boolean")Q[B]=q.toLowerCase()==="true";else if(Array.isArray(j))try{let N=JSON.parse(q);if(Array.isArray(N))Q[B]=N;else Q[B]=q.split(",").map((f)=>f.trim())}catch{Q[B]=q.split(",").map((N)=>N.trim())}else Q[B]=q}}}return Q}return J(X)}async function H7({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let Q=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?T7(w,X,J):X,B=Y||qY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)_0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${B}`);let z=[w,`.${w}`].filter(Boolean),G=[`${w}.config`,`.${w}.config`].filter(Boolean),K=$?[$,`.${$}`]:[],E=$?[`${$}.config`,`.${$}.config`]:[],q=Array.from(new Set([B,i0(B,"config"),i0(B,".config"),A?i0(B,A):void 0].filter(Boolean)));for(let N of q){if(J)_0.info(`Searching for configuration in: ${N}`);let R=[i0(B,"config"),i0(B,".config")].concat(A?[i0(B,A)]:[]).includes(N)?[...z,...G,...K,...E]:[...G,...z,...E,...K];for(let O of R)for(let y of j){let T=i0(N,`${O}${y}`),M=await HA(T,Q,W);if(M!==null){if(J)_0.success(`Configuration loaded from: ${T}`);return M}}}if(w){let N=i0(OJ(),".config",w),f=["config",`${w}.config`];if($)f.push(`${$}.config`);if(J)_0.info(`Checking user config directory: ${N}`);for(let R of f)for(let O of j){let y=i0(N,`${R}${O}`),T=await HA(y,Q,W);if(T!==null){if(J)_0.success(`Configuration loaded from user config directory: ${y}`);return T}}}if(w){let N=i0(OJ(),".config"),f=[`.${w}.config`];if($)f.push(`.${$}.config`);if(J)_0.info(`Checking user config directory for dotfile configs: ${N}`);for(let R of f)for(let O of j){let y=i0(N,`${R}${O}`),T=await HA(y,Q,W);if(T!==null){if(J)_0.success(`Configuration loaded from user config directory dotfile: ${y}`);return T}}}if(w){let N=OJ(),f=[`.${w}.config`,`.${w}`];if($)f.push(`.${$}.config`),f.push(`.${$}`);if(J)_0.info(`Checking user home directory for dotfile configs: ${N}`);for(let R of f)for(let O of j){let y=i0(N,`${R}${O}`),T=await HA(y,Q,W);if(T!==null){if(J)_0.success(`Configuration loaded from user home directory: ${y}`);return T}}}try{let N=i0(B,"package.json");if(Mj(N)){let f=await import(N),R=f[w];if(!R&&$){if(R=f[$],R&&J)_0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)_0.success(`Configuration loaded from package.json: ${R===f[w]?w:$}`);return BU(Q,R,W)}catch(O){if(J)_0.warn("Failed to merge package.json config:",O)}}}catch(N){if(J)_0.warn("Failed to load package.json:",N)}if(J)_0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return Q}function R7(w,$={}){let Y=SA.cwd();while(Y.includes("storage"))Y=cB(Y,"..");let A=cB(Y,w||"");if($?.relative)return yK(SA.cwd(),A);return A}async function M7(){try{let w=await H7({name:"clarity",alias:"logging",defaultConfig:OA,cwd:SA.cwd()});return{...OA,...w||{}}}catch{return OA}}function F0(){if(gw.env.NODE_ENV==="test"||gw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function I7(){if(gw.env.NODE_ENV==="test"||gw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof gw<"u"){let w=gw.type;if(w==="renderer"||w==="worker")return!1;return!!(gw.versions&&(gw.versions.node||gw.versions.bun))}return!1}class yj{async format(w){let $=await I7(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:W1.pid,hostname:$(),environment:W1.env.NODE_ENV||"development",platform:W1.platform,version:W1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:W1.env.NODE_ENV||W1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class bA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...sJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new yj,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??h.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...LA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...LA};return{...LA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:sJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await vK(this.config.logDirectory,aB.F_OK|aB.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await iK(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:vw.from(w);try{if(!GA(this.currentLogFile))await DJ(this.currentLogFile,"",{mode:420});if(X=tB(this.currentLogFile,"a",420),cK(X,Q,{flag:"a"}),rB(X),X!==void 0)hJ(X),X=void 0;if((await U1(this.currentLogFile)).size===0){if(await DJ(this.currentLogFile,Q,{flag:"w",mode:420}),(await U1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;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(X!==void 0)try{hJ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();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 Q1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return Q1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return Q1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return kJ(16).toString("hex")}generateKey(){return kJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=kJ(16),A=PK("aes-256-gcm",$,Y),X=vw.isBuffer(w)?w:vw.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=vw.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=oB(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(vw.from(vw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(F0())return;if(!this.shouldWriteToFile())return;let w=await U1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await KA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await U1(Y).catch(()=>null))try{if(await sB(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await FA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await DJ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await U1(Y).catch(()=>null))await sB(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await KA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await FA(Q1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=pB(w),A=uK($),X=oB();await dK(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),GA(this.currentLogFile))try{let w=tB(this.currentLogFile,"r+");rB(w),hJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await KA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await FA(Q1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?u.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let w=typeof h.env.NO_COLOR<"u",$=h.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof h.stderr<"u"&&h.stderr.isTTY||typeof h.stdout<"u"&&h.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=h.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${u.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),$}supportsHyperlinks(){if(F0())return!1;let w=h.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=h.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(mK($)||$.startsWith("./")||$.startsWith("../"))$=gK($);else return null;return GA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":Pj[w],G=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:u.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:u.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
13
- `);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:u.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!F0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
14
- `;if(W)j+=`${W}
15
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(W,Q)=>{},finish:(W)=>{},interrupt:(W,Q)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!F0()&&h.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!F0()&&h.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Q="info")=>{if(!F0()&&h.stdout.isTTY)h.stdout.write(`
16
- `);if(this[Q==="warning"?"warn":Q](W),this.activeProgressBar&&this.shouldStyleConsole()&&!F0()&&h.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:Y,message:`${u.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
17
- `,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":u.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!F0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new bA($,{...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(!GA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return pB(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=vw.isBuffer(w)?w:vw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=bK("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=vw.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F0()}isServerMode(){return!F0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
18
- `),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(j),showTimestamp:!1}))}else if(!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(w){if(F0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${u.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();h.stdin.removeListener("data",Y);try{if(typeof h.stdin.setRawMode==="function")h.stdin.setRawMode(!1)}catch{}h.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof h.stdin.setRawMode==="function")h.stdin.setRawMode(!0)}catch{}h.stdin.resume(),h.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let Q=/%([sdijfo%])/g,B=0;if(Y=w.replace(Q,(j,z)=>{if(z==="%")return"%";if(B>=$.length)return j;let G=$[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<$.length)Y+=` ${$.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${u.blue("")} `;console.error(`${B}${Q} ${u.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
20
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!h.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?u.green("✓"):u.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=h.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,h.stdout.write(w.lastRenderedLine),$)h.stdout.write(`
21
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||F0()||!h.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(F0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await KA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=Q1(this.config.logDirectory,A);if(w.before)try{if((await U1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await FA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function Oj(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function Lj(w){return w instanceof o0}function V7(w){return w instanceof uA}function C7(w){if(Lj(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class dA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return fY.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=qA.env[Q]||(B?qA.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=qA.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof cA)throw z;throw E$.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw E$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(qA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
2
+ import{createRequire as gG}from"node:module";var vG=Object.defineProperty;var cG=(w)=>w;function mG(w,$){this[w]=cG.bind(null,$)}var rQ=(w,$)=>{for(var Y in $)vG(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:mG.bind($,Y)})};var a=(w,$)=>()=>(w&&($=w(w=0)),$);var i=gG(import.meta.url);import{existsSync as Bj,statSync as fj}from"fs";import{existsSync as r5,mkdirSync as _M,readdirSync as DM,readFileSync as t5,writeFileSync as kM}from"fs";import{homedir as t$}from"os";import{dirname as PM,resolve as Aw}from"path";import _A from"process";import{existsSync as zj,statSync as Gj}from"fs";import{existsSync as _J,mkdirSync as a5,readdirSync as s5,writeFileSync as o5}from"fs";import{homedir as a$}from"os";import{dirname as Ej,resolve as c0}from"path";import _$ from"process";import{join as e5,relative as w6,resolve as Kj}from"path";import qA from"process";import{existsSync as oj,mkdirSync as lM,readdirSync as pM,writeFileSync as rM}from"fs";import{homedir as fJ}from"os";import{dirname as sM,resolve as v0}from"path";import s1 from"process";import{join as $6,relative as Y6,resolve as Fj}from"path";import NA from"process";import{existsSync as ej,mkdirSync as Yy,readdirSync as Ay,writeFileSync as Xy}from"fs";import{dirname as Uy,resolve as HA}from"path";import DJ from"process";import{Buffer as j$}from"buffer";import{createCipheriv as A6,createDecipheriv as X6,randomBytes as zJ}from"crypto";import{closeSync as GJ,createReadStream as Tj,createWriteStream as J6,existsSync as EJ,fsyncSync as qj,openSync as Nj,writeFileSync as U6}from"fs";import{access as W6,constants as Hj,mkdir as Q6,readdir as oY,rename as Rj,stat as s$,unlink as eY,writeFile as KJ}from"fs/promises";import{join as o$}from"path";import L0 from"process";import{pipeline as j6}from"stream/promises";import{createGzip as Mj}from"zlib";import e$ from"process";import bw from"process";import{Buffer as Pw}from"buffer";import{createCipheriv as B6,createDecipheriv as f6,randomBytes as FJ}from"crypto";import{closeSync as TJ,createReadStream as yj,createWriteStream as z6,existsSync as wA,fsyncSync as Ij,openSync as Cj,writeFileSync as G6}from"fs";import{access as E6,constants as Vj,mkdir as K6,readdir as $A,rename as Lj,stat as w1,unlink as YA,writeFile as qJ}from"fs/promises";import{isAbsolute as F6,join as $1,resolve as T6}from"path";import k from"process";import{pipeline as q6}from"stream/promises";import{createGzip as Sj}from"zlib";import Y1 from"process";import uw from"process";import AA from"process";import{existsSync as XA}from"fs";import{resolve as NJ}from"path";import{existsSync as N6}from"fs";import{existsSync as H6,readdirSync as R6}from"fs";import{extname as HJ,resolve as Oj}from"path";import M6 from"process";import{join as y6,relative as I6,resolve as hj}from"path";import RA from"process";import{Buffer as iw}from"buffer";import{createCipheriv as C6,createDecipheriv as V6,randomBytes as RJ}from"crypto";import{closeSync as MJ,createReadStream as _j,createWriteStream as L6,existsSync as JA,fsyncSync as Dj,openSync as kj,writeFileSync as S6}from"fs";import{access as O6,constants as Zj,mkdir as h6,readdir as UA,rename as xj,stat as A1,unlink as WA,writeFile as yJ}from"fs/promises";import{isAbsolute as _6,join as X1,resolve as D6}from"path";import Z from"process";import{pipeline as k6}from"stream/promises";import{createGzip as Pj}from"zlib";import J1 from"process";import vw from"process";import jA from"process";import{existsSync as BA}from"fs";import{resolve as OJ}from"path";import{existsSync as eE}from"fs";class aj{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!Bj(w))return!0;return fj(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=Bj(Y)?fj(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class sj{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function P6(w,$){this[w]=x6.bind(null,$)}class dJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!zj(w))return!0;return Gj(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=zj(Y)?Gj(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class nJ{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function u6(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function v6(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function c6(w){return w.getStats().size*2}function lJ(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&$0($[0])&&"id"in $[0]&&$[0].id===3&&$0($[1])&&"id"in $[1]&&$[1].id===4)return $;if($0($)&&$0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if($0(w)&&"arr"in w&&Array.isArray(w.arr)&&$0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&$0($[0])&&$0(w[0])){let A=[...$];for(let X of w)if($0(X)&&"name"in X){if(!A.find((U)=>$0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if($0(X)&&"path"in X){if(!A.find((U)=>$0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>MA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!$0($)||!$0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if($0(X)&&$0(Y[A]))Y[A]=lJ(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((Q)=>MA(Q,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 MA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!MA(w[Y],$[Y]))return!1;return!0}if($0(w)&&$0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!MA(w[X],$[X]))return!1}return!0}return!1}function $0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function m6(w,$){if(!ej(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return lJ($,A)}catch{return null}}catch{return null}}async function g6({name:w="",cwd:$,defaultConfig:Y}){let A=$||DJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let Q of X){let W=HA(A,`${U}${Q}`),j=await m6(W,Y);if(j!==null)return j}try{let U=HA(A,"package.json");if(ej(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return lJ(Y,W)}catch{}}}catch{}return Y}function d6(w,$={}){let Y=NA.cwd();while(Y.includes("storage"))Y=Fj(Y,"..");let A=Fj(Y,w||"");if($?.relative)return Y6(NA.cwd(),A);return A}async function n6(){try{let w=await g6({name:"clarity",defaultConfig:GA,cwd:NA.cwd(),endpoint:"",headers:{}});return{...GA,...w}}catch{return GA}}function U0(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function l6(){if(bw.env.NODE_ENV==="test"||bw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof bw<"u"){let w=bw.type;if(w==="renderer"||w==="worker")return!1;return!!(bw.versions&&(bw.versions.node||bw.versions.bun))}return!1}class $B{async format(w){let $=await l6(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:e$.pid,hostname:$(),environment:e$.env.NODE_ENV||"development",platform:e$.platform,version:e$.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:e$.env.NODE_ENV||e$.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...ZJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new $B,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??L0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...EA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...EA};return{...EA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:ZJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,Q=1000;while(J<U)try{try{try{await W6(this.config.logDirectory,Hj.F_OK|Hj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await Q6(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(w)).encrypted:j$.from(w);try{if(!EJ(this.currentLogFile))await KJ(this.currentLogFile,"",{mode:420});if(X=Nj(this.currentLogFile,"a",420),U6(X,W,{flag:"a"}),qj(X),X!==void 0)GJ(X),X=void 0;if((await s$(this.currentLogFile)).size===0){if(await KJ(this.currentLogFile,W,{flag:"w",mode:420}),(await s$(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let B=j;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(J<U-1){let f=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let z=Q*2**J;await new Promise((G)=>setTimeout(G,z)),J++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(X!==void 0)try{GJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let B=W,f=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let j=Q*2**(J-1);await new Promise((B)=>setTimeout(B,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 o$(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return o$(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return o$(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,W])=>W.createdAt.getTime()-Q.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[Q]of X.slice(U))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return zJ(16).toString("hex")}generateKey(){return zJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=zJ(16),A=A6("aes-256-gcm",$,Y),X=j$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:j$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Mj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(j$.from(j$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(U0())return;let w=await s$(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await oY(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let B=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${U}`;if(await s$(Y).catch(()=>null))try{if(await Rj(Y,Q),$.compress)try{let W=`${Q}.gz`;await this.compressLogFile(Q,W),await eY(Q)}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 KJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await s$(Y).catch(()=>null))await Rj(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await oY(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Q)=>Q.localeCompare(U));for(let U of J.slice($.maxFiles))await eY(o$(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=Tj(w),A=J6($),X=Mj();await j6(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),EJ(this.currentLogFile))try{let w=Nj(this.currentLogFile,"r+");qj(w),GJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await oY(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await eY(o$(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?s.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,Q=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=L0.stdout.columns||120,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 B=Q(j).trim().length,f=Q($).length,z=Math.max(1,W-2-B-f);return`${j.trim()}${" ".repeat(z)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let Q=Number.parseInt(U,10);return Q<$[0].length?String($[0][Q]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let Q=$[A++];switch(U){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,Q;if($ instanceof Error)U=$.message,Q=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!U0()){let j=fB[w],B=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",f;switch(w){case"debug":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:s.gray(U),level:w}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:U,level:w}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:s.green(U),level:w}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:U,level:w}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:U,level:w}),console.error(f),Q){let z=Q.split(`
3
+ `);for(let G of z)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:s.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),Q)console.error(Q)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
4
+ `;if(Q)W+=`${Q}
5
+ `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!U0()){let Y=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:s.blue("◐"),tag:Y,message:`${s.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,Q=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
6
+ `,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let B=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:s.green("✓"),tag:B,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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new yA($,{...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(!EJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Tj(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=j$.isBuffer(w)?w:j$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),Q=X6("aes-256-gcm",Y,X);return Q.setAuthTag(J),j$.concat([Q.update(U),Q.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U0()}isServerMode(){return!U0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!U0()){let J=w.split(`
7
+ `),U=Math.max(...J.map((B)=>B.length))+2,Q=`┌${"".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,j=J.map((B)=>{let f=" ".repeat(U-B.length-2);return`│ ${B}${f} │`});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(Q)})),j.forEach((B)=>console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(B),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(W),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
8
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(U0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${s.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();L0.stdin.removeListener("data",Y);try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!1)}catch{}L0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof L0.stdin.setRawMode==="function")L0.stdin.setRawMode(!0)}catch{}L0.stdin.resume(),L0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,Q=0;if(Y=w.replace(U,(W,j)=>{if(j==="%")return"%";if(Q>=$.length)return W;let B=$[Q++];switch(j){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 W}}),Q<$.length)Y+=` ${$.slice(Q).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!U0()){let U=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",Q=s.blue("◐");console.error(`${Q} ${U} ${s.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
9
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||U0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,Q)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),Q!==void 0)this.activeProgressBar.message=Q;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,Q="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;L0.stdout.write(`${"\r".padEnd(L0.stdout.columns||80)}\r`),this.log(Q,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=s.green("━".repeat(A)),U=s.gray("━".repeat(X)),Q=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=w.message?` ${w.message}`:"",B=$||Y===100?s.green("✓"):s.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${s.gray(this.formatTag(this.name))}`:"",z=`\r${B}${f} ${Q} ${W}${j}`,G=L0.stdout.columns||80,T=" ".repeat(Math.max(0,G-z.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${z}${T}`,L0.stdout.write(w.lastRenderedLine),$)L0.stdout.write(`
10
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||U0()||!L0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await oY(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=o$(this.config.logDirectory,A);if(w.before)try{if((await s$(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await eY(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function zA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&d($[0])&&"id"in $[0]&&$[0].id===3&&d($[1])&&"id"in $[1]&&$[1].id===4)return $;if(d($)&&d(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(d(w)&&"arr"in w&&Array.isArray(w.arr)&&d($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&d($[0])&&d(w[0])){let A=[...$];for(let X of w)if(d(X)&&"name"in X){if(!A.find((U)=>d(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(d(X)&&"path"in X){if(!A.find((U)=>d(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>IA(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!d($)||!d(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(d(X)&&d(Y[A]))Y[A]=zA(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((Q)=>IA(Q,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 pJ(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:zA(w,$);if(Array.isArray(w))return Y==="replace"?$:zA(w,$);if(!d($)||!d(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=zA(U,J);else if(d(J)&&d(U))A[X]=pJ(U,J,Y);else A[X]=J}return A}function IA(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!IA(w[Y],$[Y]))return!1;return!0}if(d(w)&&d($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!IA(w[X],$[X]))return!1}return!0}return!1}function d(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function QA(w,$,Y="replace"){if(!oj(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return pJ($,X,Y)}catch{return null}}catch{return null}}function p6(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,Q=[]){let W={...U};for(let[j,B]of Object.entries(U)){let f=[...Q,j],z=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${f.map(z).join("_")}`,T=`${A}_${f.map((K)=>K.toUpperCase()).join("_")}`;if(Y)O0.info(`Checking environment variable ${G} for config ${w}.${f.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))W[j]=J(B,f);else{let K=s1.env[G]||s1.env[T];if(K!==void 0){if(Y)O0.info(`Using environment variable ${K?G:T} for config ${w}.${f.join(".")}`);if(typeof B==="number")W[j]=Number(K);else if(typeof B==="boolean")W[j]=K.toLowerCase()==="true";else if(Array.isArray(B))try{let F=JSON.parse(K);if(Array.isArray(F))W[j]=F;else W[j]=K.split(",").map((q)=>q.trim())}catch{W[j]=K.split(",").map((F)=>F.trim())}else W[j]=K}}}return W}return J(X)}async function r6({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:Q="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?p6(w,X,J):X,j=Y||s1.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(J)O0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${j}`);let f=[w,`.${w}`].filter(Boolean),z=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([j,v0(j,"config"),v0(j,".config"),A?v0(j,A):void 0].filter(Boolean)));for(let F of K){if(J)O0.info(`Searching for configuration in: ${F}`);let R=[v0(j,"config"),v0(j,".config")].concat(A?[v0(j,A)]:[]).includes(F)?[...f,...z,...G,...T]:[...z,...f,...T,...G];for(let L of R)for(let V of B){let N=v0(F,`${L}${V}`),M=await QA(N,W,Q);if(M!==null){if(J)O0.success(`Configuration loaded from: ${N}`);return M}}}if(w){let F=v0(fJ(),".config",w),q=["config",`${w}.config`];if($)q.push(`${$}.config`);if(J)O0.info(`Checking user config directory: ${F}`);for(let R of q)for(let L of B){let V=v0(F,`${R}${L}`),N=await QA(V,W,Q);if(N!==null){if(J)O0.success(`Configuration loaded from user config directory: ${V}`);return N}}}if(w){let F=v0(fJ(),".config"),q=[`.${w}.config`];if($)q.push(`.${$}.config`);if(J)O0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of q)for(let L of B){let V=v0(F,`${R}${L}`),N=await QA(V,W,Q);if(N!==null){if(J)O0.success(`Configuration loaded from user config directory dotfile: ${V}`);return N}}}if(w){let F=fJ(),q=[`.${w}.config`,`.${w}`];if($)q.push(`.${$}.config`),q.push(`.${$}`);if(J)O0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of q)for(let L of B){let V=v0(F,`${R}${L}`),N=await QA(V,W,Q);if(N!==null){if(J)O0.success(`Configuration loaded from user home directory: ${V}`);return N}}}try{let F=v0(j,"package.json");if(oj(F)){let q=await import(F),R=q[w];if(!R&&$){if(R=q[$],R&&J)O0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)O0.success(`Configuration loaded from package.json: ${R===q[w]?w:$}`);return pJ(W,R,Q)}catch(L){if(J)O0.warn("Failed to merge package.json config:",L)}}}catch(F){if(J)O0.warn("Failed to load package.json:",F)}if(J)O0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function t6(w,$={}){let Y=qA.cwd();while(Y.includes("storage"))Y=Kj(Y,"..");let A=Kj(Y,w||"");if($?.relative)return w6(qA.cwd(),A);return A}async function a6(){try{let w=await r6({name:"clarity",alias:"logging",defaultConfig:KA,cwd:qA.cwd()});return{...KA,...w||{}}}catch{return KA}}function E0(){if(uw.env.NODE_ENV==="test"||uw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function s6(){if(uw.env.NODE_ENV==="test"||uw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof uw<"u"){let w=uw.type;if(w==="renderer"||w==="worker")return!1;return!!(uw.versions&&(uw.versions.node||uw.versions.bun))}return!1}class YB{async format(w){let $=await s6(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:Y1.pid,hostname:$(),environment:Y1.env.NODE_ENV||"development",platform:Y1.platform,version:Y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Y1.env.NODE_ENV||Y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class CA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...xJ},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new YB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...FA,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...FA};return{...FA,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:xJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,Q=1000;while(J<U)try{try{try{await E6(this.config.logDirectory,Vj.F_OK|Vj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await K6(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(w)).encrypted:Pw.from(w);try{if(!wA(this.currentLogFile))await qJ(this.currentLogFile,"",{mode:420});if(X=Cj(this.currentLogFile,"a",420),G6(X,W,{flag:"a"}),Ij(X),X!==void 0)TJ(X),X=void 0;if((await w1(this.currentLogFile)).size===0){if(await qJ(this.currentLogFile,W,{flag:"w",mode:420}),(await w1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let B=j;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(J<U-1){let f=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let z=Q*2**J;await new Promise((G)=>setTimeout(G,z)),J++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(X!==void 0)try{TJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let B=W,f=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let j=Q*2**(J-1);await new Promise((B)=>setTimeout(B,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 w=new Date().toISOString().split("T")[0];return $1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,W])=>W.createdAt.getTime()-Q.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[Q]of X.slice(U))this.encryptionKeys.delete(Q),this.keys.delete(Q)}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 w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=FJ(16),A=B6("aes-256-gcm",$,Y),X=Pw.isBuffer(w)?w:Pw.from(w,"utf8"),J=A.update(X),U=A.final(),Q=J.length+U.length,W=A.getAuthTag(),j=Pw.allocUnsafe(16+Q+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+Q),{encrypted:j,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Sj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(Pw.from(Pw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let w=await w1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await $A(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let B=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${U}`;if(await w1(Y).catch(()=>null))try{if(await Lj(Y,Q),$.compress)try{let W=`${Q}.gz`;await this.compressLogFile(Q,W),await YA(Q)}catch(W){console.error("Error compressing rotated file:",W)}if(J.length===0&&!X.some((W)=>W.endsWith(".log.1")))try{let W=`${Y}.1`;await qJ(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await w1(Y).catch(()=>null))await Lj(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await $A(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Q)=>Q.localeCompare(U));for(let U of J.slice($.maxFiles))await YA($1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=yj(w),A=z6($),X=Sj();await q6(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),wA(this.currentLogFile))try{let w=Cj(this.currentLogFile,"r+");Ij(w),TJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await $A(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await YA($1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?b.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let w=typeof k.env.NO_COLOR<"u",$=k.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,Q=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=k.stdout.columns||120,j="";if(J==="warning"||J==="error")j=`${Y} ${X}`;else if(J==="info"||J==="success")j=`${Y} ${A} ${X}`;else j=`${Y} ${A} ${b.cyan(X)}`;if(!U)return j.trim();let B=Q(j).trim().length,f=Q($).length,z=Math.max(1,W-2-B-f);return`${j.trim()}${" ".repeat(z)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let Q=Number.parseInt(U,10);return Q<$[0].length?String($[0][Q]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let Q=$[A++];switch(U){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=b.underline(b.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Q=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${Q}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>b.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>b.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>b.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>b.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>b.strikethrough(A)),$}supportsHyperlinks(){if(E0())return!1;let w=k.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=k.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(F6($)||$.startsWith("./")||$.startsWith("../"))$=T6($);else return null;return wA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,Q;if($ instanceof Error)U=$.message,Q=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":zB[w],z=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:b.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:b.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.error(G),Q){let T=Q.split(`
11
+ `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:b.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!E0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),Q)console.error(Q)}if(!this.shouldLog(w))return;let B=`${J} ${this.environment}.${w.toUpperCase()}: ${j}
12
+ `;if(Q)B+=`${Q}
13
+ `;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress(w,$=""){let Y={update:(Q,W)=>{},finish:(Q)=>{},interrupt:(Q,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!E0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Q,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Q),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!E0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Q)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Q)},interrupt:(Q,W="info")=>{if(!E0()&&k.stdout.isTTY)k.stdout.write(`
14
+ `);if(this[W==="warning"?"warn":W](Q),this.activeProgressBar&&this.shouldStyleConsole()&&!E0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":b.blue("◐"),tag:Y,message:`${b.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,Q=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
15
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:this.options.showIcons===!1?"":b.green("✓"),tag:B,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E0())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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new CA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(E0())throw Error("createReadStream is not supported in browser environments");if(!wA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return yj(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Pw.isBuffer(w)?w:Pw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),Q=f6("aes-256-gcm",Y,X);Q.setAuthTag(J);let W=Q.update(U),j=Q.final(),B=W.length+j.length,f=Pw.allocUnsafe(B);return W.copy(f,0),j.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return E0()}isServerMode(){return!E0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let Q=X.split(`
16
+ `),W=Math.max(...Q.map((z)=>z.length))+2,j=`┌${"─".repeat(W)}┐`,B=`└${"─".repeat(W)}┘`,f=Q.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:b.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(j),showTimestamp:!1})),f.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(B),showTimestamp:!1}))}else if(!E0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
17
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(E0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${b.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();k.stdin.removeListener("data",Y);try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!1)}catch{}k.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!0)}catch{}k.stdin.resume(),k.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=w.replace(W,(B,f)=>{if(f==="%")return"%";if(j>=$.length)return B;let z=$[j++];switch(f){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 B}}),j<$.length)Y+=` ${$.slice(j).map((B)=>typeof B==="object"?JSON.stringify(B,null,2):String(B)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${j}${W} ${b.cyan(A)}`)}let Q=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
18
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!k.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=b.green("━".repeat(A)),U=b.gray("━".repeat(X)),Q=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=w.message?` ${w.message}`:"",B=this.options.showIcons===!1?"":$||Y===100?b.green("✓"):b.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",z=`\r${B}${f} ${Q} ${W}${j}`,G=k.stdout.columns||80,T=" ".repeat(Math.max(0,G-z.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${z}${T}`,k.stdout.write(w.lastRenderedLine),$)k.stdout.write(`
19
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||E0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(E0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await $A(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=$1(this.config.logDirectory,A);if(w.before)try{if((await w1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await YA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function AB(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let Q=0;Q<=Y;Q++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),Q===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 XB(w){return w instanceof a0}function o6(w){return w instanceof VA}function e6(w){if(XB(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class DA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:Q=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let B=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],B,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:Q,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return wY.track("applyEnvironmentVariables",j,{configName:w});return j()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=U.map((B)=>this.formatEnvKey(B,A.useCamelCase)),W=`${Y}_${Q.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((B)=>B.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let B=AA.env[W]||(j?AA.env[j]:void 0);if(B!==void 0){if(A.verbose){let f=AA.env[W]?W:j}try{w[X]=this.parseEnvironmentValue(B,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof LA)throw f;throw B$.envVar(W,B,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw B$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(AA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=`${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:Q,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
22
20
 
23
21
  `;for(let A of w)Y+=`${A.key}
24
22
  `,Y+=` Type: ${A.type}
@@ -30,25 +28,25 @@ import{createRequire as q6}from"node:module";var G6=Object.defineProperty;var K6
30
28
  `;Y+=`| Variable | Type | Description | Example |
31
29
  `,Y+=`|----------|------|-------------|----------|
32
30
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
33
- `;return Y}}function y7(w,$){let Y=hj("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function _j(w,$,Y={}){return Sj(w,$,Y,new WeakMap)}function Sj(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return Zj(w,$,X,A);if(!Jw($)||!Jw(w))return $;return S7(w,$,Y,A)}function Zj(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return O7(w,$);case"smart":return L7(w,$,A);default:return $}return $}function O7(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>tJ(X,A)))Y.push(A);return Y}function L7(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Jw($[0])&&Jw(w[0]))return _7(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function _7(w,$,Y){let A=[...$];for(let X of w){if(!Jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((B)=>Jw(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function S7(w,$,Y,A){let X=$;if(Jw(X)&&A.has(X))return A.get(X);let J={...w};if(Jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(Jw(W)&&Jw(Q))J[U]=Sj(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=Zj(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function jU(w,$,Y="replace"){return _j(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function tJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!tJ(w[Y],$[Y]))return!1;return!0}if(Jw(w)&&Jw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!tJ(w[X],$[X]))return!1}return!0}return!1}function Jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class lA{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:W=!1}=Y;if(X){let B=G1.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!NA(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new NY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new NY(w,Error("Configuration must export a valid object"),"unknown");let N={config:jU($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)G1.setWithFileCheck("file",N,w,J);return N}catch(B){throw B instanceof Error?E$.configLoad(w,B):E$.configLoad(w,Error(String(B)))}};if(U)return fY.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(xJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return Oj(async()=>{return NA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!NA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=xJ(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=xJ(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!NA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class zU{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await fY.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!lK($))throw new EY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new EY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:uj},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class GU{fileLoader=new lA;envProcessor=new dA;validator=new zU;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)qw.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){let Q=Date.now()-$;throw qw.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||u$.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(m0(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw E$.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?FY(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)qw.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)qw.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?FY(w,Y,X):Y,W=[m0(Y1(),".config",w),m0(Y1(),".config"),Y1()];for(let Q of W){if(X)qw.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)qw.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?FY(w,A,J):A;try{let Q=m0(Y,"package.json");if(!pJ(Q))return null;let B=await import(Q),j=B[w],z=w;if(!j&&$)j=B[$],z=$;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)qw.success(`Configuration loaded from package.json: ${z}`);return{config:jU(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)qw.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:FY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw E$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return G1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);G1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,m0(w,"config"),m0(w,".config"),$?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(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[m0(Y1(),".config",w),m0(Y1(),".config"),Y1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Qj(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function Z7(w){return lw.loadConfig({...w,__strictErrorHandling:!0})}async function kj(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await lw.loadConfig(w);else A=await lw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)qw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await lw.applyEnvironmentVariables(W.name||"",$,!0,W.verbose||!1))?.config??$;return $}}async function k7(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await lw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Qj(Y)))return(await lw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await lw.loadConfig({...w,cwd:w.cwd||u$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Qj($)))return(await lw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function h7(w,$,Y="replace"){let A=new lA;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function FY(w,$,Y=!1){let A=new dA,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=u$.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}function D7(w){let $=m0(u$.cwd(),w.configDir),Y=m0(u$.cwd(),w.generatedDir),A=m0(Y,"config-types.ts");if(!pJ(uB(A)))MK(uB(A),{recursive:!0,mode:511});let X=pJ($)?IK($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${BF}
31
+ `;return Y}}function wE(w,$){let Y=jB("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function JB(w,$,Y={}){return UB(w,$,Y,new WeakMap)}function UB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let Q=U(w,$);if(Q!==void 0)return Q}if(Array.isArray($)||Array.isArray(w))return WB(w,$,X,A);if(!Xw($)||!Xw(w))return $;return XE(w,$,Y,A)}function WB(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return $E(w,$);case"smart":return YE(w,$,A);default:return $}return $}function $E(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>kJ(X,A)))Y.push(A);return Y}function YE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Xw($[0])&&Xw(w[0]))return AE(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function AE(w,$,Y){let A=[...$];for(let X of w){if(!Xw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let Q of J)if(Q in X){if(A.find((j)=>Xw(j)&&(Q in j)&&j[Q]===X[Q])){U=!0;break}}if(!U)A.push(X)}return A}function XE(w,$,Y,A){let X=$;if(Xw(X)&&A.has(X))return A.get(X);let J={...w};if(Xw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let Q=X[U],W=J[U];if(Y.skipNullish&&(Q===null||Q===void 0))continue;if(Q===null||Q===void 0){J[U]=Q;continue}if(Xw(Q)&&Xw(W))J[U]=UB(W,Q,Y,A);else if(Array.isArray(Q)||Array.isArray(W))J[U]=WB(W,Q,Y.arrayMergeMode||"smart",A);else J[U]=Q}return J}function rJ(w,$,Y="replace"){return JB(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function kJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!kJ(w[Y],$[Y]))return!1;return!0}if(Xw(w)&&Xw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!kJ(w[X],$[X]))return!1}return!0}return!1}function Xw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class kA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath(w,$,Y={}){let{arrayStrategy:A="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:Q=!1}=Y;if(X){let j=U1.getWithFileCheck("file",w);if(j){if(Q)console.log(`Configuration loaded from cache: ${w}`);return j}}let W=async()=>{if(!XA(w))return null;try{let j=`?t=${Date.now()}`,B=await import(w+j),f=B.default||B,z="default"in B,G=Object.keys(B).length>0;if(!z&&!G)throw new o1(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new o1(w,Error("Configuration must export a valid object"),"unknown");let F={config:rJ($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)U1.setWithFileCheck("file",F,w,J);return F}catch(j){throw j instanceof Error?B$.configLoad(w,j):B$.configLoad(w,Error(String(j)))}};if(U)return wY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(NJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return AB(async()=>{return XA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!XA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let Q=NJ(w,`${J}${U}`);if(await this.checkFileAccess(Q))A.push(Q)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let Q=NJ(w,U);if(await this.checkFileAccess(Q))A.push(Q)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!XA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class tJ{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:Q=!0,verbose:W=!1}=Y,j=async()=>{let B=[],f=[],z={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:Q,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,z);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],z);else return this.validateWithJSONSchema(w,$,z)}catch(G){return B.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:B,warnings:f}}};if(Q)return await wY.track("validateConfiguration",j);return j()}async validateWithSchemaFile(w,$,Y){try{if(!N6($))throw new e1($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new e1($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,Q=Array.isArray($.type)?$.type:[$.type];if(!Q.includes(U)){if(A.push({path:Y,message:`Expected type ${Q.join(" or ")}, got ${U}`,expected:Q.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let Q=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let Q of $.required)if(!(Q in U)){if(A.push({path:Y?`${Y}.${Q}`:Q,message:`Missing required property '${Q}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[Q,W]of Object.entries($.properties))if(Q in U){let j=Y?`${Y}.${Q}`:Q;if(this.validateObjectAgainstSchema(U[Q],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let Q=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!Q.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),Q=this.validateWithRule(U,J,J.path);if(A.push(...Q),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:EB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class aJ{fileLoader=new kA;envProcessor=new DA;validator=new tJ;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let Q;try{Q=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;Q={...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 B=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!B&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),z=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(z||B))throw W;if(f&&(!j||!z))Q={...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)Q={...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 Q={...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(Q.config,X,J,U.name);if(Y?.enabled&&Q)this.cacheResult(U.name||"",Q,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Kw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);Q.metrics=W}return Q}catch(Q){let W=Date.now()-$;throw Kw.error(`Configuration loading failed after ${W}ms:`,[Q instanceof Error?Q:Error(String(Q))]),Q}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:Q,checkEnv:W=!0,arrayStrategy:j="replace",verbose:B=!1}=w,f=J||_$.cwd(),z=[],G=await this.loadLocalConfiguration(A,X,f,U,Q,j,B,W,Y);if(G)return z.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,z,W,A,B);let T=await this.loadHomeConfiguration(A,X,Q,j,B,W);if(T)return z.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,z,W,A,B);let K=await this.loadPackageJsonConfiguration(A,X,f,Q,j,B,W);if(K)return z.push(c0(f,"package.json")),this.finalizeResult(K,z,W,A,B);if(z.push(...this.getAllSearchPaths(A,X,f,U)),$)throw B$.configNotFound(A,z,X);return{...await this.applyEnvironmentVariables(A,Q,W,B),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,Q,W){let j=Q?a1(w,X,U):X,B=this.getLocalDirectories(Y,A);for(let f of B){if(U)Kw.info(`Searching for configuration in: ${f}`);let z=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(z,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Kw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?a1(w,Y,X):Y,Q=[c0(a$(),".config",w),c0(a$(),".config"),a$()];for(let W of Q){if(X)Kw.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths(w,W,$),B=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(B){if(X)Kw.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let Q=U?a1(w,A,J):A;try{let W=c0(Y,"package.json");if(!_J(W))return null;let j=await import(W),B=j[w],f=w;if(!B&&$)B=j[$],f=$;if(B&&typeof B==="object"&&!Array.isArray(B)){if(J)Kw.success(`Configuration loaded from package.json: ${f}`);return{config:rJ(Q,B,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Kw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:a1(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw B$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return U1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);U1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,c0(w,"config"),c0(w,".config"),$?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(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[c0(a$(),".config",w),c0(a$(),".config"),a$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function ij(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function JE(w){return cw.loadConfig({...w,__strictErrorHandling:!0})}async function QB(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await cw.loadConfig(w);else A=await cw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Kw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let Q=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await cw.applyEnvironmentVariables(Q.name||"",$,!0,Q.verbose||!1))?.config??$;return $}}async function UE(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await cw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&ij(Y)))return(await cw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await cw.loadConfig({...w,cwd:w.cwd||_$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&ij($)))return(await cw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function WE(w,$,Y="replace"){let A=new kA;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function a1(w,$,Y=!1){let A=new DA,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,Q=[]){let W={...U};for(let[j,B]of Object.entries(U)){let f=[...Q,j],z=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((K)=>K.toUpperCase()).join("")}`,`${X}_${f.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of z)if(G=_$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof B==="boolean")W[j]=["true","1","yes"].includes(G.toLowerCase());else if(typeof B==="number"){let K=Number(G);if(!Number.isNaN(K))W[j]=K}else if(Array.isArray(B))try{W[j]=JSON.parse(G)}catch{W[j]=G.split(",").map((K)=>K.trim())}else W[j]=G;else if(B&&typeof B==="object"&&!Array.isArray(B))W[j]=J(B,f)}return W}return J($)}function QE(w){let $=c0(_$.cwd(),w.configDir),Y=c0(_$.cwd(),w.generatedDir),A=c0(Y,"config-types.ts");if(!_J(Ej(A)))a5(Ej(A),{recursive:!0,mode:511});let X=_J($)?s5($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${iE}
34
32
  export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
35
- `;VK(A,J,{mode:438})}function x7(w){let $=null,Y=null,A=()=>{if(!Y)Y=kj(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)qw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let W=X[U];return A(),W},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,W){if(!$)$={...X};return $[U]=W,!0}})}function P7(w){let $=eB(rK.cwd(),w?.configDir||"./config");function Y(){if(!nK($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=pK($).filter((Q)=>X.has(PJ(Q))).map((Q)=>({base:Q.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Q})),W=new Map;for(let{base:Q,file:B}of U){let j=PJ(B).toLowerCase(),z=W.get(Q);if(!z){W.set(Q,B);continue}let G=PJ(z).toLowerCase();if(J.indexOf(j)<J.indexOf(G))W.set(Q,B)}return Array.from(W.entries()).map(([Q,B])=>({base:Q,file:B})).sort((Q,B)=>Q.base.localeCompare(B.base))}function A(){let X=Y(),J=X.map((B)=>B.base),U=J.length?J.map((B)=>`'${B}'`).join(" | "):"string",W=X.length?`{
36
- ${X.map((B)=>{let j=eB($,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
33
+ `;o5(A,J,{mode:438})}function jE(w){let $=null,Y=null,A=()=>{if(!Y)Y=QB(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Kw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let Q=X[U];return A(),Q},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,Q){if(!$)$={...X};return $[U]=Q,!0}})}function BE(w){let $=Oj(M6.cwd(),w?.configDir||"./config");function Y(){if(!H6($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=R6($).filter((W)=>X.has(HJ(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),Q=new Map;for(let{base:W,file:j}of U){let B=HJ(j).toLowerCase(),f=Q.get(W);if(!f){Q.set(W,j);continue}let z=HJ(f).toLowerCase();if(J.indexOf(B)<J.indexOf(z))Q.set(W,j)}return Array.from(Q.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",Q=X.length?`{
34
+ ${X.map((j)=>{let B=Oj($,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${B}').default`}).join(`,
37
35
  `)}
38
36
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
39
- export type ConfigByName = ${W}
37
+ export type ConfigByName = ${Q}
40
38
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
41
39
  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 zF(w,$={}){let Y=hA.cwd();while(Y.includes("storage"))Y=wj(Y,"..");let A=wj(Y,w||"");if($?.relative)return aK(hA.cwd(),A);return A}function N0(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function KF(){if(dw.env.NODE_ENV==="test"||dw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof dw<"u"){let w=dw.type;if(w==="renderer"||w==="worker")return!1;return!!(dw.versions&&(dw.versions.node||dw.versions.bun))}return!1}class mj{async format(w){let $=await KF(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:z1.pid,hostname:$(),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 nA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...vA},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new mj,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...dJ,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...dJ};return{...dJ,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:vA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await $7(this.config.logDirectory,Xj.F_OK|Xj.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await Y7(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:iw.from(w);try{if(!EA(this.currentLogFile))await cJ(this.currentLogFile,"",{mode:420});if(X=Aj(this.currentLogFile,"a",420),w7(X,Q,{flag:"a"}),Yj(X),X!==void 0)uJ(X),X=void 0;if((await B1(this.currentLogFile)).size===0){if(await cJ(this.currentLogFile,Q,{flag:"w",mode:420}),(await B1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;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(X!==void 0)try{uJ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();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 j1(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 j1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return j1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return bJ(16).toString("hex")}generateKey(){return bJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=bJ(16),A=sK("aes-256-gcm",$,Y),X=iw.isBuffer(w)?w:iw.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=iw.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Uj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(iw.from(iw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let w=await B1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await fA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await B1(Y).catch(()=>null))try{if(await Jj(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await TA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await cJ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await B1(Y).catch(()=>null))await Jj(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await fA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await TA(j1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=$j(w),A=eK($),X=Uj();await J7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),EA(this.currentLogFile))try{let w=Aj(this.currentLogFile,"r+");Yj(w),uJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await fA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await TA(j1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?i.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let w=typeof D.env.NO_COLOR<"u",$=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(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=D.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${i.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=i.underline(i.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>i.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>i.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>i.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>i.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>i.strikethrough(A)),$}supportsHyperlinks(){if(N0())return!1;let w=D.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=D.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(A7($)||$.startsWith("./")||$.startsWith("../"))$=X7($);else return null;return EA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":fF[w],G=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:i.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:i.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
43
- `);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:i.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!N0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
44
- `;if(W)j+=`${W}
45
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(W,Q)=>{},finish:(W)=>{},interrupt:(W,Q)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!N0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Q="info")=>{if(!N0()&&D.stdout.isTTY)D.stdout.write(`
46
- `);if(this[Q==="warning"?"warn":Q](W),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=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(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
47
- `,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":i.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!N0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new nA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(N0())throw Error("createReadStream is not supported in browser environments");if(!EA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return $j(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=iw.isBuffer(w)?w:iw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=oK("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=iw.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N0()}isServerMode(){return!N0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
48
- `),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:i.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(j),showTimestamp:!1}))}else if(!N0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
49
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(N0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${i.cyan("?")} ${w} (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(""),$(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(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let Q=/%([sdijfo%])/g,B=0;if(Y=w.replace(Q,(j,z)=>{if(z==="%")return"%";if(B>=$.length)return j;let G=$[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<$.length)Y+=` ${$.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${B}${Q} ${i.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
50
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=i.green("━".repeat(A)),U=i.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?i.green("✓"):i.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=D.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,D.stdout.write(w.lastRenderedLine),$)D.stdout.write(`
51
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||N0()||!D.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(N0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await fA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=j1(this.config.logDirectory,A);if(w.before)try{if((await B1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await 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($){console.error("Error during log clearing process:",$)}}}async function TF(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class FU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return JU.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=RA.env[Q]||(B?RA.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=RA.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof KU)throw z;throw K1.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw K1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(RA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
40
+ `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function uE(w,$={}){let Y=RA.cwd();while(Y.includes("storage"))Y=hj(Y,"..");let A=hj(Y,w||"");if($?.relative)return I6(RA.cwd(),A);return A}function F0(){if(vw.env.NODE_ENV==="test"||vw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function cE(){if(vw.env.NODE_ENV==="test"||vw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof vw<"u"){let w=vw.type;if(w==="renderer"||w==="worker")return!1;return!!(vw.versions&&(vw.versions.node||vw.versions.bun))}return!1}class qB{async format(w){let $=await cE(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:J1.pid,hostname:$(),environment:J1.env.NODE_ENV||"development",platform:J1.platform,version:J1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:J1.env.NODE_ENV||J1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class ZA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...SA},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new qB,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...SJ,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...SJ};return{...SJ,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:SA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!F0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,Q=1000;while(J<U)try{try{try{await O6(this.config.logDirectory,Zj.F_OK|Zj.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await h6(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(w)).encrypted:iw.from(w);try{if(!JA(this.currentLogFile))await yJ(this.currentLogFile,"",{mode:420});if(X=kj(this.currentLogFile,"a",420),S6(X,W,{flag:"a"}),Dj(X),X!==void 0)MJ(X),X=void 0;if((await A1(this.currentLogFile)).size===0){if(await yJ(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 B=j;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(J<U-1){let f=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let z=Q*2**J;await new Promise((G)=>setTimeout(G,z)),J++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(X!==void 0)try{MJ(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let B=W,f=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let j=Q*2**(J-1);await new Promise((B)=>setTimeout(B,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 w=new Date().toISOString().split("T")[0];return X1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(F0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,W])=>W.createdAt.getTime()-Q.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[Q]of X.slice(U))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return RJ(16).toString("hex")}generateKey(){return RJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=RJ(16),A=C6("aes-256-gcm",$,Y),X=iw.isBuffer(w)?w:iw.from(w,"utf8"),J=A.update(X),U=A.final(),Q=J.length+U.length,W=A.getAuthTag(),j=iw.allocUnsafe(16+Q+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+Q),{encrypted:j,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Pj(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(iw.from(iw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(F0())return;if(!this.shouldWriteToFile())return;let w=await A1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await UA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let B=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${U}`;if(await A1(Y).catch(()=>null))try{if(await xj(Y,Q),$.compress)try{let W=`${Q}.gz`;await this.compressLogFile(Q,W),await WA(Q)}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 yJ(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 xj(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await UA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Q)=>Q.localeCompare(U));for(let U of J.slice($.maxFiles))await WA(X1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=_j(w),A=L6($),X=Pj();await k6(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),JA(this.currentLogFile))try{let w=kj(this.currentLogFile,"r+");Dj(w),MJ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!F0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await UA(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await WA(X1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?c.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||F0())return!1;let w=typeof Z.env.NO_COLOR<"u",$=Z.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof Z.stderr<"u"&&Z.stderr.isTTY||typeof Z.stdout<"u"&&Z.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,Q=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=Z.stdout.columns||120,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 B=Q(j).trim().length,f=Q($).length,z=Math.max(1,W-2-B-f);return`${j.trim()}${" ".repeat(z)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let Q=Number.parseInt(U,10);return Q<$[0].length?String($[0][Q]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let Q=$[A++];switch(U){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Q=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${Q}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),$}supportsHyperlinks(){if(F0())return!1;let w=Z.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=Z.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(_6($)||$.startsWith("./")||$.startsWith("../"))$=D6($);else return null;return JA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,Q;if($ instanceof Error)U=$.message,Q=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":lE[w],z=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:c.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:c.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.error(G),Q){let T=Q.split(`
41
+ `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:c.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!F0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),Q)console.error(Q)}let B=`${J} ${this.environment}.${w.toUpperCase()}: ${j}
42
+ `;if(Q)B+=`${Q}
43
+ `;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress(w,$=""){let Y={update:(Q,W)=>{},finish:(Q)=>{},interrupt:(Q,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!F0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Q,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Q),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!F0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Q)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Q)},interrupt:(Q,W="info")=>{if(!F0()&&Z.stdout.isTTY)Z.stdout.write(`
44
+ `);if(this[W==="warning"?"warn":W](Q),this.activeProgressBar&&this.shouldStyleConsole()&&!F0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":c.blue("◐"),tag:Y,message:`${c.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,Q=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
45
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:this.options.showIcons===!1?"":c.green("✓"),tag:B,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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new ZA($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(F0())throw Error("createReadStream is not supported in browser environments");if(!JA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return _j(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=iw.isBuffer(w)?w:iw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),Q=V6("aes-256-gcm",Y,X);Q.setAuthTag(J);let W=Q.update(U),j=Q.final(),B=W.length+j.length,f=iw.allocUnsafe(B);return W.copy(f,0),j.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return F0()}isServerMode(){return!F0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let Q=X.split(`
46
+ `),W=Math.max(...Q.map((z)=>z.length))+2,j=`┌${"─".repeat(W)}┐`,B=`└${"─".repeat(W)}┘`,f=Q.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(j),showTimestamp:!1})),f.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(B),showTimestamp:!1}))}else if(!F0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
47
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(F0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${c.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();Z.stdin.removeListener("data",Y);try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!1)}catch{}Z.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!0)}catch{}Z.stdin.resume(),Z.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=w.replace(W,(B,f)=>{if(f==="%")return"%";if(j>=$.length)return B;let z=$[j++];switch(f){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 B}}),j<$.length)Y+=` ${$.slice(j).map((B)=>typeof B==="object"?JSON.stringify(B,null,2):String(B)).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 Q=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
48
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!Z.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=c.green("━".repeat(A)),U=c.gray("━".repeat(X)),Q=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=w.message?` ${w.message}`:"",B=this.options.showIcons===!1?"":$||Y===100?c.green("✓"):c.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",z=`\r${B}${f} ${Q} ${W}${j}`,G=Z.stdout.columns||80,T=" ".repeat(Math.max(0,G-z.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${z}${T}`,Z.stdout.write(w.lastRenderedLine),$)Z.stdout.write(`
49
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||F0()||!Z.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(F0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await UA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=X1(this.config.logDirectory,A);if(w.before)try{if((await A1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await WA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function pE(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let Q=0;Q<=Y;Q++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),Q===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 oJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:Q=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let B=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],B,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:Q,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return gJ.track("applyEnvironmentVariables",j,{configName:w});return j()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=U.map((B)=>this.formatEnvKey(B,A.useCamelCase)),W=`${Y}_${Q.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((B)=>B.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let B=jA.env[W]||(j?jA.env[j]:void 0);if(B!==void 0){if(A.verbose){let f=jA.env[W]?W:j}try{w[X]=this.parseEnvironmentValue(B,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof sJ)throw f;throw W1.envVar(W,B,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw W1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(jA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=`${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:Q,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
52
50
 
53
51
  `;for(let A of w)Y+=`${A.key}
54
52
  `,Y+=` Type: ${A.type}
@@ -60,28 +58,28 @@ export type ConfigOf = Config
60
58
  `;Y+=`| Variable | Type | Description | Example |
61
59
  `,Y+=`|----------|------|-------------|----------|
62
60
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
63
- `;return Y}}function HF(w,$,Y={}){return aj(w,$,Y,new WeakMap)}function aj(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return sj(w,$,X,A);if(!Uw($)||!Uw(w))return $;return VF(w,$,Y,A)}function sj(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return RF(w,$);case"smart":return MF(w,$,A);default:return $}return $}function RF(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>XU(X,A)))Y.push(A);return Y}function MF(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Uw($[0])&&Uw(w[0]))return IF(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function IF(w,$,Y){let A=[...$];for(let X of w){if(!Uw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((B)=>Uw(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function VF(w,$,Y,A){let X=$;if(Uw(X)&&A.has(X))return A.get(X);let J={...w};if(Uw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(Uw(W)&&Uw(Q))J[U]=aj(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=sj(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function oj(w,$,Y="replace"){return HF(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function XU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!XU(w[Y],$[Y]))return!1;return!0}if(Uw(w)&&Uw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!XU(w[X],$[X]))return!1}return!0}return!1}function Uw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class ej{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:W=!1}=Y;if(X){let B=_A.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!MA(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new iA(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new iA(w,Error("Configuration must export a valid object"),"unknown");let N={config:oj($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)_A.setWithFileCheck("file",N,w,J);return N}catch(B){throw B instanceof Error?K1.configLoad(w,B):K1.configLoad(w,Error(String(B)))}};if(U)return JU.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(lJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return TF(async()=>{return MA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!MA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=lJ(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=lJ(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!MA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class w9{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await JU.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!CF($))throw new mA($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new mA($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:yF},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function OF(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class $9{fileLoader=new ej;envProcessor=new FU;validator=new w9;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)_w.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let Q=Date.now()-$;throw _w.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||gA.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(Xw(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw K1.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${OF(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?IA(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)_w.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)_w.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?IA(w,Y,X):Y,W=[Xw($1(),".config",w),Xw($1(),".config"),$1()];for(let Q of W){if(X)_w.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)_w.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?IA(w,A,J):A;try{let Q=Xw(Y,"package.json");if(!HK(Q))return null;let B={};try{B=JSON.parse(RK(Q,"utf8"))}catch(G){if(J)_w.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let j=B[w],z=w;if(!j&&$){let G=Array.isArray($)?$:[$];for(let K of G){if(!K)continue;if(B[K]){j=B[K],z=K;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)_w.success(`Configuration loaded from package.json: ${z}`);return{config:oj(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)_w.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:IA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw K1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return _A.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);_A.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Xw(w,"config"),Xw(w,".config"),$?Xw(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(Xw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Xw($1(),".config",w),Xw($1(),".config"),$1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}async function qU(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await nJ.loadConfig(w);else A=await nJ.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)_w.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await nJ.applyEnvironmentVariables(W.name||"",$,!0,W.verbose||!1))?.config??$;return $}}function IA(w,$,Y=!1){let A=new FU,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=gA.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}var _A,JU,U7,Q7=(w)=>w,B7=(w,$)=>{for(var Y in $)U7(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:W7.bind($,Y)})},j7=(w,$)=>()=>(w&&($=w(w=0)),$),Vj,hj,G1,fY,Dj,b7,u7,Wj,CA,aJ,L0,a,c7,Bj,v7,jj,i7,m7,vJ,g7,zj,Gj,iJ,d7,l7,n7,p7,yA,xj,r7,_0,t7,a7,Kj,OA,sJ,q0,u,s7,Fj,o7,qj,e7,wF,mJ,$F,Nj,Ej,YF,gJ,AF,XF,JF,UF,QF,LA,Pj,WF,BF="0.15.6",o0,uA,NY,oJ,eJ,cA,wU,$U,EY,YU,AU,E$,bj,uj,qw,lw,cj,vj,jF,GF,ij,vA,dI,V0,i,lI,FF,nI,qF,pI,rI,fj,tI,NF,EF,aI,Tj,sI,oI,eI,wV,$V,dJ,fF,YV,Nw,gj,iA,dj,lj,KU,nj,pj,mA,rj,tj,K1,yF,_w,nJ,QV,WV;var NU=t(()=>{_A=new Hj,JU=new Rj,U7=Object.defineProperty;Vj={};B7(Vj,{withErrorRecovery:()=>Oj,tryLoadConfig:()=>h7,loadConfigWithResult:()=>Z7,loadConfig:()=>kj,isRetryableError:()=>C7,isConfigNotFoundError:()=>V7,isBunfigError:()=>Lj,globalPerformanceMonitor:()=>fY,globalCache:()=>G1,getEnvOrDefault:()=>y7,generateConfigTypes:()=>D7,defaultGeneratedDir:()=>vj,defaultConfigDir:()=>cj,deepMergeWithArrayStrategy:()=>jU,deepMerge:()=>_j,createLibraryConfig:()=>x7,config:()=>k7,bunfigPlugin:()=>P7,applyEnvVarsToConfig:()=>FY,TypeGenerationError:()=>$U,SchemaValidationError:()=>EY,PluginError:()=>AU,PerformanceMonitor:()=>QU,FileSystemError:()=>wU,ErrorFactory:()=>E$,EnvVarError:()=>cA,EnvProcessor:()=>dA,ConfigValidator:()=>zU,ConfigValidationError:()=>oJ,ConfigNotFoundError:()=>uA,ConfigMergeError:()=>eJ,ConfigLoader:()=>GU,ConfigLoadError:()=>NY,ConfigFileLoader:()=>lA,ConfigCache:()=>UU,CacheUtils:()=>Dj,BunfigError:()=>o0,BrowserConfigError:()=>YU,ArrayMergeStrategies:()=>bj});jF=j7(async()=>{hj=import.meta.require,G1=new UU,fY=new QU,Dj={createKey:z7,isEquivalent:G7,estimateMemoryUsage:K7},b7=kA(rJ.cwd(),"config"),u7=kA(rJ.cwd(),"src/generated"),Wj=ZA.env.CLARITY_LOG_DIR||OK(N7(),"logs"),CA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Wj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},aJ=await E7(),L0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},a=L0,c7=L0.red,Bj=L0.green,v7=L0.yellow,jj=L0.blue,i7=L0.magenta,m7=L0.cyan,vJ=L0.white,g7=L0.gray,zj=L0.bgRed,Gj=L0.bgYellow,iJ=L0.bold,d7=L0.dim,l7=L0.italic,n7=L0.underline,p7=L0.reset,yA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},xj={debug:"\uD83D\uDD0D",info:jj("ℹ"),success:Bj("✓"),warning:Gj(vJ(iJ(" WARN "))),error:zj(vJ(iJ(" ERROR ")))},r7=new xA("stacks"),_0=new xA("bunfig",{showTags:!0}),t7=i0(qY.cwd(),"config"),a7=i0(qY.cwd(),"src/generated"),Kj=SA.env.CLARITY_LOG_DIR||CK(R7(),"logs"),OA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Kj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},sJ=await M7(),q0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},u=q0,s7=q0.red,Fj=q0.green,o7=q0.yellow,qj=q0.blue,e7=q0.magenta,wF=q0.cyan,mJ=q0.white,$F=q0.gray,Nj=q0.bgRed,Ej=q0.bgYellow,YF=q0.bgGray,gJ=q0.bold,AF=q0.dim,XF=q0.italic,JF=q0.underline,UF=q0.strikethrough,QF=q0.reset,LA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Pj={debug:"\uD83D\uDD0D",info:qj("ℹ"),success:Fj("✓"),warning:Ej(mJ(gJ(" WARN "))),error:Nj(mJ(gJ(" ERROR ")))},WF=new bA("stacks"),o0=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},uA=class extends o0{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},NY=class extends o0{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},oJ=class extends o0{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},eJ=class extends o0{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},cA=class extends o0{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},wU=class extends o0{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},$U=class extends o0{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},EY=class extends o0{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},YU=class extends o0{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},AU=class extends o0{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},E$={configNotFound(w,$,Y){return new uA(w,$,Y)},configLoad(w,$,Y){return new NY(w,$,Y)},configValidation(w,$,Y){return new oJ(w,$,Y)},configMerge(w,$,Y,A){return new eJ(w,$,Y,A)},envVar(w,$,Y,A){return new cA(w,$,Y,A)},fileSystem(w,$,Y){return new wU(w,$,Y)},typeGeneration(w,$,Y){return new $U(w,$,Y)},schemaValidation(w,$,Y){return new EY(w,$,Y)},browserConfig(w,$,Y,A){return new YU(w,$,Y,A)},plugin(w,$,Y){return new AU(w,$,Y)}},bj={replace:"replace",concat:"concat",smart:"smart"},uj=/^https?:\/\//,qw=new bA("bunfig",{showTags:!0}),lw=new GU,cj=m0(u$.cwd(),"config"),vj=m0(u$.cwd(),"src/generated")});GF=hA.env.CLARITY_LOG_DIR||tK(zF(),"logs"),ij={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:GF,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},vA={...ij},dI=(async()=>{try{let{loadConfig:w}=await jF().then(()=>Vj),$=await w({name:"clarity",alias:"logging",defaultConfig:ij,cwd:hA.cwd()});if($)Object.assign(vA,$)}catch{}return vA})();V0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},i=V0,lI=V0.red,FF=V0.green,nI=V0.yellow,qF=V0.blue,pI=V0.magenta,rI=V0.cyan,fj=V0.white,tI=V0.gray,NF=V0.bgRed,EF=V0.bgYellow,aI=V0.bgGray,Tj=V0.bold,sI=V0.dim,oI=V0.italic,eI=V0.underline,wV=V0.strikethrough,$V=V0.reset,dJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fF={debug:"\uD83D\uDD0D",info:qF("ℹ"),success:FF("✓"),warning:EF(fj(Tj(" WARN "))),error:NF(fj(Tj(" ERROR ")))};YV=new nA("stacks");Nw=class Nw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};gj=class gj extends Nw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};iA=class iA extends Nw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};dj=class dj extends Nw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};lj=class lj extends Nw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};KU=class KU extends Nw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};nj=class nj extends Nw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};pj=class pj extends Nw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};mA=class mA extends Nw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};rj=class rj extends Nw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};tj=class tj extends Nw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};K1={configNotFound(w,$,Y){return new gj(w,$,Y)},configLoad(w,$,Y){return new iA(w,$,Y)},configValidation(w,$,Y){return new dj(w,$,Y)},configMerge(w,$,Y,A){return new lj(w,$,Y,A)},envVar(w,$,Y,A){return new KU(w,$,Y,A)},fileSystem(w,$,Y){return new nj(w,$,Y)},typeGeneration(w,$,Y){return new pj(w,$,Y)},schemaValidation(w,$,Y){return new mA(w,$,Y)},browserConfig(w,$,Y,A){return new rj(w,$,Y,A)},plugin(w,$,Y){return new tj(w,$,Y)}};yF=/^https?:\/\//;_w=new nA("bunfig",{showTags:!0});nJ=new $9;QV=Xw(gA.cwd(),"config"),WV=Xw(gA.cwd(),"src/generated")});function q1(w){return w.startsWith("*.")}function TY(w,$){if(!q1($))return!1;let Y=$.slice(1);return w.length>Y.length&&w.endsWith(Y)}function pA(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!q1(J))continue;if(TY($,J)){let W=J.length-1;if(W>X)X=W,A=U}}return A}var H;var nw=t(()=>{H={info:(...w)=>console.log("[info]",...w),success:(...w)=>console.log("[success]",...w),warn:(...w)=>console.warn("[warn]",...w),error:(...w)=>console.error("[error]",...w),debug:(...w)=>console.debug("[debug]",...w),log:(...w)=>console.log(...w),start:(...w)=>console.log("[start]",...w),box:(...w)=>console.log("[box]",...w)}});import{createRequire as mF}from"node:module";import{Resolver as MU}from"node:dns/promises";import{createHash as dF,sign as lF}from"node:crypto";import{createHash as nF}from"node:crypto";import{sign as pF}from"node:crypto";import{generateKeyPairSync as Fz,X509Certificate as Yq}from"node:crypto";import IU from"node:os";import VU from"node:path";import{existsSync as j9,statSync as z9}from"fs";import{existsSync as Xq,mkdirSync as ZV,readdirSync as kV,readFileSync as Jq,writeFileSync as hV}from"fs";import{homedir as E1}from"os";import{dirname as PV,resolve as Ww}from"path";import xX from"process";import{existsSync as G9,statSync as K9}from"fs";import{existsSync as rU,mkdirSync as Uq,readdirSync as Qq,writeFileSync as Wq}from"fs";import{homedir as f1}from"os";import{dirname as F9,resolve as d0}from"path";import i$ from"process";import{join as Bq,relative as jq,resolve as q9}from"path";import fX from"process";import{existsSync as qz,mkdirSync as nV,readdirSync as pV,writeFileSync as rV}from"fs";import{homedir as CU}from"os";import{dirname as sV,resolve as g0}from"path";import VY from"process";import{join as zq,relative as Gq,resolve as N9}from"path";import TX from"process";import{existsSync as Nz,mkdirSync as Y3,readdirSync as A3,writeFileSync as X3}from"fs";import{dirname as U3,resolve as HX}from"path";import tU from"process";import{Buffer as f$}from"buffer";import{createCipheriv as Kq,createDecipheriv as Fq,randomBytes as yU}from"crypto";import{closeSync as OU,createReadStream as E9,createWriteStream as qq,existsSync as LU,fsyncSync as f9,openSync as T9,writeFileSync as Nq}from"fs";import{access as Eq,constants as H9,mkdir as fq,readdir as tA,rename as R9,stat as T1,unlink as aA,writeFile as _U}from"fs/promises";import{join as H1}from"path";import S0 from"process";import{pipeline as Tq}from"stream/promises";import{createGzip as M9}from"zlib";import R1 from"process";import aw from"process";import{Buffer as pw}from"buffer";import{createCipheriv as Hq,createDecipheriv as Rq,randomBytes as SU}from"crypto";import{closeSync as ZU,createReadStream as I9,createWriteStream as Mq,existsSync as sA,fsyncSync as V9,openSync as C9,writeFileSync as Iq}from"fs";import{access as Vq,constants as y9,mkdir as Cq,readdir as oA,rename as O9,stat as M1,unlink as eA,writeFile as kU}from"fs/promises";import{isAbsolute as yq,join as I1,resolve as Oq}from"path";import l from"process";import{pipeline as Lq}from"stream/promises";import{createGzip as L9}from"zlib";import V1 from"process";import sw from"process";import wX from"process";import{existsSync as $X}from"fs";import{resolve as hU}from"path";import{existsSync as _q}from"fs";import{existsSync as Sq,readdirSync as Zq}from"fs";import{extname as DU,resolve as _9}from"path";import kq from"process";import{join as hq,relative as Dq,resolve as S9}from"path";import RX from"process";import{Buffer as rw}from"buffer";import{createCipheriv as xq,createDecipheriv as Pq,randomBytes as xU}from"crypto";import{closeSync as PU,createReadStream as Z9,createWriteStream as bq,existsSync as YX,fsyncSync as k9,openSync as h9,writeFileSync as uq}from"fs";import{access as cq,constants as D9,mkdir as vq,readdir as AX,rename as x9,stat as C1,unlink as XX,writeFile as bU}from"fs/promises";import{isAbsolute as iq,join as y1,resolve as mq}from"path";import n from"process";import{pipeline as gq}from"stream/promises";import{createGzip as P9}from"zlib";import O1 from"process";import ow from"process";import JX from"process";import{existsSync as UX}from"fs";import{resolve as uU}from"path";import{existsSync as dq}from"fs";import{exec as GE}from"node:child_process";import UQ from"node:fs";import KE from"node:os";import Ew from"node:path";import oz from"node:process";import{promisify as FE}from"node:util";import Z1 from"node:crypto";import ew from"node:fs";import BQ from"node:path";import bE from"node:crypto";import{execSync as vE}from"node:child_process";import hX from"node:os";async function BX(w,$={},Y=30000){try{return await fetch(w,{...$,signal:AbortSignal.timeout(Y)})}catch(A){if(A&&typeof A==="object"&&A.name==="TimeoutError"){let X=Error(`ACME HTTP request to ${w} timed out after ${Y}ms`);throw X.name="AcmeRequestTimeoutError",X}throw A}}async function $z(w,$,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=w.split(".").slice(-2).join("."),U;try{let B=new MU,j=await B.resolveNs(J),z=(await Promise.all(j.map((G)=>B.resolve4(G).catch(()=>[])))).flat();if(z.length>0)U=new MU,U.setServers(z)}catch{}let W=Date.now()+A,Q=U??new MU;for(;;){try{if((await Q.resolveTxt(w)).some((B)=>B.join("")===$))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,X))}}class IY{tokens=new Map;add(w,$){this.tokens.set(w,$)}get(w){return this.tokens.get(w)}remove(w){this.tokens.delete(w)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(w){let $=w.indexOf(IY.PATH_PREFIX);if($===-1)return;let Y=w.slice($+IY.PATH_PREFIX.length);return this.get(Y)}}function jX(w){return(typeof w==="string"?Buffer.from(w,"utf8"):Buffer.from(w)).toString("base64url")}function dU(w){return Buffer.from(w,"base64url")}function Yz(w){let $=w.export({format:"jwk"});if($.kty!=="EC"||$.crv!=="P-256"||!$.x||!$.y)throw Error(`Expected a P-256 EC public key, got kty=${$.kty} crv=${$.crv}`);return{crv:"P-256",kty:"EC",x:$.x,y:$.y}}function Az(w){let $=`{"crv":"${w.crv}","kty":"${w.kty}","x":"${w.x}","y":"${w.y}"}`;return dF("sha256").update($).digest("base64url")}function Xz(w){let{protectedHeader:$,payload:Y,privateKey:A}=w,X=jX(JSON.stringify($)),J=Y===""?"":jX(JSON.stringify(Y)),U=`${X}.${J}`,W=lF("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:jX(W)}}class EX{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(w){this.directoryUrl=w.directoryUrl,this.accountKey=w.accountKey,this.jwk=Yz(w.accountPublicKey),this.thumbprint=Az(this.jwk),this.requestTimeoutMs=w.requestTimeoutMs??wz}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let w=await BX(this.directoryUrl,{},this.requestTimeoutMs);if(!w.ok)throw Error(`Failed to fetch ACME directory: HTTP ${w.status}`);return this.directoryCache=await w.json(),this.directoryCache}async newNonce(){let w=await this.directory(),$=(await BX(w.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!$)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=$,$}async ensureNonce(){if(this.nonce){let w=this.nonce;return this.nonce=void 0,w}return this.newNonce()}async signedPost(w){let{url:$,payload:Y,useJwk:A}=w,X={alg:"ES256",nonce:await this.ensureNonce(),url:$};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=Xz({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await BX($,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)},this.requestTimeoutMs),W=U.headers.get("replay-nonce");if(W)this.nonce=W;let Q=U.headers.get("content-type")??"",B;if(Q.includes("application/pem-certificate-chain")||Q.startsWith("text/"))B=await U.text();else{let j=await U.text();B=j?JSON.parse(j):{}}if(U.status>=400){let j=B??{};throw new NX(`ACME request to ${$} failed (HTTP ${U.status}): ${j.type??""} ${j.detail??""}`.trim(),j,U.status)}return{status:U.status,headers:U.headers,body:B,location:U.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount(w={}){let $=await this.directory(),Y={termsOfServiceAgreed:!0};if(w.email)Y.contact=[`mailto:${w.email}`];let A=await this.signedPost({url:$.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder(w){let $=await this.directory(),Y={identifiers:w.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:$.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization(w){return(await this.signedPost({url:w,payload:""})).body}keyAuthorization(w){return`${w}.${this.thumbprint}`}dns01TxtValue(w){return nF("sha256").update(this.keyAuthorization(w)).digest("base64url")}async notifyChallengeReady(w){await this.signedPost({url:w,payload:{}})}async pollAuthorization(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization(w);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((W)=>W.status==="invalid");throw new NX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await B9(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${w} to become valid`)}async finalizeOrder(w,$){return(await this.signedPost({url:w,payload:{csr:$}})).body}async getOrder(w){return(await this.signedPost({url:w,payload:""})).body}async pollOrder(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder(w);if(J.status==="valid"){if(!J.certificate)throw Error("ACME order is valid but has no certificate URL");return J.certificate}if(J.status==="invalid")throw Error(`ACME order ${w} became invalid`);await B9(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${w} to become valid`)}async downloadCertificate(w){let $=await this.signedPost({url:w,payload:""});return typeof $.body==="string"?$.body:String($.body)}static selectChallenge(w,$){let Y=w.challenges.find((A)=>A.type===$);if(!Y)throw Error(`No ${$} challenge available for ${w.identifier.value}`);return Y}}function Qz(w){let $=w.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=$[0];if(!Y)return{certPem:`${w.trim()}
61
+ `;return Y}}function rE(w,$,Y={}){return VB(w,$,Y,new WeakMap)}function VB(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let Q=U(w,$);if(Q!==void 0)return Q}if(Array.isArray($)||Array.isArray(w))return LB(w,$,X,A);if(!Jw($)||!Jw(w))return $;return oE(w,$,Y,A)}function LB(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return tE(w,$);case"smart":return aE(w,$,A);default:return $}return $}function tE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>mJ(X,A)))Y.push(A);return Y}function aE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Jw($[0])&&Jw(w[0]))return sE(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function sE(w,$,Y){let A=[...$];for(let X of w){if(!Jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let Q of J)if(Q in X){if(A.find((j)=>Jw(j)&&(Q in j)&&j[Q]===X[Q])){U=!0;break}}if(!U)A.push(X)}return A}function oE(w,$,Y,A){let X=$;if(Jw(X)&&A.has(X))return A.get(X);let J={...w};if(Jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let Q=X[U],W=J[U];if(Y.skipNullish&&(Q===null||Q===void 0))continue;if(Q===null||Q===void 0){J[U]=Q;continue}if(Jw(Q)&&Jw(W))J[U]=VB(W,Q,Y,A);else if(Array.isArray(Q)||Array.isArray(W))J[U]=LB(W,Q,Y.arrayMergeMode||"smart",A);else J[U]=Q}return J}function SB(w,$,Y="replace"){return rE(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function mJ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!mJ(w[Y],$[Y]))return!1;return!0}if(Jw(w)&&Jw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!mJ(w[X],$[X]))return!1}return!0}return!1}function Jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class OB{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:Q=!1}=Y;if(X){let j=TA.getWithFileCheck("file",w);if(j){if(Q)console.log(`Configuration loaded from cache: ${w}`);return j}}let W=async()=>{if(!BA(w))return null;try{let j=`?t=${Date.now()}`,B=await import(w+j),f=B.default||B,z="default"in B,G=Object.keys(B).length>0;if(!z&&!G)throw new OA(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new OA(w,Error("Configuration must export a valid object"),"unknown");let F={config:SB($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)TA.setWithFileCheck("file",F,w,J);return F}catch(j){throw j instanceof Error?W1.configLoad(w,j):W1.configLoad(w,Error(String(j)))}};if(U)return gJ.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(OJ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return pE(async()=>{return BA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!BA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let Q=OJ(w,`${J}${U}`);if(await this.checkFileAccess(Q))A.push(Q)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let Q=OJ(w,U);if(await this.checkFileAccess(Q))A.push(Q)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!BA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class hB{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:Q=!0,verbose:W=!1}=Y,j=async()=>{let B=[],f=[],z={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:Q,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,z);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],z);else return this.validateWithJSONSchema(w,$,z)}catch(G){return B.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:B,warnings:f}}};if(Q)return await gJ.track("validateConfiguration",j);return j()}async validateWithSchemaFile(w,$,Y){try{if(!eE($))throw new hA($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new hA($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,Q=Array.isArray($.type)?$.type:[$.type];if(!Q.includes(U)){if(A.push({path:Y,message:`Expected type ${Q.join(" or ")}, got ${U}`,expected:Q.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let Q=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let Q of $.required)if(!(Q in U)){if(A.push({path:Y?`${Y}.${Q}`:Q,message:`Missing required property '${Q}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[Q,W]of Object.entries($.properties))if(Q in U){let j=Y?`${Y}.${Q}`:Q;if(this.validateObjectAgainstSchema(U[Q],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let Q=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!Q.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),Q=this.validateWithRule(U,J,J.path);if(A.push(...Q),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:wK},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function $K(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class _B{fileLoader=new OB;envProcessor=new oJ;validator=new hB;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let Q;try{Q=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;Q={...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 B=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!B&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),z=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(z||B))throw W;if(f&&(!j||!z))Q={...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)Q={...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 Q={...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(Q.config,X,J,U.name);if(Y?.enabled&&Q)this.cacheResult(U.name||"",Q,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Sw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);Q.metrics=W}return Q}catch(Q){if(Q instanceof Error&&Q.name==="ConfigNotFoundError")throw Q;let W=Date.now()-$;throw Sw.error(`Configuration loading failed after ${W}ms:`,[Q instanceof Error?Q:Error(String(Q))]),Q}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:Q,checkEnv:W=!0,arrayStrategy:j="replace",verbose:B=!1}=w,f=J||_A.cwd(),z=[],G=await this.loadLocalConfiguration(A,X,f,U,Q,j,B,W,Y);if(G)return z.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,z,W,A,B);let T=await this.loadHomeConfiguration(A,X,Q,j,B,W);if(T)return z.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,z,W,A,B);let K=await this.loadPackageJsonConfiguration(A,X,f,Q,j,B,W);if(K)return z.push(Aw(f,"package.json")),this.finalizeResult(K,z,W,A,B);if(z.push(...this.getAllSearchPaths(A,X,f,U)),$)throw W1.configNotFound(A,z,X);return{...await this.applyEnvironmentVariables(A,Q,W,B),warnings:[`No configuration file found for "${A}"${$K(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,Q,W){let j=Q?fA(w,X,U):X,B=this.getLocalDirectories(Y,A);for(let f of B){if(U)Sw.info(`Searching for configuration in: ${f}`);let z=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(z,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Sw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?fA(w,Y,X):Y,Q=[Aw(t$(),".config",w),Aw(t$(),".config"),t$()];for(let W of Q){if(X)Sw.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths(w,W,$),B=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(B){if(X)Sw.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let Q=U?fA(w,A,J):A;try{let W=Aw(Y,"package.json");if(!r5(W))return null;let j={};try{j=JSON.parse(t5(W,"utf8"))}catch(z){if(J)Sw.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let B=j[w],f=w;if(!B&&$){let z=Array.isArray($)?$:[$];for(let G of z){if(!G)continue;if(j[G]){B=j[G],f=G;break}}}if(B&&typeof B==="object"&&!Array.isArray(B)){if(J)Sw.success(`Configuration loaded from package.json: ${f}`);return{config:SB(Q,B,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Sw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:fA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw W1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return TA.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);TA.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Aw(w,"config"),Aw(w,".config"),$?Aw(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Aw(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Aw(t$(),".config",w),Aw(t$(),".config"),t$()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}async function DB(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await hJ.loadConfig(w);else A=await hJ.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Sw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let Q=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await hJ.applyEnvironmentVariables(Q.name||"",$,!0,Q.verbose||!1))?.config??$;return $}}function fA(w,$,Y=!1){let A=new oJ,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,Q=[]){let W={...U};for(let[j,B]of Object.entries(U)){let f=[...Q,j],z=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((K)=>K.toUpperCase()).join("")}`,`${X}_${f.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of z)if(G=_A.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof B==="boolean")W[j]=["true","1","yes"].includes(G.toLowerCase());else if(typeof B==="number"){let K=Number(G);if(!Number.isNaN(K))W[j]=K}else if(Array.isArray(B))try{W[j]=JSON.parse(G)}catch{W[j]=G.split(",").map((K)=>K.trim())}else W[j]=G;else if(B&&typeof B==="object"&&!Array.isArray(B))W[j]=J(B,f)}return W}return J($)}var TA,gJ,Z6,x6=(w)=>w,i6=(w,$)=>{for(var Y in $)Z6(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:P6.bind($,Y)})},b6=(w,$)=>()=>(w&&($=w(w=0)),$),wB,jB,U1,wY,BB,fE,zE,bj,GA,ZJ,S0,s,GE,uj,EE,vj,KE,FE,IJ,TE,cj,mj,CJ,qE,NE,HE,RE,EA,fB,ME,O0,yE,IE,gj,KA,xJ,K0,b,CE,dj,VE,nj,LE,SE,VJ,OE,lj,pj,hE,LJ,_E,DE,kE,ZE,xE,FA,zB,PE,iE="0.15.6",a0,VA,o1,PJ,iJ,LA,bJ,uJ,e1,vJ,cJ,B$,GB,EB,Kw,cw,KB,FB,bE,vE,TB,SA,py,y0,c,ry,mE,ty,gE,ay,sy,rj,oy,dE,nE,ey,tj,wI,$I,YI,AI,XI,SJ,lE,JI,Fw,NB,OA,HB,RB,sJ,MB,yB,hA,IB,CB,W1,wK,Sw,hJ,BI,fI;var kB=a(()=>{TA=new aj,gJ=new sj,Z6=Object.defineProperty;wB={};i6(wB,{withErrorRecovery:()=>AB,tryLoadConfig:()=>WE,loadConfigWithResult:()=>JE,loadConfig:()=>QB,isRetryableError:()=>e6,isConfigNotFoundError:()=>o6,isBunfigError:()=>XB,globalPerformanceMonitor:()=>wY,globalCache:()=>U1,getEnvOrDefault:()=>wE,generateConfigTypes:()=>QE,defaultGeneratedDir:()=>FB,defaultConfigDir:()=>KB,deepMergeWithArrayStrategy:()=>rJ,deepMerge:()=>JB,createLibraryConfig:()=>jE,config:()=>UE,bunfigPlugin:()=>BE,applyEnvVarsToConfig:()=>a1,TypeGenerationError:()=>uJ,SchemaValidationError:()=>e1,PluginError:()=>cJ,PerformanceMonitor:()=>nJ,FileSystemError:()=>bJ,ErrorFactory:()=>B$,EnvVarError:()=>LA,EnvProcessor:()=>DA,ConfigValidator:()=>tJ,ConfigValidationError:()=>PJ,ConfigNotFoundError:()=>VA,ConfigMergeError:()=>iJ,ConfigLoader:()=>aJ,ConfigLoadError:()=>o1,ConfigFileLoader:()=>kA,ConfigCache:()=>dJ,CacheUtils:()=>BB,BunfigError:()=>a0,BrowserConfigError:()=>vJ,ArrayMergeStrategies:()=>GB});bE=b6(async()=>{jB=import.meta.require,U1=new dJ,wY=new nJ,BB={createKey:u6,isEquivalent:v6,estimateMemoryUsage:c6},fE=HA(DJ.cwd(),"config"),zE=HA(DJ.cwd(),"src/generated"),bj=NA.env.CLARITY_LOG_DIR||$6(d6(),"logs"),GA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:bj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},ZJ=await n6(),S0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},s=S0,GE=S0.red,uj=S0.green,EE=S0.yellow,vj=S0.blue,KE=S0.magenta,FE=S0.cyan,IJ=S0.white,TE=S0.gray,cj=S0.bgRed,mj=S0.bgYellow,CJ=S0.bold,qE=S0.dim,NE=S0.italic,HE=S0.underline,RE=S0.reset,EA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},fB={debug:"\uD83D\uDD0D",info:vj("ℹ"),success:uj("✓"),warning:mj(IJ(CJ(" WARN "))),error:cj(IJ(CJ(" ERROR ")))},ME=new yA("stacks"),O0=new yA("bunfig",{showTags:!0}),yE=v0(s1.cwd(),"config"),IE=v0(s1.cwd(),"src/generated"),gj=qA.env.CLARITY_LOG_DIR||e5(t6(),"logs"),KA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:gj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},xJ=await a6(),K0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},b=K0,CE=K0.red,dj=K0.green,VE=K0.yellow,nj=K0.blue,LE=K0.magenta,SE=K0.cyan,VJ=K0.white,OE=K0.gray,lj=K0.bgRed,pj=K0.bgYellow,hE=K0.bgGray,LJ=K0.bold,_E=K0.dim,DE=K0.italic,kE=K0.underline,ZE=K0.strikethrough,xE=K0.reset,FA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},zB={debug:"\uD83D\uDD0D",info:nj("ℹ"),success:dj("✓"),warning:pj(VJ(LJ(" WARN "))),error:lj(VJ(LJ(" ERROR ")))},PE=new CA("stacks"),a0=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},VA=class extends a0{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},o1=class extends a0{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},PJ=class extends a0{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},iJ=class extends a0{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},LA=class extends a0{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},bJ=class extends a0{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},uJ=class extends a0{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},e1=class extends a0{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},vJ=class extends a0{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},cJ=class extends a0{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},B$={configNotFound(w,$,Y){return new VA(w,$,Y)},configLoad(w,$,Y){return new o1(w,$,Y)},configValidation(w,$,Y){return new PJ(w,$,Y)},configMerge(w,$,Y,A){return new iJ(w,$,Y,A)},envVar(w,$,Y,A){return new LA(w,$,Y,A)},fileSystem(w,$,Y){return new bJ(w,$,Y)},typeGeneration(w,$,Y){return new uJ(w,$,Y)},schemaValidation(w,$,Y){return new e1(w,$,Y)},browserConfig(w,$,Y,A){return new vJ(w,$,Y,A)},plugin(w,$,Y){return new cJ(w,$,Y)}},GB={replace:"replace",concat:"concat",smart:"smart"},EB=/^https?:\/\//,Kw=new CA("bunfig",{showTags:!0}),cw=new aJ,KB=c0(_$.cwd(),"config"),FB=c0(_$.cwd(),"src/generated")});vE=RA.env.CLARITY_LOG_DIR||y6(uE(),"logs"),TB={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},SA={...TB},py=(async()=>{try{let{loadConfig:w}=await bE().then(()=>wB),$=await w({name:"clarity",alias:"logging",defaultConfig:TB,cwd:RA.cwd()});if($)Object.assign(SA,$)}catch{}return SA})();y0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},c=y0,ry=y0.red,mE=y0.green,ty=y0.yellow,gE=y0.blue,ay=y0.magenta,sy=y0.cyan,rj=y0.white,oy=y0.gray,dE=y0.bgRed,nE=y0.bgYellow,ey=y0.bgGray,tj=y0.bold,wI=y0.dim,$I=y0.italic,YI=y0.underline,AI=y0.strikethrough,XI=y0.reset,SJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lE={debug:"\uD83D\uDD0D",info:gE("ℹ"),success:mE("✓"),warning:nE(rj(tj(" WARN "))),error:dE(rj(tj(" ERROR ")))};JI=new ZA("stacks");Fw=class Fw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};NB=class NB extends Fw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};OA=class OA extends Fw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};HB=class HB extends Fw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};RB=class RB extends Fw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};sJ=class sJ extends Fw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};MB=class MB extends Fw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};yB=class yB extends Fw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};hA=class hA extends Fw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};IB=class IB extends Fw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};CB=class CB extends Fw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};W1={configNotFound(w,$,Y){return new NB(w,$,Y)},configLoad(w,$,Y){return new OA(w,$,Y)},configValidation(w,$,Y){return new HB(w,$,Y)},configMerge(w,$,Y,A){return new RB(w,$,Y,A)},envVar(w,$,Y,A){return new sJ(w,$,Y,A)},fileSystem(w,$,Y){return new MB(w,$,Y)},typeGeneration(w,$,Y){return new yB(w,$,Y)},schemaValidation(w,$,Y){return new hA(w,$,Y)},browserConfig(w,$,Y,A){return new IB(w,$,Y,A)},plugin(w,$,Y){return new CB(w,$,Y)}};wK=/^https?:\/\//;Sw=new ZA("bunfig",{showTags:!0});hJ=new _B;BI=Aw(_A.cwd(),"config"),fI=Aw(_A.cwd(),"src/generated")});import{homedir as eJ}from"node:os";import{join as wU,resolve as YK}from"node:path";async function xB(){if(!$U)$U=await DB({name:"rpx",cwd:YK(__dirname,".."),defaultConfig:ZB});return $U}var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",ZB,$U=null,mw;var xA=a(()=>{kB();ZB={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:wU(eJ(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:wU(eJ(),".stacks","ssl","stacks.localhost.crt"),keyPath:wU(eJ(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};mw=ZB});function Q1(w){return w.startsWith("*.")}function $Y(w,$){if(!Q1($))return!1;let Y=$.slice(1);return w.length>Y.length&&w.endsWith(Y)}function PB(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!Q1(J))continue;if($Y($,J)){let Q=J.length-1;if(Q>X)X=Q,A=U}}return A}import{existsSync as AK,readdirSync as XK,readFileSync as JK,statSync as UK}from"node:fs";import{homedir as bB}from"node:os";import{isAbsolute as WK,join as j1}from"node:path";function AU(w,$){if(w==="~")return $;if(w.startsWith("~/"))return j1($,w.slice(2));return w}function jK(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function PA(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function BK(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function fK(w,$){let Y=$.readText(j1(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(j1(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function zK(w){let $=w.selfRegisters??!1;return{command:w.command,env:w.env,urlEnv:w.urlEnv,selfRegisters:$,routes:w.routes??($?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function GK(w,$){let Y=fK(w,$);if(Y?.command)return zK(Y);let A=$.fileExists(j1(w,"buddy")),X=$.readText(j1(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((W)=>W==="stacks"||W.startsWith("@stacksjs/")))return{command:A?"./buddy dev":"bun run dev",env:{STACKS_PROXY_MANAGED:"1"},urlEnv:["APP_URL"],routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0},{path:"/api",portEnv:"PORT_API",defaultPort:3008,stripPrefix:!1,readyGate:!1},{path:"/docs",portEnv:"PORT_DOCS",defaultPort:3006,stripPrefix:!0,readyGate:!1}]};if(J?.scripts?.dev)return{command:"bun run dev",routes:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}]};return null}function XU(w,$={}){let Y={dirExists:$.dirExists??YU.dirExists,fileExists:$.fileExists??YU.fileExists,readText:$.readText??YU.readText},A=$.detect??GK,X=$.homeDir??bB(),J=w.tlds??vB,U=(w.roots??uB).map((z)=>AU(z,X)),Q=w.idleTimeoutMs??QK,W=new Map;for(let z of w.sites??[])W.set(z.to,z);let j=(z)=>z.idleTimeoutMs??Q;function B(z){let G=PB(W,z);if(!G)return null;let T=WK(G.dir)?G.dir:AU(G.dir,X),K=G.selfRegisters??!1,F=G.routes??[];if(!K&&F.length===0)F=A(T,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let q=iB({...G.env??{}},void 0,z);return{host:z,id:PA(z),dir:T,command:G.command,env:q,routes:F,selfRegisters:K,idleTimeoutMs:j(G),source:"config"}}function f(z){let G=BK(z,J);if(!G)return null;for(let T of U){let K=j1(T,G);if(!Y.dirExists(K))continue;let F=A(K,Y);if(!F)continue;let q=F.selfRegisters??!1;return{host:z,id:PA(z),dir:K,command:F.command,env:iB({...F.env??{}},F.urlEnv,z),routes:q?[]:F.routes??[],selfRegisters:q,idleTimeoutMs:Q,source:"discovered"}}return null}return{resolve(z){let G=jK(z);if(!G)return null;return B(G)??f(G)}}}function EK(w){try{return XK(w,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name)}catch{return[]}}function cB(w,$={}){let Y=$.homeDir??bB(),A=w.tlds??vB,X=(w.roots??uB).map((f)=>AU(f,Y)),J=$.readdir??EK,U=XU(w,$),Q=[],W=new Set,j=(f)=>{if(f&&!W.has(f.host))W.add(f.host),Q.push(f)};for(let f of w.sites??[])if(!f.to.includes("*"))j(U.resolve(f.to));let B=A[0]??"localhost";for(let f of X)for(let z of J(f))j(U.resolve(`${z}.${B}`));return Q}function iB(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}var uB,vB,QK=1800000,YU;var JU=a(()=>{uB=["~/Code"],vB=["localhost","test"],YU={dirExists:(w)=>{try{return UK(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return AK(w)}catch{return!1}},readText:(w)=>{try{return JK(w,"utf8")}catch{return null}}}});var H;var k$=a(()=>{H={info:(...w)=>console.log("[info]",...w),success:(...w)=>console.log("[success]",...w),warn:(...w)=>console.warn("[warn]",...w),error:(...w)=>console.error("[error]",...w),debug:(...w)=>console.debug("[debug]",...w),log:(...w)=>console.log(...w),start:(...w)=>console.log("[start]",...w),box:(...w)=>console.log("[box]",...w)}});import{createRequire as KK}from"node:module";import{Resolver as UU}from"node:dns/promises";import{createHash as TK,sign as qK}from"node:crypto";import{createHash as NK}from"node:crypto";import{sign as HK}from"node:crypto";import{generateKeyPairSync as rf,X509Certificate as OK}from"node:crypto";import WU from"node:os";import QU from"node:path";import{existsSync as gB,statSync as dB}from"fs";import{existsSync as _K,mkdirSync as ZI,readdirSync as xI,readFileSync as DK,writeFileSync as PI}from"fs";import{homedir as B1}from"os";import{dirname as uI,resolve as Ww}from"path";import yX from"process";import{existsSync as nB,statSync as lB}from"fs";import{existsSync as DU,mkdirSync as kK,readdirSync as ZK,writeFileSync as xK}from"fs";import{homedir as f1}from"os";import{dirname as pB,resolve as g0}from"path";import x$ from"process";import{join as PK,relative as iK,resolve as rB}from"path";import UX from"process";import{existsSync as tf,mkdirSync as tI,readdirSync as aI,writeFileSync as sI}from"fs";import{homedir as jU}from"os";import{dirname as w4,resolve as m0}from"path";import UY from"process";import{join as bK,relative as uK,resolve as tB}from"path";import WX from"process";import{existsSync as af,mkdirSync as J4,readdirSync as U4,writeFileSync as W4}from"fs";import{dirname as j4,resolve as QX}from"path";import kU from"process";import{Buffer as f$}from"buffer";import{createCipheriv as vK,createDecipheriv as cK,randomBytes as BU}from"crypto";import{closeSync as fU,createReadStream as aB,createWriteStream as mK,existsSync as zU,fsyncSync as sB,openSync as oB,writeFileSync as gK}from"fs";import{access as dK,constants as eB,mkdir as nK,readdir as iA,rename as wf,stat as z1,unlink as bA,writeFile as GU}from"fs/promises";import{join as G1}from"path";import h0 from"process";import{pipeline as lK}from"stream/promises";import{createGzip as $f}from"zlib";import E1 from"process";import lw from"process";import{Buffer as gw}from"buffer";import{createCipheriv as pK,createDecipheriv as rK,randomBytes as EU}from"crypto";import{closeSync as KU,createReadStream as Yf,createWriteStream as tK,existsSync as uA,fsyncSync as Af,openSync as Xf,writeFileSync as aK}from"fs";import{access as sK,constants as Jf,mkdir as oK,readdir as vA,rename as Uf,stat as K1,unlink as cA,writeFile as FU}from"fs/promises";import{isAbsolute as eK,join as F1,resolve as wF}from"path";import n from"process";import{pipeline as $F}from"stream/promises";import{createGzip as Wf}from"zlib";import T1 from"process";import pw from"process";import mA from"process";import{existsSync as gA}from"fs";import{resolve as TU}from"path";import{existsSync as YF}from"fs";import{existsSync as AF,readdirSync as XF}from"fs";import{extname as qU,resolve as Qf}from"path";import JF from"process";import{join as UF,relative as WF,resolve as jf}from"path";import jX from"process";import{Buffer as dw}from"buffer";import{createCipheriv as QF,createDecipheriv as jF,randomBytes as NU}from"crypto";import{closeSync as HU,createReadStream as Bf,createWriteStream as BF,existsSync as dA,fsyncSync as ff,openSync as zf,writeFileSync as fF}from"fs";import{access as zF,constants as Gf,mkdir as GF,readdir as nA,rename as Ef,stat as q1,unlink as lA,writeFile as RU}from"fs/promises";import{isAbsolute as EF,join as N1,resolve as KF}from"path";import l from"process";import{pipeline as FF}from"stream/promises";import{createGzip as Kf}from"zlib";import H1 from"process";import rw from"process";import pA from"process";import{existsSync as rA}from"fs";import{resolve as MU}from"path";import{existsSync as TF}from"fs";import{exec as uT}from"node:child_process";import dU from"node:fs";import vT from"node:os";import Tw from"node:path";import D9 from"node:process";import{promisify as cT}from"node:util";import I1 from"node:crypto";import tw from"node:fs";import pU from"node:path";import B7 from"node:crypto";import{execSync as G7}from"node:child_process";import RX from"node:os";async function sA(w,$={},Y=30000){try{return await fetch(w,{...$,signal:AbortSignal.timeout(Y)})}catch(A){if(A&&typeof A==="object"&&A.name==="TimeoutError"){let X=Error(`ACME HTTP request to ${w} timed out after ${Y}ms`);throw X.name="AcmeRequestTimeoutError",X}throw A}}async function Zf(w,$,Y={}){let A=Y.timeoutMs??120000,X=Y.intervalMs??3000,J=w.split(".").slice(-2).join("."),U;try{let j=new UU,B=await j.resolveNs(J),f=(await Promise.all(B.map((z)=>j.resolve4(z).catch(()=>[])))).flat();if(f.length>0)U=new UU,U.setServers(f)}catch{}let Q=Date.now()+A,W=U??new UU;for(;;){try{if((await W.resolveTxt(w)).some((j)=>j.join("")===$))return!0}catch{}if(Date.now()>=Q)return!1;await new Promise((j)=>setTimeout(j,X))}}class JY{tokens=new Map;add(w,$){this.tokens.set(w,$)}get(w){return this.tokens.get(w)}remove(w){this.tokens.delete(w)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath(w){let $=w.indexOf(JY.PATH_PREFIX);if($===-1)return;let Y=w.slice($+JY.PATH_PREFIX.length);return this.get(Y)}}function oA(w){return(typeof w==="string"?Buffer.from(w,"utf8"):Buffer.from(w)).toString("base64url")}function SU(w){return Buffer.from(w,"base64url")}function xf(w){let $=w.export({format:"jwk"});if($.kty!=="EC"||$.crv!=="P-256"||!$.x||!$.y)throw Error(`Expected a P-256 EC public key, got kty=${$.kty} crv=${$.crv}`);return{crv:"P-256",kty:"EC",x:$.x,y:$.y}}function Pf(w){let $=`{"crv":"${w.crv}","kty":"${w.kty}","x":"${w.x}","y":"${w.y}"}`;return TK("sha256").update($).digest("base64url")}function bf(w){let{protectedHeader:$,payload:Y,privateKey:A}=w,X=oA(JSON.stringify($)),J=Y===""?"":oA(JSON.stringify(Y)),U=`${X}.${J}`,Q=qK("sha256",Buffer.from(U),{key:A,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:oA(Q)}}class JX{directoryUrl;accountKey;jwk;thumbprint;requestTimeoutMs;directoryCache;nonce;accountKid;constructor(w){this.directoryUrl=w.directoryUrl,this.accountKey=w.accountKey,this.jwk=xf(w.accountPublicKey),this.thumbprint=Pf(this.jwk),this.requestTimeoutMs=w.requestTimeoutMs??kf}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let w=await sA(this.directoryUrl,{},this.requestTimeoutMs);if(!w.ok)throw Error(`Failed to fetch ACME directory: HTTP ${w.status}`);return this.directoryCache=await w.json(),this.directoryCache}async newNonce(){let w=await this.directory(),$=(await sA(w.newNonce,{method:"HEAD"},this.requestTimeoutMs)).headers.get("replay-nonce");if(!$)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=$,$}async ensureNonce(){if(this.nonce){let w=this.nonce;return this.nonce=void 0,w}return this.newNonce()}async signedPost(w){let{url:$,payload:Y,useJwk:A}=w,X={alg:"ES256",nonce:await this.ensureNonce(),url:$};if(A)X.jwk=this.jwk;else X.kid=this.requireKid();let J=bf({protectedHeader:X,payload:Y,privateKey:this.accountKey}),U=await sA($,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)},this.requestTimeoutMs),Q=U.headers.get("replay-nonce");if(Q)this.nonce=Q;let W=U.headers.get("content-type")??"",j;if(W.includes("application/pem-certificate-chain")||W.startsWith("text/"))j=await U.text();else{let B=await U.text();j=B?JSON.parse(B):{}}if(U.status>=400){let B=j??{};throw new XX(`ACME request to ${$} failed (HTTP ${U.status}): ${B.type??""} ${B.detail??""}`.trim(),B,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(w={}){let $=await this.directory(),Y={termsOfServiceAgreed:!0};if(w.email)Y.contact=[`mailto:${w.email}`];let A=await this.signedPost({url:$.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder(w){let $=await this.directory(),Y={identifiers:w.map((X)=>({type:"dns",value:X}))},A=await this.signedPost({url:$.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization(w){return(await this.signedPost({url:w,payload:""})).body}keyAuthorization(w){return`${w}.${this.thumbprint}`}dns01TxtValue(w){return NK("sha256").update(this.keyAuthorization(w)).digest("base64url")}async notifyChallengeReady(w){await this.signedPost({url:w,payload:{}})}async pollAuthorization(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getAuthorization(w);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((Q)=>Q.status==="invalid");throw new XX(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await mB(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${w} to become valid`)}async finalizeOrder(w,$){return(await this.signedPost({url:w,payload:{csr:$}})).body}async getOrder(w){return(await this.signedPost({url:w,payload:""})).body}async pollOrder(w,$={}){let Y=$.timeoutMs??60000,A=$.intervalMs??2000,X=Date.now()+Y;while(Date.now()<X){let J=await this.getOrder(w);if(J.status==="valid"){if(!J.certificate)throw Error("ACME order is valid but has no certificate URL");return J.certificate}if(J.status==="invalid")throw Error(`ACME order ${w} became invalid`);await mB(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${w} to become valid`)}async downloadCertificate(w){let $=await this.signedPost({url:w,payload:""});return typeof $.body==="string"?$.body:String($.body)}static selectChallenge(w,$){let Y=w.challenges.find((A)=>A.type===$);if(!Y)throw Error(`No ${$} challenge available for ${w.identifier.value}`);return Y}}function cf(w){let $=w.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=$[0];if(!Y)return{certPem:`${w.trim()}
64
62
  `,chainPem:""};let A=`${Y.trim()}
65
63
  `,X=$.slice(1).map((J)=>J.trim()).join(`
66
64
  `);return{certPem:A,chainPem:X?`${X}
67
- `:""}}function Wz(w){return`_acme-challenge.${w.startsWith("*.")?w.slice(2):w}`}function B9(w){return new Promise(($)=>setTimeout($,w))}function rF(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function R$(w,$){return Buffer.concat([Buffer.from([w]),rF($.length),$])}function Bz(w){let $;if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=[],A=w;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);$=Buffer.from(Y)}else if($=w.length===0?Buffer.from([0]):w,$[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return R$(2,$)}function v$(w){let $=w.split(".").map(Number);if($.length<2)throw Error(`Invalid OID: ${w}`);let Y=[40*$[0]+$[1]];for(let A=2;A<$.length;A++){let X=$[A],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);Y.push(...J)}return R$(6,Buffer.from(Y))}function Qw(...w){return R$(48,Buffer.concat(w))}function lU(...w){return R$(49,Buffer.concat(w))}function nU(w){return R$(3,Buffer.concat([Buffer.from([0]),w]))}function jz(w){return R$(4,w)}function zz(w){return R$(12,Buffer.from(w,"utf8"))}function pU(w,$,Y){let A=128|(Y?32:0)|w;return R$(A,$)}function $q(w){let $=w.export({format:"jwk"});if(!$.x||!$.y)throw Error("Public key JWK is missing x/y coordinates");let Y=dU($.x),A=dU($.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 Gz(w){let{domains:$,publicKey:Y,privateKey:A}=w;if($.length===0)throw Error("At least one domain is required to build a CSR");let X=Qw(lU(Qw(v$(oF),zz($[0])))),J=Qw(Qw(v$(tF),v$(aF)),nU($q(Y))),U=$.map((q)=>pU(2,Buffer.from(q,"ascii"),!1)),W=Qw(...U),Q=Qw(v$(wq),jz(W)),B=Qw(Q),j=Qw(v$(eF),lU(B)),z=pU(0,j,!0),G=Qw(Bz(0),X,J,z),K=pF("sha256",G,A),E=Qw(v$(sF));return Qw(G,E,nU(K))}function Kz(w){return Gz(w).toString("base64url")}function Aq(w){if(w){let{createPrivateKey:X,createPublicKey:J}=gF("node:crypto"),U=X(w),W=J(U.export({format:"pem",type:"pkcs8"}));return{privateKey:U,publicKey:W,pem:w}}let{privateKey:$,publicKey:Y}=Fz("ec",{namedCurve:"P-256"}),A=$.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:$,publicKey:Y,pem:A}}async function jQ(w){let{domains:$,method:Y}=w;if($.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!w.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if($.some((z)=>z.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=w.directoryUrl??(w.staging===!1?Uz:Jz),X=Aq(w.accountKeyPem),J=new EX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey,requestTimeoutMs:w.requestTimeoutMs});await J.newAccount({email:w.email});let{order:U,orderUrl:W}=await J.newOrder($),Q=w.http01Store??DX,B=[],j=[];try{for(let T of U.authorizations){let M=await J.getAuthorization(T);if(M.status==="valid")continue;let V=EX.selectChallenge(M,Y);if(Y==="dns-01"){let S=Wz(M.identifier.value),U0=J.dns01TxtValue(V.token);await w.dnsProvider.setTxt(S,U0),B.push({name:S,value:U0}),await $z(S,U0,{timeoutMs:w.dnsPropagationTimeoutMs??120000})}else Q.add(V.token,J.keyAuthorization(V.token)),j.push(V.token);await J.notifyChallengeReady(V.url),await J.pollAuthorization(T,{timeoutMs:w.timeoutMs})}let{privateKey:z,publicKey:G}=Fz("ec",{namedCurve:"P-256"}),K=Kz({domains:$,publicKey:G,privateKey:z});await J.finalizeOrder(U.finalize,K);let E=await J.pollOrder(W,{timeoutMs:w.timeoutMs}),q=await J.downloadCertificate(E),{certPem:N,chainPem:f}=Qz(q),R=f?`${N}${f}`:N,O=z.export({format:"pem",type:"pkcs8"}).toString(),y=new Date(new Yq(N).validTo);return{certPem:N,keyPem:O,chainPem:f,fullChainPem:R,accountKeyPem:X.pem,notAfter:y}}finally{for(let{name:z,value:G}of B)await w.dnsProvider?.removeTxt(z,G).catch(()=>{});for(let z of j)Q.remove(z)}}class Ez{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!j9(w))return!0;return z9(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=j9(Y)?z9(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class fz{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function pq(w,$){this[w]=nq.bind(null,$)}class GQ{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!G9(w))return!0;return K9(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=G9(Y)?K9(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class KQ{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function aq(w,$={}){let Y=Object.keys($).sort().map((A)=>`${A}:${$[A]}`).join("|");return Y?`${w}:${Y}`:w}function sq(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function oq(w){return w.getStats().size*2}function FQ(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&$0($[0])&&"id"in $[0]&&$[0].id===3&&$0($[1])&&"id"in $[1]&&$[1].id===4)return $;if($0($)&&$0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if($0(w)&&"arr"in w&&Array.isArray(w.arr)&&$0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&$0($[0])&&$0(w[0])){let A=[...$];for(let X of w)if($0(X)&&"name"in X){if(!A.find((J)=>$0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if($0(X)&&"path"in X){if(!A.find((J)=>$0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>IX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!$0($)||!$0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if($0(X)&&$0(Y[A]))Y[A]=FQ(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((W)=>IX(W,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 IX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!IX(w[Y],$[Y]))return!1;return!0}if($0(w)&&$0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!IX(w[X],$[X]))return!1}return!0}return!1}function $0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function eq(w,$){if(!Nz(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return FQ($,A)}catch{return null}}catch{return null}}async function wN({name:w="",cwd:$,defaultConfig:Y}){let A=$||tU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let W of X){let Q=HX(A,`${U}${W}`),B=await eq(Q,Y);if(B!==null)return B}try{let U=HX(A,"package.json");if(Nz(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return FQ(Y,W)}catch{}}}catch{}return Y}function $N(w,$={}){let Y=TX.cwd();while(Y.includes("storage"))Y=N9(Y,"..");let A=N9(Y,w||"");if($?.relative)return Gq(TX.cwd(),A);return A}async function YN(){try{let w=await wN({name:"clarity",defaultConfig:GX,cwd:TX.cwd(),endpoint:"",headers:{}});return{...GX,...w}}catch{return GX}}function W0(){if(aw.env.NODE_ENV==="test"||aw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function AN(){if(aw.env.NODE_ENV==="test"||aw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof aw<"u"){let w=aw.type;if(w==="renderer"||w==="worker")return!1;return!!(aw.versions&&(aw.versions.node||aw.versions.bun))}return!1}class Hz{async format(w){let $=await AN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:R1.pid,hostname:$(),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 VX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...sU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Hz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??S0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...KX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...KX};return{...KX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:sU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Eq(this.config.logDirectory,H9.F_OK|H9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await fq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:f$.from(w);try{if(!LU(this.currentLogFile))await _U(this.currentLogFile,"",{mode:420});if(A=T9(this.currentLogFile,"a",420),Nq(A,W,{flag:"a"}),f9(A),A!==void 0)OU(A),A=void 0;if((await T1(this.currentLogFile)).size===0){if(await _U(this.currentLogFile,W,{flag:"w",mode:420}),(await T1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let B=Q;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(X<J-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,j);let z=U*2**X;await new Promise((G)=>setTimeout(G,z)),X++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{OU(A)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(X===J-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}X++;let Q=U*2**(X-1);await new Promise((B)=>setTimeout(B,Q))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return H1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return H1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return H1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return 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 w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=yU(16),A=Kq("aes-256-gcm",$,Y),X=f$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:f$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=M9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(f$.from(f$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(W0())return;let w=await T1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await tA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await T1(Y).catch(()=>null))try{if(await R9(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await aA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await _U(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await T1(Y).catch(()=>null))await R9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await tA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await aA(H1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=E9(w),A=qq($),X=M9();await Tq(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),LU(this.currentLogFile))try{let w=T9(this.currentLogFile,"r+");f9(w),OU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await tA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await aA(H1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?s.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=S0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${s.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!W0()){let B=Sz[w],j=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:s.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:s.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z),W){let G=W.split(`
68
- `);for(let K of G)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:s.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!W0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let Q=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
69
- `;if(W)Q+=`${W}
70
- `;Q=Q.replace(this.ANSI_PATTERN,""),await this.writeToFile(Q)}time(w){let $=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(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
71
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.fancy&&!W0()){let B=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:s.green("✓"),tag:B,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!W0())console.error(Q.trim());await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new VX($,{...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(!LU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return E9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=f$.isBuffer(w)?w:f$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),W=Fq("aes-256-gcm",Y,X);return W.setAuthTag(J),f$.concat([W.update(U),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return W0()}isServerMode(){return!W0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!W0()){let J=w.split(`
72
- `),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,Q=`└${"─".repeat(U)}┘`,B=J.map((j)=>{let z=" ".repeat(U-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:s.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(Q),showTimestamp:!1}))}else if(!W0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
73
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(W0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${s.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();S0.stdin.removeListener("data",Y);try{if(typeof S0.stdin.setRawMode==="function")S0.stdin.setRawMode(!1)}catch{}S0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof S0.stdin.setRawMode==="function")S0.stdin.setRawMode(!0)}catch{}S0.stdin.resume(),S0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let X=/%([sdijfo%])/g,J=0;if(Y=w.replace(X,(U,W)=>{if(W==="%")return"%";if(J>=$.length)return U;let Q=$[J++];switch(W){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return U}}),J<$.length)Y+=` ${$.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!W0()){let X=this.options.showTags!==!1&&this.name?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
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress(w,$=""){if(!this.enabled||!this.fancy||W0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,X)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,A)),X!==void 0)this.activeProgressBar.message=X;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,A!==void 0)this.activeProgressBar.message=A;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(A,X="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;S0.stdout.write(`${"\r".padEnd(S0.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()||!S0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=s.green("━".repeat(A)),U=s.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=$||Y===100?s.green("✓"):s.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${s.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=S0.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,S0.stdout.write(w.lastRenderedLine),$)S0.stdout.write(`
75
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||W0()||!S0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await tA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=H1(this.config.logDirectory,A);if(w.before)try{if((await T1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await aA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function zX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&p($[0])&&"id"in $[0]&&$[0].id===3&&p($[1])&&"id"in $[1]&&$[1].id===4)return $;if(p($)&&p(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(p(w)&&"arr"in w&&Array.isArray(w.arr)&&p($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&p($[0])&&p(w[0])){let A=[...$];for(let X of w)if(p(X)&&"name"in X){if(!A.find((J)=>p(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(p(X)&&"path"in X){if(!A.find((J)=>p(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>CX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!p($)||!p(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(p(X)&&p(Y[A]))Y[A]=zX(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((W)=>p(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((W)=>p(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((W)=>CX(W,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 qQ(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:zX(w,$);if(Array.isArray(w))return Y==="replace"?$:zX(w,$);if(!p($)||!p(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=zX(U,J);else if(p(J)&&p(U))A[X]=qQ(U,J,Y);else A[X]=J}return A}function CX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!CX(w[Y],$[Y]))return!1;return!0}if(p(w)&&p($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!CX(w[X],$[X]))return!1}return!0}return!1}function p(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function QX(w,$,Y="replace"){if(!qz(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return qQ($,X,Y)}catch{return null}}catch{return null}}function XN(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${z.map(G).join("_")}`,E=`${A}_${z.map((q)=>q.toUpperCase()).join("_")}`;if(Y)k0.info(`Checking environment variable ${K} for config ${w}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))Q[B]=J(j,z);else{let q=VY.env[K]||VY.env[E];if(q!==void 0){if(Y)k0.info(`Using environment variable ${q?K:E} for config ${w}.${z.join(".")}`);if(typeof j==="number")Q[B]=Number(q);else if(typeof j==="boolean")Q[B]=q.toLowerCase()==="true";else if(Array.isArray(j))try{let N=JSON.parse(q);if(Array.isArray(N))Q[B]=N;else Q[B]=q.split(",").map((f)=>f.trim())}catch{Q[B]=q.split(",").map((N)=>N.trim())}else Q[B]=q}}}return Q}return J(X)}async function JN({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let Q=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?XN(w,X,J):X,B=Y||VY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)k0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${B}`);let z=[w,`.${w}`].filter(Boolean),G=[`${w}.config`,`.${w}.config`].filter(Boolean),K=$?[$,`.${$}`]:[],E=$?[`${$}.config`,`.${$}.config`]:[],q=Array.from(new Set([B,g0(B,"config"),g0(B,".config"),A?g0(B,A):void 0].filter(Boolean)));for(let N of q){if(J)k0.info(`Searching for configuration in: ${N}`);let f=[g0(B,"config"),g0(B,".config")].concat(A?[g0(B,A)]:[]).includes(N)?[...z,...G,...K,...E]:[...G,...z,...E,...K];for(let R of f)for(let O of j){let y=g0(N,`${R}${O}`),T=await QX(y,Q,W);if(T!==null){if(J)k0.success(`Configuration loaded from: ${y}`);return T}}}if(w){let N=g0(CU(),".config",w),f=["config",`${w}.config`];if($)f.push(`${$}.config`);if(J)k0.info(`Checking user config directory: ${N}`);for(let R of f)for(let O of j){let y=g0(N,`${R}${O}`),T=await QX(y,Q,W);if(T!==null){if(J)k0.success(`Configuration loaded from user config directory: ${y}`);return T}}}if(w){let N=g0(CU(),".config"),f=[`.${w}.config`];if($)f.push(`.${$}.config`);if(J)k0.info(`Checking user config directory for dotfile configs: ${N}`);for(let R of f)for(let O of j){let y=g0(N,`${R}${O}`),T=await QX(y,Q,W);if(T!==null){if(J)k0.success(`Configuration loaded from user config directory dotfile: ${y}`);return T}}}if(w){let N=CU(),f=[`.${w}.config`,`.${w}`];if($)f.push(`.${$}.config`),f.push(`.${$}`);if(J)k0.info(`Checking user home directory for dotfile configs: ${N}`);for(let R of f)for(let O of j){let y=g0(N,`${R}${O}`),T=await QX(y,Q,W);if(T!==null){if(J)k0.success(`Configuration loaded from user home directory: ${y}`);return T}}}try{let N=g0(B,"package.json");if(qz(N)){let f=await import(N),R=f[w];if(!R&&$){if(R=f[$],R&&J)k0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)k0.success(`Configuration loaded from package.json: ${R===f[w]?w:$}`);return qQ(Q,R,W)}catch(O){if(J)k0.warn("Failed to merge package.json config:",O)}}}catch(N){if(J)k0.warn("Failed to load package.json:",N)}if(J)k0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return Q}function UN(w,$={}){let Y=fX.cwd();while(Y.includes("storage"))Y=q9(Y,"..");let A=q9(Y,w||"");if($?.relative)return jq(fX.cwd(),A);return A}async function QN(){try{let w=await JN({name:"clarity",alias:"logging",defaultConfig:FX,cwd:fX.cwd()});return{...FX,...w||{}}}catch{return FX}}function E0(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function WN(){if(sw.env.NODE_ENV==="test"||sw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof sw<"u"){let w=sw.type;if(w==="renderer"||w==="worker")return!1;return!!(sw.versions&&(sw.versions.node||sw.versions.bun))}return!1}class Rz{async format(w){let $=await WN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:V1.pid,hostname:$(),environment:V1.env.NODE_ENV||"development",platform:V1.platform,version:V1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:V1.env.NODE_ENV||V1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...oU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Rz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...qX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...qX};return{...qX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:oU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!E0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await Vq(this.config.logDirectory,y9.F_OK|y9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await Cq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:pw.from(w);try{if(!sA(this.currentLogFile))await kU(this.currentLogFile,"",{mode:420});if(A=C9(this.currentLogFile,"a",420),Iq(A,W,{flag:"a"}),V9(A),A!==void 0)ZU(A),A=void 0;if((await M1(this.currentLogFile)).size===0){if(await kU(this.currentLogFile,W,{flag:"w",mode:420}),(await M1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let B=Q;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(X<J-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,j);let z=U*2**X;await new Promise((G)=>setTimeout(G,z)),X++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{ZU(A)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(X===J-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}X++;let Q=U*2**(X-1);await new Promise((B)=>setTimeout(B,Q))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return I1(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 I1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return I1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(E0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return SU(16).toString("hex")}generateKey(){return SU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=SU(16),A=Hq("aes-256-gcm",$,Y),X=pw.isBuffer(w)?w:pw.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=pw.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=L9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(pw.from(pw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(E0())return;if(!this.shouldWriteToFile())return;let w=await M1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await oA(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await M1(Y).catch(()=>null))try{if(await O9(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await eA(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await kU(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await M1(Y).catch(()=>null))await O9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await oA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await eA(I1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=I9(w),A=Mq($),X=L9();await Lq(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),sA(this.currentLogFile))try{let w=C9(this.currentLogFile,"r+");V9(w),ZU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!E0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await oA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await eA(I1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?c.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||E0())return!1;let w=typeof l.env.NO_COLOR<"u",$=l.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof l.stderr<"u"&&l.stderr.isTTY||typeof l.stdout<"u"&&l.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=l.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${c.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=c.underline(c.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),$}supportsHyperlinks(){if(E0())return!1;let w=l.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=l.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(yq($)||$.startsWith("./")||$.startsWith("../"))$=Oq($);else return null;return sA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":Zz[w],G=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:c.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:c.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
76
- `);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:c.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!E0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
77
- `;if(W)j+=`${W}
78
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!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
- `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!E0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":c.blue("◐"),tag:Y,message:`${c.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
80
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":c.green("✓"),tag:B,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!E0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new yX($,{...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(!sA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return I9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=pw.isBuffer(w)?w:pw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=Rq("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=pw.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return E0()}isServerMode(){return!E0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
81
- `),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(j),showTimestamp:!1}))}else if(!E0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
82
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(E0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${c.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();l.stdin.removeListener("data",Y);try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!1)}catch{}l.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!0)}catch{}l.stdin.resume(),l.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,W=0;if(Y=w.replace(U,(Q,B)=>{if(B==="%")return"%";if(W>=$.length)return Q;let j=$[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return Q}}),W<$.length)Y+=` ${$.slice(W).map((Q)=>typeof Q==="object"?JSON.stringify(Q,null,2):String(Q)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${W}${U} ${c.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
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(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=c.green("━".repeat(A)),U=c.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?c.green("✓"):c.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=l.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,l.stdout.write(w.lastRenderedLine),$)l.stdout.write(`
84
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||E0()||!l.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(E0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await oA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=I1(this.config.logDirectory,A);if(w.before)try{if((await M1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await eA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function Mz(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function Iz(w){return w instanceof e0}function BN(w){return w instanceof OX}function jN(w){if(Iz(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some(($)=>w.message.toLowerCase().includes($.toLowerCase()))}class PX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return LY.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=wX.env[Q]||(B?wX.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=wX.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof LX)throw z;throw H$.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw H$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(wX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
65
+ `:""}}function mf(w){return`_acme-challenge.${w.startsWith("*.")?w.slice(2):w}`}function mB(w){return new Promise(($)=>setTimeout($,w))}function RK(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function E$(w,$){return Buffer.concat([Buffer.from([w]),RK($.length),$])}function gf(w){let $;if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=[],A=w;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);$=Buffer.from(Y)}else if($=w.length===0?Buffer.from([0]):w,$[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return E$(2,$)}function Z$(w){let $=w.split(".").map(Number);if($.length<2)throw Error(`Invalid OID: ${w}`);let Y=[40*$[0]+$[1]];for(let A=2;A<$.length;A++){let X=$[A],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);Y.push(...J)}return E$(6,Buffer.from(Y))}function Uw(...w){return E$(48,Buffer.concat(w))}function OU(...w){return E$(49,Buffer.concat(w))}function hU(w){return E$(3,Buffer.concat([Buffer.from([0]),w]))}function df(w){return E$(4,w)}function nf(w){return E$(12,Buffer.from(w,"utf8"))}function _U(w,$,Y){let A=128|(Y?32:0)|w;return E$(A,$)}function SK(w){let $=w.export({format:"jwk"});if(!$.x||!$.y)throw Error("Public key JWK is missing x/y coordinates");let Y=SU($.x),A=SU($.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 lf(w){let{domains:$,publicKey:Y,privateKey:A}=w;if($.length===0)throw Error("At least one domain is required to build a CSR");let X=Uw(OU(Uw(Z$(CK),nf($[0])))),J=Uw(Uw(Z$(MK),Z$(yK)),hU(SK(Y))),U=$.map((K)=>_U(2,Buffer.from(K,"ascii"),!1)),Q=Uw(...U),W=Uw(Z$(LK),df(Q)),j=Uw(W),B=Uw(Z$(VK),OU(j)),f=_U(0,B,!0),z=Uw(gf(0),X,J,f),G=HK("sha256",z,A),T=Uw(Z$(IK));return Uw(z,T,hU(G))}function pf(w){return lf(w).toString("base64url")}function hK(w){if(w){let{createPrivateKey:X,createPublicKey:J}=FK("node:crypto"),U=X(w),Q=J(U.export({format:"pem",type:"pkcs8"}));return{privateKey:U,publicKey:Q,pem:w}}let{privateKey:$,publicKey:Y}=rf("ec",{namedCurve:"P-256"}),A=$.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:$,publicKey:Y,pem:A}}async function rU(w){let{domains:$,method:Y}=w;if($.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!w.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if($.some((f)=>f.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=w.directoryUrl??(w.staging===!1?vf:uf),X=hK(w.accountKeyPem),J=new JX({directoryUrl:A,accountKey:X.privateKey,accountPublicKey:X.publicKey,requestTimeoutMs:w.requestTimeoutMs});await J.newAccount({email:w.email});let{order:U,orderUrl:Q}=await J.newOrder($),W=w.http01Store??MX,j=[],B=[];try{for(let N of U.authorizations){let M=await J.getAuthorization(N);if(M.status==="valid")continue;let C=JX.selectChallenge(M,Y);if(Y==="dns-01"){let h=mf(M.identifier.value),J0=J.dns01TxtValue(C.token);await w.dnsProvider.setTxt(h,J0),j.push({name:h,value:J0}),await Zf(h,J0,{timeoutMs:w.dnsPropagationTimeoutMs??120000})}else W.add(C.token,J.keyAuthorization(C.token)),B.push(C.token);await J.notifyChallengeReady(C.url),await J.pollAuthorization(N,{timeoutMs:w.timeoutMs})}let{privateKey:f,publicKey:z}=rf("ec",{namedCurve:"P-256"}),G=pf({domains:$,publicKey:z,privateKey:f});await J.finalizeOrder(U.finalize,G);let T=await J.pollOrder(Q,{timeoutMs:w.timeoutMs}),K=await J.downloadCertificate(T),{certPem:F,chainPem:q}=cf(K),R=q?`${F}${q}`:F,L=f.export({format:"pem",type:"pkcs8"}).toString(),V=new Date(new OK(F).validTo);return{certPem:F,keyPem:L,chainPem:q,fullChainPem:R,accountKeyPem:X.pem,notAfter:V}}finally{for(let{name:f,value:z}of j)await w.dnsProvider?.removeTxt(f,z).catch(()=>{});for(let f of B)W.remove(f)}}class sf{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!gB(w))return!0;return dB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=gB(Y)?dB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class of{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function HF(w,$){this[w]=NF.bind(null,$)}class aU{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!nB(w))return!0;return lB(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=nB(Y)?lB(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class sU{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function yF(w,$={}){let Y=Object.keys($).sort().map((A)=>`${A}:${$[A]}`).join("|");return Y?`${w}:${Y}`:w}function IF(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function CF(w){return w.getStats().size*2}function oU(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&Y0($[0])&&"id"in $[0]&&$[0].id===3&&Y0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(Y0($)&&Y0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(Y0(w)&&"arr"in w&&Array.isArray(w.arr)&&Y0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&Y0($[0])&&Y0(w[0])){let A=[...$];for(let X of w)if(Y0(X)&&"name"in X){if(!A.find((J)=>Y0(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(Y0(X)&&"path"in X){if(!A.find((J)=>Y0(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>fX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!Y0($)||!Y0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=oU(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((Q)=>Y0(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(Y0(U)&&"path"in U){if(!J.find((Q)=>Y0(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((Q)=>fX(Q,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 fX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!fX(w[Y],$[Y]))return!1;return!0}if(Y0(w)&&Y0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!fX(w[X],$[X]))return!1}return!0}return!1}function Y0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function VF(w,$){if(!af(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return oU($,A)}catch{return null}}catch{return null}}async function LF({name:w="",cwd:$,defaultConfig:Y}){let A=$||kU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let Q of X){let W=QX(A,`${U}${Q}`),j=await VF(W,Y);if(j!==null)return j}try{let U=QX(A,"package.json");if(af(U)){let Q=(await import(U))[w];if(Q&&typeof Q==="object"&&!Array.isArray(Q))try{return oU(Y,Q)}catch{}}}catch{}return Y}function SF(w,$={}){let Y=WX.cwd();while(Y.includes("storage"))Y=tB(Y,"..");let A=tB(Y,w||"");if($?.relative)return uK(WX.cwd(),A);return A}async function OF(){try{let w=await LF({name:"clarity",defaultConfig:wX,cwd:WX.cwd(),endpoint:"",headers:{}});return{...wX,...w}}catch{return wX}}function W0(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hF(){if(lw.env.NODE_ENV==="test"||lw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof lw<"u"){let w=lw.type;if(w==="renderer"||w==="worker")return!1;return!!(lw.versions&&(lw.versions.node||lw.versions.bun))}return!1}class w9{async format(w){let $=await hF(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:E1.pid,hostname:$(),environment:E1.env.NODE_ENV||"development",platform:E1.platform,version:E1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:E1.env.NODE_ENV||E1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...xU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new w9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??h0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...$X,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...$X};return{...$X,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:xU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await dK(this.config.logDirectory,eB.F_OK|eB.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await nK(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 Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:f$.from(w);try{if(!zU(this.currentLogFile))await GU(this.currentLogFile,"",{mode:420});if(A=oB(this.currentLogFile,"a",420),gK(A,Q,{flag:"a"}),sB(A),A!==void 0)fU(A),A=void 0;if((await z1(this.currentLogFile)).size===0){if(await GU(this.currentLogFile,Q,{flag:"w",mode:420}),(await z1(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 B=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,B);let f=U*2**X;await new Promise((z)=>setTimeout(z,f)),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{fU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(Q){if(X===J-1){let j=Q,B=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),Q}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return G1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return G1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return G1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(W0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,Q])=>Q.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return BU(16).toString("hex")}generateKey(){return BU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=BU(16),A=vK("aes-256-gcm",$,Y),X=f$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:f$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=$f(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(f$.from(f$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(W0())return;let w=await z1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await iA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let B=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${U}`;if(await z1(Y).catch(()=>null))try{if(await wf(Y,Q),$.compress)try{let W=`${Q}.gz`;await this.compressLogFile(Q,W),await bA(Q)}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 GU(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 z1(Y).catch(()=>null))await wf(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await iA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await bA(G1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=aB(w),A=mK($),X=$f();await lK(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),zU(this.currentLogFile))try{let w=oB(this.currentLogFile,"r+");sB(w),fU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!W0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await iA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await bA(G1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?o.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,Q=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=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 B=Q(j).trim().length,f=Q($).length,z=Math.max(1,W-2-B-f);return`${j.trim()}${" ".repeat(z)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let Q=Number.parseInt(U,10);return Q<$[0].length?String($[0][Q]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let Q=$[A++];switch(U){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,Q;if($ instanceof Error)U=$.message,Q=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!W0()){let j=B9[w],B=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",f;switch(w){case"debug":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:o.gray(U),level:w}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:U,level:w}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:o.green(U),level:w}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:U,level:w}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:U,level:w}),console.error(f),Q){let z=Q.split(`
66
+ `);for(let G of z)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:o.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!W0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),Q)console.error(Q)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
67
+ `;if(Q)W+=`${Q}
68
+ `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!W0()){let Y=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:o.blue("◐"),tag:Y,message:`${o.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,Q=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
69
+ `,W=W.replace(this.ANSI_PATTERN,""),this.fancy&&!W0()){let j=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:o.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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new zX($,{...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(!zU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return aB(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=f$.isBuffer(w)?w:f$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),Q=cK("aes-256-gcm",Y,X);return Q.setAuthTag(J),f$.concat([Q.update(U),Q.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return W0()}isServerMode(){return!W0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!W0()){let J=w.split(`
70
+ `),U=Math.max(...J.map((B)=>B.length))+2,Q=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,j=J.map((B)=>{let f=" ".repeat(U-B.length-2);return`│ ${B}${f} │`});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(Q)})),j.forEach((B)=>console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(B),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(W),showTimestamp:!1}))}else if(!W0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
71
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(W0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${o.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();h0.stdin.removeListener("data",Y);try{if(typeof h0.stdin.setRawMode==="function")h0.stdin.setRawMode(!1)}catch{}h0.stdin.pause(),console.error(""),$(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(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let X=/%([sdijfo%])/g,J=0;if(Y=w.replace(X,(U,Q)=>{if(Q==="%")return"%";if(J>=$.length)return U;let W=$[J++];switch(Q){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return U}}),J<$.length)Y+=` ${$.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!W0()){let X=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",J=o.blue("◐");console.error(`${J} ${X} ${o.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
72
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress(w,$=""){if(!this.enabled||!this.fancy||W0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,X)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,A)),X!==void 0)this.activeProgressBar.message=X;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,A!==void 0)this.activeProgressBar.message=A;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(A,X="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||W0())return;h0.stdout.write(`${"\r".padEnd(h0.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()||!h0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=o.green("━".repeat(A)),U=o.gray("━".repeat(X)),Q=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=w.message?` ${w.message}`:"",B=$||Y===100?o.green("✓"):o.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${o.gray(this.formatTag(this.name))}`:"",z=`\r${B}${f} ${Q} ${W}${j}`,G=h0.stdout.columns||80,T=" ".repeat(Math.max(0,G-z.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${z}${T}`,h0.stdout.write(w.lastRenderedLine),$)h0.stdout.write(`
73
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||W0()||!h0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(W0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await iA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=G1(this.config.logDirectory,A);if(w.before)try{if((await z1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await bA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function eA(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&p($[0])&&"id"in $[0]&&$[0].id===3&&p($[1])&&"id"in $[1]&&$[1].id===4)return $;if(p($)&&p(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(p(w)&&"arr"in w&&Array.isArray(w.arr)&&p($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&p($[0])&&p(w[0])){let A=[...$];for(let X of w)if(p(X)&&"name"in X){if(!A.find((J)=>p(J)&&("name"in J)&&J.name===X.name))A.push(X)}else if(p(X)&&"path"in X){if(!A.find((J)=>p(J)&&("path"in J)&&J.path===X.path))A.push(X)}else if(!A.some((J)=>GX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!p($)||!p(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(p(X)&&p(Y[A]))Y[A]=eA(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((Q)=>p(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((Q)=>p(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((Q)=>GX(Q,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 eU(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:eA(w,$);if(Array.isArray(w))return Y==="replace"?$:eA(w,$);if(!p($)||!p(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=eA(U,J);else if(p(J)&&p(U))A[X]=eU(U,J,Y);else A[X]=J}return A}function GX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!GX(w[Y],$[Y]))return!1;return!0}if(p(w)&&p($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!GX(w[X],$[X]))return!1}return!0}return!1}function p(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function tA(w,$,Y="replace"){if(!tf(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return eU($,X,Y)}catch{return null}}catch{return null}}function _F(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,Q=[]){let W={...U};for(let[j,B]of Object.entries(U)){let f=[...Q,j],z=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${f.map(z).join("_")}`,T=`${A}_${f.map((K)=>K.toUpperCase()).join("_")}`;if(Y)D0.info(`Checking environment variable ${G} for config ${w}.${f.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))W[j]=J(B,f);else{let K=UY.env[G]||UY.env[T];if(K!==void 0){if(Y)D0.info(`Using environment variable ${K?G:T} for config ${w}.${f.join(".")}`);if(typeof B==="number")W[j]=Number(K);else if(typeof B==="boolean")W[j]=K.toLowerCase()==="true";else if(Array.isArray(B))try{let F=JSON.parse(K);if(Array.isArray(F))W[j]=F;else W[j]=K.split(",").map((q)=>q.trim())}catch{W[j]=K.split(",").map((F)=>F.trim())}else W[j]=K}}}return W}return J(X)}async function DF({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:Q="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?_F(w,X,J):X,j=Y||UY.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${j}`);let f=[w,`.${w}`].filter(Boolean),z=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([j,m0(j,"config"),m0(j,".config"),A?m0(j,A):void 0].filter(Boolean)));for(let F of K){if(J)D0.info(`Searching for configuration in: ${F}`);let q=[m0(j,"config"),m0(j,".config")].concat(A?[m0(j,A)]:[]).includes(F)?[...f,...z,...G,...T]:[...z,...f,...T,...G];for(let R of q)for(let L of B){let V=m0(F,`${R}${L}`),N=await tA(V,W,Q);if(N!==null){if(J)D0.success(`Configuration loaded from: ${V}`);return N}}}if(w){let F=m0(jU(),".config",w),q=["config",`${w}.config`];if($)q.push(`${$}.config`);if(J)D0.info(`Checking user config directory: ${F}`);for(let R of q)for(let L of B){let V=m0(F,`${R}${L}`),N=await tA(V,W,Q);if(N!==null){if(J)D0.success(`Configuration loaded from user config directory: ${V}`);return N}}}if(w){let F=m0(jU(),".config"),q=[`.${w}.config`];if($)q.push(`.${$}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of q)for(let L of B){let V=m0(F,`${R}${L}`),N=await tA(V,W,Q);if(N!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${V}`);return N}}}if(w){let F=jU(),q=[`.${w}.config`,`.${w}`];if($)q.push(`.${$}.config`),q.push(`.${$}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of q)for(let L of B){let V=m0(F,`${R}${L}`),N=await tA(V,W,Q);if(N!==null){if(J)D0.success(`Configuration loaded from user home directory: ${V}`);return N}}}try{let F=m0(j,"package.json");if(tf(F)){let q=await import(F),R=q[w];if(!R&&$){if(R=q[$],R&&J)D0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)D0.success(`Configuration loaded from package.json: ${R===q[w]?w:$}`);return eU(W,R,Q)}catch(L){if(J)D0.warn("Failed to merge package.json config:",L)}}}catch(F){if(J)D0.warn("Failed to load package.json:",F)}if(J)D0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function kF(w,$={}){let Y=UX.cwd();while(Y.includes("storage"))Y=rB(Y,"..");let A=rB(Y,w||"");if($?.relative)return iK(UX.cwd(),A);return A}async function ZF(){try{let w=await DF({name:"clarity",alias:"logging",defaultConfig:YX,cwd:UX.cwd()});return{...YX,...w||{}}}catch{return YX}}function T0(){if(pw.env.NODE_ENV==="test"||pw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function xF(){if(pw.env.NODE_ENV==="test"||pw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof pw<"u"){let w=pw.type;if(w==="renderer"||w==="worker")return!1;return!!(pw.versions&&(pw.versions.node||pw.versions.bun))}return!1}class $9{async format(w){let $=await xF(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:T1.pid,hostname:$(),environment:T1.env.NODE_ENV||"development",platform:T1.platform,version:T1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:T1.env.NODE_ENV||T1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class EX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...PU},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new $9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...AX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...AX};return{...AX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:PU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await sK(this.config.logDirectory,Jf.F_OK|Jf.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await oK(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 Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:gw.from(w);try{if(!uA(this.currentLogFile))await FU(this.currentLogFile,"",{mode:420});if(A=Xf(this.currentLogFile,"a",420),aK(A,Q,{flag:"a"}),Af(A),A!==void 0)KU(A),A=void 0;if((await K1(this.currentLogFile)).size===0){if(await FU(this.currentLogFile,Q,{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 B=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,B);let f=U*2**X;await new Promise((z)=>setTimeout(z,f)),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{KU(A)}catch(W){console.error("Debug: [writeToFile] Error closing file descriptor:",W)}}}catch(Q){if(X===J-1){let j=Q,B=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),Q}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return F1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return F1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return F1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,Q])=>Q.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return EU(16).toString("hex")}generateKey(){return EU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=EU(16),A=pK("aes-256-gcm",$,Y),X=gw.isBuffer(w)?w:gw.from(w,"utf8"),J=A.update(X),U=A.final(),Q=J.length+U.length,W=A.getAuthTag(),j=gw.allocUnsafe(16+Q+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+Q),{encrypted:j,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Wf(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(gw.from(gw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let w=await K1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await vA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let B=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${U}`;if(await K1(Y).catch(()=>null))try{if(await Uf(Y,Q),$.compress)try{let W=`${Q}.gz`;await this.compressLogFile(Q,W),await cA(Q)}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 FU(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 Uf(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await vA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await cA(F1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Yf(w),A=tK($),X=Wf();await $F(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),uA(this.currentLogFile))try{let w=Xf(this.currentLogFile,"r+");Af(w),KU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await vA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await cA(F1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?u.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let w=typeof n.env.NO_COLOR<"u",$=n.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,Q=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=n.stdout.columns||120,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 B=Q(j).trim().length,f=Q($).length,z=Math.max(1,W-2-B-f);return`${j.trim()}${" ".repeat(z)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let Q=Number.parseInt(U,10);return Q<$[0].length?String($[0][Q]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let Q=$[A++];switch(U){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=u.underline(u.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Q=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${Q}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),$}supportsHyperlinks(){if(T0())return!1;let w=n.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=n.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(eK($)||$.startsWith("./")||$.startsWith("../"))$=wF($);else return null;return uA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,Q;if($ instanceof Error)U=$.message,Q=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":f9[w],z=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:u.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:u.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.error(G),Q){let T=Q.split(`
74
+ `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:u.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),Q)console.error(Q)}if(!this.shouldLog(w))return;let B=`${J} ${this.environment}.${w.toUpperCase()}: ${j}
75
+ `;if(Q)B+=`${Q}
76
+ `;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!T0()&&n.stdout.isTTY)n.stdout.write(`
77
+ `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:Y,message:`${u.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,Q=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
78
+ `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:this.options.showIcons===!1?"":u.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new EX($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(T0())throw Error("createReadStream is not supported in browser environments");if(!uA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Yf(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=gw.isBuffer(w)?w:gw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),Q=rK("aes-256-gcm",Y,X);Q.setAuthTag(J);let W=Q.update(U),j=Q.final(),B=W.length+j.length,f=gw.allocUnsafe(B);return W.copy(f,0),j.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T0()}isServerMode(){return!T0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let Q=X.split(`
79
+ `),W=Math.max(...Q.map((z)=>z.length))+2,j=`┌${"─".repeat(W)}┐`,B=`└${"─".repeat(W)}┘`,f=Q.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(j),showTimestamp:!1})),f.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(B),showTimestamp:!1}))}else if(!T0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
80
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(T0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${u.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();n.stdin.removeListener("data",Y);try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!1)}catch{}n.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!0)}catch{}n.stdin.resume(),n.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,Q=0;if(Y=w.replace(U,(W,j)=>{if(j==="%")return"%";if(Q>=$.length)return W;let B=$[Q++];switch(j){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 W}}),Q<$.length)Y+=` ${$.slice(Q).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",Q=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${Q}${U} ${u.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
81
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!n.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=u.green("━".repeat(A)),U=u.gray("━".repeat(X)),Q=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=w.message?` ${w.message}`:"",B=this.options.showIcons===!1?"":$||Y===100?u.green("✓"):u.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",z=`\r${B}${f} ${Q} ${W}${j}`,G=n.stdout.columns||80,T=" ".repeat(Math.max(0,G-z.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${z}${T}`,n.stdout.write(w.lastRenderedLine),$)n.stdout.write(`
82
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||T0()||!n.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await vA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=F1(this.config.logDirectory,A);if(w.before)try{if((await K1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await cA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function Y9(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let Q=0;Q<=Y;Q++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),Q===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 A9(w){return w instanceof s0}function PF(w){return w instanceof KX}function iF(w){if(A9(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some(($)=>w.message.toLowerCase().includes($.toLowerCase()))}class IX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:Q=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let B=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],B,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:Q,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return BY.track("applyEnvironmentVariables",j,{configName:w});return j()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=U.map((B)=>this.formatEnvKey(B,A.useCamelCase)),W=`${Y}_${Q.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((B)=>B.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let B=mA.env[W]||(j?mA.env[j]:void 0);if(B!==void 0){if(A.verbose){let f=mA.env[W]?W:j}try{w[X]=this.parseEnvironmentValue(B,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof FX)throw f;throw G$.envVar(W,B,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw G$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(mA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=`${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:Q,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
85
83
 
86
84
  `;for(let A of w)Y+=`${A.key}
87
85
  `,Y+=` Type: ${A.type}
@@ -93,25 +91,25 @@ export type ConfigOf = Config
93
91
  `;Y+=`| Variable | Type | Description | Example |
94
92
  `,Y+=`|----------|------|-------------|----------|
95
93
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
96
- `;return Y}}function zN(w,$){let Y=Lz("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function Vz(w,$,Y={}){return Cz(w,$,Y,new WeakMap)}function Cz(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return yz(w,$,X,A);if(!Bw($)||!Bw(w))return $;return qN(w,$,Y,A)}function yz(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return GN(w,$);case"smart":return KN(w,$,A);default:return $}return $}function GN(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>aU(X,A)))Y.push(A);return Y}function KN(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Bw($[0])&&Bw(w[0]))return FN(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function FN(w,$,Y){let A=[...$];for(let X of w){if(!Bw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((Q)=>Bw(Q)&&(W in Q)&&Q[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function qN(w,$,Y,A){let X=$;if(Bw(X)&&A.has(X))return A.get(X);let J={...w};if(Bw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(Bw(W)&&Bw(Q))J[U]=Cz(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=yz(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function NQ(w,$,Y="replace"){return Vz(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function aU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!aU(w[Y],$[Y]))return!1;return!0}if(Bw(w)&&Bw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!aU(w[X],$[X]))return!1}return!0}return!1}function Bw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class bX{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:W=!1}=Y;if(X){let B=_1.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!$X(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new CY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new CY(w,Error("Configuration must export a valid object"),"unknown");let E={config:NQ($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)_1.setWithFileCheck("file",E,w,J);return E}catch(B){throw B instanceof Error?H$.configLoad(w,B):H$.configLoad(w,Error(String(B)))}};if(U)return LY.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(hU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return Mz(async()=>{return $X(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!$X(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=hU(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=hU(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!$X(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class EQ{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await LY.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!_q($))throw new yY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new yY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:hz},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class fQ{fileLoader=new bX;envProcessor=new PX;validator=new EQ;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)fw.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){let Q=Date.now()-$;throw fw.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||i$.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(d0(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw H$.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?RY(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)fw.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)fw.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?RY(w,Y,X):Y,W=[d0(f1(),".config",w),d0(f1(),".config"),f1()];for(let Q of W){if(X)fw.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)fw.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?RY(w,A,J):A;try{let Q=d0(Y,"package.json");if(!rU(Q))return null;let B=await import(Q),j=B[w],z=w;if(!j&&$)j=B[$],z=$;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)fw.success(`Configuration loaded from package.json: ${z}`);return{config:NQ(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)fw.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:RY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw H$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return _1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);_1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,d0(w,"config"),d0(w,".config"),$?d0(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(d0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[d0(f1(),".config",w),d0(f1(),".config"),f1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function b9(w){let $=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),Y=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return $||Y}async function NN(w){return w$.loadConfig({...w,__strictErrorHandling:!0})}async function Oz(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await w$.loadConfig(w);else A=await w$.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)fw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await w$.applyEnvironmentVariables(U.name||"",$,!0,U.verbose||!1))?.config??$;return $}}async function EN(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await w$.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&b9(Y)))return(await w$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await w$.loadConfig({...w,cwd:w.cwd||i$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&b9($)))return(await w$.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function fN(w,$,Y="replace"){let A=new bX;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function RY(w,$,Y=!1){let A=new PX,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=i$.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}function TN(w){let $=d0(i$.cwd(),w.configDir),Y=d0(i$.cwd(),w.generatedDir),A=d0(Y,"config-types.ts");if(!rU(F9(A)))Uq(F9(A),{recursive:!0,mode:511});let X=rU($)?Qq($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${rN}
94
+ `;return Y}}function bF(w,$){let Y=Q9("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function X9(w,$,Y={}){return J9(w,$,Y,new WeakMap)}function J9(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let Q=U(w,$);if(Q!==void 0)return Q}if(Array.isArray($)||Array.isArray(w))return U9(w,$,X,A);if(!Qw($)||!Qw(w))return $;return mF(w,$,Y,A)}function U9(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return uF(w,$);case"smart":return vF(w,$,A);default:return $}return $}function uF(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>ZU(X,A)))Y.push(A);return Y}function vF(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Qw($[0])&&Qw(w[0]))return cF(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function cF(w,$,Y){let A=[...$];for(let X of w){if(!Qw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let Q of J)if(Q in X){if(A.find((W)=>Qw(W)&&(Q in W)&&W[Q]===X[Q])){U=!0;break}}if(!U)A.push(X)}return A}function mF(w,$,Y,A){let X=$;if(Qw(X)&&A.has(X))return A.get(X);let J={...w};if(Qw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let Q=X[U],W=J[U];if(Y.skipNullish&&(Q===null||Q===void 0))continue;if(Q===null||Q===void 0){J[U]=Q;continue}if(Qw(Q)&&Qw(W))J[U]=J9(W,Q,Y,A);else if(Array.isArray(Q)||Array.isArray(W))J[U]=U9(W,Q,Y.arrayMergeMode||"smart",A);else J[U]=Q}return J}function wW(w,$,Y="replace"){return X9(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function ZU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!ZU(w[Y],$[Y]))return!1;return!0}if(Qw(w)&&Qw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!ZU(w[X],$[X]))return!1}return!0}return!1}function Qw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class CX{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:Q=!1}=Y;if(X){let j=M1.getWithFileCheck("file",w);if(j){if(Q)console.log(`Configuration loaded from cache: ${w}`);return j}}let W=async()=>{if(!gA(w))return null;try{let j=`?t=${Date.now()}`,B=await import(w+j),f=B.default||B,z="default"in B,G=Object.keys(B).length>0;if(!z&&!G)throw new WY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new WY(w,Error("Configuration must export a valid object"),"unknown");let T={config:wW($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)M1.setWithFileCheck("file",T,w,J);return T}catch(j){throw j instanceof Error?G$.configLoad(w,j):G$.configLoad(w,Error(String(j)))}};if(U)return BY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(TU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return Y9(async()=>{return gA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!gA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let Q=TU(w,`${J}${U}`);if(await this.checkFileAccess(Q))A.push(Q)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let Q=TU(w,U);if(await this.checkFileAccess(Q))A.push(Q)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!gA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class $W{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:Q=!0,verbose:W=!1}=Y,j=async()=>{let B=[],f=[],z={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:Q,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,z);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],z);else return this.validateWithJSONSchema(w,$,z)}catch(G){return B.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:B,warnings:f}}};if(Q)return await BY.track("validateConfiguration",j);return j()}async validateWithSchemaFile(w,$,Y){try{if(!YF($))throw new QY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new QY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,Q=Array.isArray($.type)?$.type:[$.type];if(!Q.includes(U)){if(A.push({path:Y,message:`Expected type ${Q.join(" or ")}, got ${U}`,expected:Q.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let Q=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let Q of $.required)if(!(Q in U)){if(A.push({path:Y?`${Y}.${Q}`:Q,message:`Missing required property '${Q}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[Q,W]of Object.entries($.properties))if(Q in U){let j=Y?`${Y}.${Q}`:Q;if(this.validateObjectAgainstSchema(U[Q],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let Q=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!Q.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),Q=this.validateWithRule(U,J,J.path);if(A.push(...Q),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:G9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class YW{fileLoader=new CX;envProcessor=new IX;validator=new $W;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let Q;try{Q=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;Q={...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 B=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!B&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),z=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(z||B))throw W;if(f&&(!j||!z))Q={...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)Q={...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 Q={...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(Q.config,X,J,U.name);if(Y?.enabled&&Q)this.cacheResult(U.name||"",Q,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)qw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);Q.metrics=W}return Q}catch(Q){let W=Date.now()-$;throw qw.error(`Configuration loading failed after ${W}ms:`,[Q instanceof Error?Q:Error(String(Q))]),Q}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:Q,checkEnv:W=!0,arrayStrategy:j="replace",verbose:B=!1}=w,f=J||x$.cwd(),z=[],G=await this.loadLocalConfiguration(A,X,f,U,Q,j,B,W,Y);if(G)return z.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,z,W,A,B);let T=await this.loadHomeConfiguration(A,X,Q,j,B,W);if(T)return z.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,z,W,A,B);let K=await this.loadPackageJsonConfiguration(A,X,f,Q,j,B,W);if(K)return z.push(g0(f,"package.json")),this.finalizeResult(K,z,W,A,B);if(z.push(...this.getAllSearchPaths(A,X,f,U)),$)throw G$.configNotFound(A,z,X);return{...await this.applyEnvironmentVariables(A,Q,W,B),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,Q,W){let j=Q?AY(w,X,U):X,B=this.getLocalDirectories(Y,A);for(let f of B){if(U)qw.info(`Searching for configuration in: ${f}`);let z=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(z,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)qw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?AY(w,Y,X):Y,Q=[g0(f1(),".config",w),g0(f1(),".config"),f1()];for(let W of Q){if(X)qw.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths(w,W,$),B=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(B){if(X)qw.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let Q=U?AY(w,A,J):A;try{let W=g0(Y,"package.json");if(!DU(W))return null;let j=await import(W),B=j[w],f=w;if(!B&&$)B=j[$],f=$;if(B&&typeof B==="object"&&!Array.isArray(B)){if(J)qw.success(`Configuration loaded from package.json: ${f}`);return{config:wW(Q,B,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)qw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:AY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw G$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return M1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);M1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,g0(w,"config"),g0(w,".config"),$?g0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(g0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[g0(f1(),".config",w),g0(f1(),".config"),f1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Ff(w){let $=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),Y=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return $||Y}async function gF(w){return aw.loadConfig({...w,__strictErrorHandling:!0})}async function W9(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await aw.loadConfig(w);else A=await aw.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)qw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let U=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await aw.applyEnvironmentVariables(U.name||"",$,!0,U.verbose||!1))?.config??$;return $}}async function dF(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await aw.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Ff(Y)))return(await aw.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await aw.loadConfig({...w,cwd:w.cwd||x$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Ff($)))return(await aw.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function nF(w,$,Y="replace"){let A=new CX;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function AY(w,$,Y=!1){let A=new IX,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,Q=[]){let W={...U};for(let[j,B]of Object.entries(U)){let f=[...Q,j],z=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((K)=>K.toUpperCase()).join("")}`,`${X}_${f.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of z)if(G=x$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof B==="boolean")W[j]=["true","1","yes"].includes(G.toLowerCase());else if(typeof B==="number"){let K=Number(G);if(!Number.isNaN(K))W[j]=K}else if(Array.isArray(B))try{W[j]=JSON.parse(G)}catch{W[j]=G.split(",").map((K)=>K.trim())}else W[j]=G;else if(B&&typeof B==="object"&&!Array.isArray(B))W[j]=J(B,f)}return W}return J($)}function lF(w){let $=g0(x$.cwd(),w.configDir),Y=g0(x$.cwd(),w.generatedDir),A=g0(Y,"config-types.ts");if(!DU(pB(A)))kK(pB(A),{recursive:!0,mode:511});let X=DU($)?ZK($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${RT}
97
95
  export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
98
- `;Wq(A,J,{mode:438})}function HN(w){let $=null,Y=null,A=()=>{if(!Y)Y=Oz(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)fw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let W=X[U];return A(),W},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,W){if(!$)$={...X};return $[U]=W,!0}})}function RN(w){let $=_9(kq.cwd(),w?.configDir||"./config");function Y(){if(!Sq($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=Zq($).filter((Q)=>X.has(DU(Q))).map((Q)=>({base:Q.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Q})),W=new Map;for(let{base:Q,file:B}of U){let j=DU(B).toLowerCase(),z=W.get(Q);if(!z){W.set(Q,B);continue}let G=DU(z).toLowerCase();if(J.indexOf(j)<J.indexOf(G))W.set(Q,B)}return Array.from(W.entries()).map(([Q,B])=>({base:Q,file:B})).sort((Q,B)=>Q.base.localeCompare(B.base))}function A(){let X=Y(),J=X.map((Q)=>Q.base),U=J.length?J.map((Q)=>`'${Q}'`).join(" | "):"string",W=X.length?`{
99
- ${X.map((Q)=>{let B=_9($,Q.file).replace(/\\/g,"/");return` '${Q.base}': typeof import('${B}').default`}).join(`,
96
+ `;xK(A,J,{mode:438})}function pF(w){let $=null,Y=null,A=()=>{if(!Y)Y=W9(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)qw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let Q=X[U];return A(),Q},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,Q){if(!$)$={...X};return $[U]=Q,!0}})}function rF(w){let $=Qf(JF.cwd(),w?.configDir||"./config");function Y(){if(!AF($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=XF($).filter((W)=>X.has(qU(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),Q=new Map;for(let{base:W,file:j}of U){let B=qU(j).toLowerCase(),f=Q.get(W);if(!f){Q.set(W,j);continue}let z=qU(f).toLowerCase();if(J.indexOf(B)<J.indexOf(z))Q.set(W,j)}return Array.from(Q.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",Q=X.length?`{
97
+ ${X.map((W)=>{let j=Qf($,W.file).replace(/\\/g,"/");return` '${W.base}': typeof import('${j}').default`}).join(`,
100
98
  `)}
101
99
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
102
- export type ConfigByName = ${W}
100
+ export type ConfigByName = ${Q}
103
101
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
104
102
  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 aN(w,$={}){let Y=RX.cwd();while(Y.includes("storage"))Y=S9(Y,"..");let A=S9(Y,w||"");if($?.relative)return Dq(RX.cwd(),A);return A}function T0(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function oN(){if(ow.env.NODE_ENV==="test"||ow.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ow<"u"){let w=ow.type;if(w==="renderer"||w==="worker")return!1;return!!(ow.versions&&(ow.versions.node||ow.versions.bun))}return!1}class bz{async format(w){let $=await oN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:O1.pid,hostname:$(),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 uX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={..._X},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new bz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...gU,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...gU};return{...gU,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:_X.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await cq(this.config.logDirectory,D9.F_OK|D9.W_OK)}catch(Q){if(Q instanceof Error&&"code"in Q)if(Q.code==="ENOENT")await vq(this.config.logDirectory,{recursive:!0,mode:493});else if(Q.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw Q;else throw Q}}catch(Q){throw console.error("Debug: [writeToFile] Failed to create log directory:",Q),Q}let W=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:rw.from(w);try{if(!YX(this.currentLogFile))await bU(this.currentLogFile,"",{mode:420});if(A=h9(this.currentLogFile,"a",420),uq(A,W,{flag:"a"}),k9(A),A!==void 0)PU(A),A=void 0;if((await C1(this.currentLogFile)).size===0){if(await bU(this.currentLogFile,W,{flag:"w",mode:420}),(await C1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(Q){let B=Q;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(X<J-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,j);let z=U*2**X;await new Promise((G)=>setTimeout(G,z)),X++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{PU(A)}catch(Q){console.error("Debug: [writeToFile] Error closing file descriptor:",Q)}}}catch(W){if(X===J-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}X++;let Q=U*2**(X-1);await new Promise((B)=>setTimeout(B,Q))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return y1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return y1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return y1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return xU(16).toString("hex")}generateKey(){return xU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=xU(16),A=xq("aes-256-gcm",$,Y),X=rw.isBuffer(w)?w:rw.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=rw.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=P9(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(rw.from(rw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let w=await C1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await AX(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await C1(Y).catch(()=>null))try{if(await x9(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await XX(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await bU(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await C1(Y).catch(()=>null))await x9(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await AX(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await XX(y1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Z9(w),A=bq($),X=P9();await gq(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),YX(this.currentLogFile))try{let w=h9(this.currentLogFile,"r+");k9(w),PU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await AX(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await XX(y1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?m.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let w=typeof n.env.NO_COLOR<"u",$=n.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=n.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${m.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),$}supportsHyperlinks(){if(T0())return!1;let w=n.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=n.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(iq($)||$.startsWith("./")||$.startsWith("../"))$=mq($);else return null;return YX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":AE[w],G=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:m.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:m.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
106
- `);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:m.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
107
- `;if(W)j+=`${W}
108
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!T0()&&n.stdout.isTTY)n.stdout.write(`
109
- `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":m.blue("◐"),tag:Y,message:`${m.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),Q=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)Q+=` ${JSON.stringify(Y)}`;if(Q+=`
110
- `,Q=Q.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":m.green("✓"),tag:B,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T0())console.error(Q.trim());if(this.shouldWriteToFile())await this.writeToFile(Q)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new uX($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(T0())throw Error("createReadStream is not supported in browser environments");if(!YX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Z9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=rw.isBuffer(w)?w:rw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=Pq("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=rw.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T0()}isServerMode(){return!T0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
111
- `),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:m.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(j),showTimestamp:!1}))}else if(!T0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
112
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(T0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${m.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();n.stdin.removeListener("data",Y);try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!1)}catch{}n.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!0)}catch{}n.stdin.resume(),n.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,W=0;if(Y=w.replace(U,(Q,B)=>{if(B==="%")return"%";if(W>=$.length)return Q;let j=$[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return Q}}),W<$.length)Y+=` ${$.slice(W).map((Q)=>typeof Q==="object"?JSON.stringify(Q,null,2):String(Q)).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)):"",W=this.options.showIcons===!1?"":`${m.blue("◐")} `;console.error(`${W}${U} ${m.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
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(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=m.green("━".repeat(A)),U=m.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?m.green("✓"):m.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=n.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,n.stdout.write(w.lastRenderedLine),$)n.stdout.write(`
114
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||T0()||!n.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await AX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=y1(this.config.logDirectory,A);if(w.before)try{if((await C1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await XX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function XE(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class HQ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return zQ.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=JX.env[Q]||(B?JX.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=JX.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof TQ)throw z;throw S1.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw S1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(JX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
103
+ `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function yT(w,$={}){let Y=jX.cwd();while(Y.includes("storage"))Y=jf(Y,"..");let A=jf(Y,w||"");if($?.relative)return WF(jX.cwd(),A);return A}function N0(){if(rw.env.NODE_ENV==="test"||rw.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CT(){if(rw.env.NODE_ENV==="test"||rw.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof rw<"u"){let w=rw.type;if(w==="renderer"||w==="worker")return!1;return!!(rw.versions&&(rw.versions.node||rw.versions.bun))}return!1}class T9{async format(w){let $=await CT(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:H1.pid,hostname:$(),environment:H1.env.NODE_ENV||"development",platform:H1.platform,version:H1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H1.env.NODE_ENV||H1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class VX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...TX},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new T9,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??l.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...LU,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...LU};return{...LU,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:TX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile(w){let $=(async()=>{let A,X=0,J=3,U=1000;while(X<J)try{try{try{await zF(this.config.logDirectory,Gf.F_OK|Gf.W_OK)}catch(W){if(W instanceof Error&&"code"in W)if(W.code==="ENOENT")await GF(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 Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:dw.from(w);try{if(!dA(this.currentLogFile))await RU(this.currentLogFile,"",{mode:420});if(A=zf(this.currentLogFile,"a",420),fF(A,Q,{flag:"a"}),ff(A),A!==void 0)HU(A),A=void 0;if((await q1(this.currentLogFile)).size===0){if(await RU(this.currentLogFile,Q,{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 B=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,B);let f=U*2**X;await new Promise((z)=>setTimeout(z,f)),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(Q){if(X===J-1){let j=Q,B=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",B),Q}X++;let W=U*2**(X-1);await new Promise((j)=>setTimeout(j,W))}})();this.pendingOperations.push($);let Y=this.pendingOperations.length-1;try{await $}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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 w=new Date().toISOString().split("T")[0];return N1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let $=typeof w.interval==="number"?w.interval:60,Y=Math.max($,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,$=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=$,this.keys.set($,Y),this.encryptionKeys.set($,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,U],[,Q])=>Q.createdAt.getTime()-U.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(A.length>J)for(let[U]of A.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return NU(16).toString("hex")}generateKey(){return NU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=NU(16),A=QF("aes-256-gcm",$,Y),X=dw.isBuffer(w)?w:dw.from(w,"utf8"),J=A.update(X),U=A.final(),Q=J.length+U.length,W=A.getAuthTag(),j=dw.allocUnsafe(16+Q+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+Q),{encrypted:j,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Kf(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(dw.from(dw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let w=await q1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await nA(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let B=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${U}`;if(await q1(Y).catch(()=>null))try{if(await Ef(Y,Q),$.compress)try{let W=`${Q}.gz`;await this.compressLogFile(Q,W),await lA(Q)}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 q1(Y).catch(()=>null))await Ef(Y,J)}if(this.currentLogFile=A,$.maxFiles){let X=(await nA(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice($.maxFiles))await lA(N1(this.config.logDirectory,J))}}}async compressLogFile(w,$){let Y=Bf(w),A=BF($),X=Kf();await FF(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),dA(this.currentLogFile))try{let w=zf(this.currentLogFile,"r+");ff(w),HU(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await nA(this.config.logDirectory)).filter(($)=>($.includes("temp")||$.includes(".tmp"))&&$.includes(this.name));for(let $ of w)try{await lA(N1(this.config.logDirectory,$))}catch(Y){console.error(`Failed to delete temp file ${$}:`,Y)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?m.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let w=typeof l.env.NO_COLOR<"u",$=l.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof l.stderr<"u"&&l.stderr.isTTY||typeof l.stdout<"u"&&l.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,Q=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=l.stdout.columns||120,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 B=Q(j).trim().length,f=Q($).length,z=Math.max(1,W-2-B-f);return`${j.trim()}${" ".repeat(z)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let Q=Number.parseInt(U,10);return Q<$[0].length?String($[0][Q]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let Q=$[A++];switch(U){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=m.underline(m.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Q=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${Q}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>m.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>m.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>m.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>m.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>m.strikethrough(A)),$}supportsHyperlinks(){if(N0())return!1;let w=l.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=l.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(EF($)||$.startsWith("./")||$.startsWith("../"))$=KF($);else return null;return dA($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,Q;if($ instanceof Error)U=$.message,Q=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":hT[w],z=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:m.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:m.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.error(G),Q){let T=Q.split(`
104
+ `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:m.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!N0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),Q)console.error(Q)}let B=`${J} ${this.environment}.${w.toUpperCase()}: ${j}
105
+ `;if(Q)B+=`${Q}
106
+ `;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress(w,$=""){let Y={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&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()&&!N0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!N0()&&l.stdout.isTTY)l.stdout.write(`
107
+ `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&l.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":m.blue("◐"),tag:Y,message:`${m.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,Q=this.formatConsoleTimestamp(U),W=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)W+=` ${JSON.stringify(Y)}`;if(W+=`
108
+ `,W=W.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?m.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:this.options.showIcons===!1?"":m.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!N0())console.error(W.trim());if(this.shouldWriteToFile())await this.writeToFile(W)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new VX($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(N0())throw Error("createReadStream is not supported in browser environments");if(!dA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Bf(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=dw.isBuffer(w)?w:dw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),Q=jF("aes-256-gcm",Y,X);Q.setAuthTag(J);let W=Q.update(U),j=Q.final(),B=W.length+j.length,f=dw.allocUnsafe(B);return W.copy(f,0),j.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N0()}isServerMode(){return!N0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let Q=X.split(`
109
+ `),W=Math.max(...Q.map((z)=>z.length))+2,j=`┌${"─".repeat(W)}┐`,B=`└${"─".repeat(W)}┘`,f=Q.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:m.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(j),showTimestamp:!1})),f.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:m.cyan(B),showTimestamp:!1}))}else if(!N0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
110
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(N0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${m.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();l.stdin.removeListener("data",Y);try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!1)}catch{}l.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof l.stdin.setRawMode==="function")l.stdin.setRawMode(!0)}catch{}l.stdin.resume(),l.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,Q=0;if(Y=w.replace(U,(W,j)=>{if(j==="%")return"%";if(Q>=$.length)return W;let B=$[Q++];switch(j){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 W}}),Q<$.length)Y+=` ${$.slice(Q).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)):"",Q=this.options.showIcons===!1?"":`${m.blue("◐")} `;console.error(`${Q}${U} ${m.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
111
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!l.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=m.green("━".repeat(A)),U=m.gray("━".repeat(X)),Q=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=w.message?` ${w.message}`:"",B=this.options.showIcons===!1?"":$||Y===100?m.green("✓"):m.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${m.gray(this.formatTag(this.name))}`:"",z=`\r${B}${f} ${Q} ${W}${j}`,G=l.stdout.columns||80,T=" ".repeat(Math.max(0,G-z.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${z}${T}`,l.stdout.write(w.lastRenderedLine),$)l.stdout.write(`
112
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||N0()||!l.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(N0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await nA(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=N1(this.config.logDirectory,A);if(w.before)try{if((await q1(X)).mtime>=w.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await lA(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function _T(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let Q=0;Q<=Y;Q++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),Q===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 XW{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:Q=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let B=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],B,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:Q,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return tU.track("applyEnvironmentVariables",j,{configName:w});return j()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=U.map((B)=>this.formatEnvKey(B,A.useCamelCase)),W=`${Y}_${Q.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((B)=>B.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let B=pA.env[W]||(j?pA.env[j]:void 0);if(B!==void 0){if(A.verbose){let f=pA.env[W]?W:j}try{w[X]=this.parseEnvironmentValue(B,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof AW)throw f;throw y1.envVar(W,B,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw y1.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(pA.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=`${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:Q,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
115
113
 
116
114
  `;for(let A of w)Y+=`${A.key}
117
115
  `,Y+=` Type: ${A.type}
@@ -123,32 +121,32 @@ export type ConfigOf = Config
123
121
  `;Y+=`| Variable | Type | Description | Example |
124
122
  `,Y+=`|----------|------|-------------|----------|
125
123
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
126
- `;return Y}}function JE(w,$,Y={}){return lz(w,$,Y,new WeakMap)}function lz(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return nz(w,$,X,A);if(!jw($)||!jw(w))return $;return BE(w,$,Y,A)}function nz(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return UE(w,$);case"smart":return QE(w,$,A);default:return $}return $}function UE(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>JQ(X,A)))Y.push(A);return Y}function QE(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(jw($[0])&&jw(w[0]))return WE(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function WE(w,$,Y){let A=[...$];for(let X of w){if(!jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((Q)=>jw(Q)&&(W in Q)&&Q[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function BE(w,$,Y,A){let X=$;if(jw(X)&&A.has(X))return A.get(X);let J={...w};if(jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(jw(W)&&jw(Q))J[U]=lz(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=nz(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function pz(w,$,Y="replace"){return JE(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function JQ(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!JQ(w[Y],$[Y]))return!1;return!0}if(jw(w)&&jw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!JQ(w[X],$[X]))return!1}return!0}return!1}function jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class rz{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:W=!1}=Y;if(X){let B=MX.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!UX(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new SX(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new SX(w,Error("Configuration must export a valid object"),"unknown");let E={config:pz($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)MX.setWithFileCheck("file",E,w,J);return E}catch(B){throw B instanceof Error?S1.configLoad(w,B):S1.configLoad(w,Error(String(B)))}};if(U)return zQ.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(uU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return XE(async()=>{return UX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!UX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=uU(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=uU(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!UX(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class tz{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await zQ.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!dq($))throw new ZX($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new ZX($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:jE},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function zE(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class az{fileLoader=new rz;envProcessor=new HQ;validator=new tz;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)tw.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let Q=Date.now()-$;throw tw.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||xX.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(Ww(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw S1.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${zE(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?WX(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)tw.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)tw.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?WX(w,Y,X):Y,W=[Ww(E1(),".config",w),Ww(E1(),".config"),E1()];for(let Q of W){if(X)tw.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)tw.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?WX(w,A,J):A;try{let Q=Ww(Y,"package.json");if(!Xq(Q))return null;let B={};try{B=JSON.parse(Jq(Q,"utf8"))}catch(G){if(J)tw.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let j=B[w],z=w;if(!j&&$){let G=Array.isArray($)?$:[$];for(let K of G){if(!K)continue;if(B[K]){j=B[K],z=K;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)tw.success(`Configuration loaded from package.json: ${z}`);return{config:pz(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)tw.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:WX(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw S1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return MX.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);MX.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Ww(w,"config"),Ww(w,".config"),$?Ww(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Ww(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Ww(E1(),".config",w),Ww(E1(),".config"),E1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function WX(w,$,Y=!1){let A=new HQ,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=xX.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}function ez(w){return UQ.readFileSync(w,"utf8")}function QQ(w,$){let Y=[];function A(X){let J;try{J=UQ.readdirSync(X)}catch{return}for(let U of J){let W=Ew.join(X,U);try{if(UQ.statSync(W).isDirectory())A(W);else if(U===$)Y.push(X)}catch{continue}}}return A(w),Y}function L(w,$,Y){if(Y||z0.verbose)console.debug(`[tlsx:${w}] ${$}`)}function w2(){return oz.env.SUDO_PASSWORD}function fE(w){let $=w.toLowerCase();return NE.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function kX(w){if(Array.isArray(w))return w.map((Y)=>kX(Y));if(typeof w==="string")return EE.test(w)?a9:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(fE(Y)){$[Y]=a9;continue}$[Y]=kX(A)}return $}function cX(w){return JSON.stringify(kX(w))}function TE(w){let $=w2();if(!$||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(w))return w;let Y=$.replace(/'/g,"'\\''"),A=w.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function T$(w,$={}){let Y=TE(w);try{let{stdout:A,stderr:X}=await qE(Y,{cwd:$.cwd||oz.cwd(),timeout:$.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${w}
127
- Error: ${A.message}`);throw X.stack=A.stack,X}}function $2(w){if(w.domain)return w.domain;if(w.domains?.length)return w.domains[0];throw Error("Either domain or domains must be specified")}function RQ(w){let $=Ew.join(KE.homedir(),".stacks","ssl"),Y=w.basePath&&w.basePath.trim()!==""?w.basePath:z0.basePath&&z0.basePath.trim()!==""?z0.basePath:$,A=w.certPath?Ew.isAbsolute(w.certPath)?w.certPath:Ew.join(Y,w.certPath):Ew.join(Y,z0.certPath),X=w.keyPath?Ew.isAbsolute(w.keyPath)?w.keyPath:Ew.join(Y,w.keyPath):Ew.join(Y,z0.keyPath),J=w.caCertPath?Ew.isAbsolute(w.caCertPath)?w.caCertPath:Ew.join(Y,w.caCertPath):Ew.join(Y,z0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function Y2(w){let $=[],Y=new Set;if(w.domain)Y.add(w.domain);if(w.domains?.length)w.domains.forEach((A)=>Y.add(A));for(let A of Y)$.push({type:2,value:A});if(w.altNameIPs?.length)for(let A of w.altNameIPs)$.push({type:7,ip:A});if(w.altNameURIs?.length)for(let A of w.altNameURIs)$.push({type:6,value:A});if(w.subjectAltNames?.length)$.push(...w.subjectAltNames);return L(_.CERT,`Generated ${$.length} Subject Alternative Names`,w.verbose),$}function MQ(w){let $=w.notBeforeDays??Tw.DEFAULT_NOT_BEFORE_DAYS,Y=w.validityDays??(w.validityYears?w.validityYears*365:Tw.DEFAULT_VALIDITY_DAYS);L(_.CERT,"Calculating certificate validity dates",w.verbose);let A=new Date(Date.now()-86400*$*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),L(_.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,w.verbose),{notBefore:A,notAfter:X}}function MY(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function $w(w,$){let Y=MY($.length);return Buffer.concat([Buffer.from([w]),Y,$])}function OY(w){let $=w.split(".").map(Number),Y=[];Y.push(40*$[0]+$[1]);for(let A=2;A<$.length;A++){let X=$[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return $w(Hw.OID,Buffer.from(Y))}function WQ(w){let $;if(typeof w==="bigint"){let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else $=w;if($[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return $w(Hw.INTEGER,$)}function A2(w,$=0){return $w(Hw.BIT_STRING,Buffer.concat([Buffer.from([$]),w]))}function X2(w){return $w(Hw.OCTET_STRING,w)}function ww(...w){return $w(Hw.SEQUENCE,Buffer.concat(w))}function HE(...w){return $w(Hw.SET,Buffer.concat(w))}function RE(w){return $w(Hw.PRINTABLE_STRING,Buffer.from(w,"ascii"))}function ME(w){return $w(Hw.UTF8_STRING,Buffer.from(w,"utf8"))}function IE(){return Buffer.from([Hw.NULL,0])}function s9(w,$,Y=!0){let A=160|w|(Y?0:0),X=MY($.length);return Buffer.concat([Buffer.from([A]),X,$])}function o9(w){let $=w.getUTCFullYear();if($>=2050){let Y=w.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return $w(Hw.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=($%100).toString().padStart(2,"0"),A=(w.getUTCMonth()+1).toString().padStart(2,"0"),X=w.getUTCDate().toString().padStart(2,"0"),J=w.getUTCHours().toString().padStart(2,"0"),U=w.getUTCMinutes().toString().padStart(2,"0"),W=w.getUTCSeconds().toString().padStart(2,"0"),Q=`${Y}${A}${X}${J}${U}${W}Z`;return $w(Hw.UTC_TIME,Buffer.from(Q,"ascii"))}}function VE(w,$){return ww(o9(w),o9($))}function e9(w){let $=[];for(let Y of w){let A;switch(Y.shortName){case"CN":A=l0.COMMON_NAME;break;case"C":A=l0.COUNTRY;break;case"L":A=l0.LOCALITY;break;case"ST":A=l0.STATE;break;case"O":A=l0.ORGANIZATION;break;case"OU":A=l0.ORGANIZATIONAL_UNIT;break;default:continue}let X=Y.shortName==="C"?RE(Y.value):ME(Y.value),J=ww(OY(A),X);$.push(HE(J))}return ww(...$)}function J2(w){return ww(OY(w),IE())}function CE(w){return w.export({type:"spki",format:"der"})}function yE(w){if(w.includes(":")){let $=w;if(w.includes("::")){let X=w.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],W=8-J.length-U.length,Q=Array.from({length:W},()=>"0");$=[...J,...Q,...U].join(":")}let Y=$.split(":"),A=Buffer.alloc(16);for(let X=0;X<8;X++){let J=Number.parseInt(Y[X]||"0",16);A.writeUInt16BE(J,X*2)}return A}else{let $=w.split(".").map((Y)=>Number.parseInt(Y,10));return Buffer.from($)}}function OE(w){let $=[];for(let Y of w)if(Y.type===2&&Y.value){let A=MY(Y.value.length);$.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=yE(Y.ip),X=MY(A.length);$.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=MY(Y.value.length);$.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return ww(...$)}function LE(w,$){if(w){if($!==void 0)return ww($w(1,Buffer.from([255])),WQ($));return ww($w(1,Buffer.from([255])))}return ww()}function _E(w){let $=0;if(w.digitalSignature)$|=128;if(w.keyEncipherment)$|=32;if(w.keyCertSign)$|=4;if(w.cRLSign)$|=2;let Y=0,A=$;while(A>0&&(A&1)===0)Y++,A>>=1;if($===0)Y=7;return A2(Buffer.from([$]),Y)}function SE(w){let $=[];if(w.serverAuth)$.push(OY(l0.SERVER_AUTH));if(w.clientAuth)$.push(OY(l0.CLIENT_AUTH));return ww(...$)}function HY(w,$,Y){let A=[OY(w)];if($)A.push($w(1,Buffer.from([255])));return A.push(X2(Y)),ww(...A)}function ZE(w){let $=[];if($.push(s9(0,WQ(2))),$.push(WQ(w.serialNumber)),$.push(J2(l0.SHA256_WITH_RSA)),$.push(e9(w.issuer)),$.push(VE(w.notBefore,w.notAfter)),$.push(e9(w.subject)),$.push(CE(w.publicKey)),w.extensions){let Y=[];if(w.extensions.basicConstraints)Y.push(HY(l0.BASIC_CONSTRAINTS,w.extensions.basicConstraints.critical??!0,LE(w.extensions.basicConstraints.isCA,w.extensions.basicConstraints.pathLenConstraint)));if(w.extensions.keyUsage)Y.push(HY(l0.KEY_USAGE,w.extensions.keyUsage.critical??!0,_E(w.extensions.keyUsage)));if(w.extensions.extendedKeyUsage)Y.push(HY(l0.EXTENDED_KEY_USAGE,!1,SE(w.extensions.extendedKeyUsage)));if(w.extensions.subjectAltName?.length)Y.push(HY(l0.SUBJECT_ALT_NAME,!1,OE(w.extensions.subjectAltName)));if(w.extensions.subjectKeyIdentifier)Y.push(HY(l0.SUBJECT_KEY_IDENTIFIER,!1,X2(w.extensions.subjectKeyIdentifier)));if(Y.length>0)$.push(s9(3,ww(...Y)))}return ww(...$)}function kE(w,$){let Y=Z1.createSign("SHA256");Y.update(w);let A=Y.sign($);return ww(w,J2(l0.SHA256_WITH_RSA),A2(A))}function hE(w,$){let Y=w.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${$}-----
124
+ `;return Y}}function DT(w,$,Y={}){return C9(w,$,Y,new WeakMap)}function C9(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let Q=U(w,$);if(Q!==void 0)return Q}if(Array.isArray($)||Array.isArray(w))return V9(w,$,X,A);if(!jw($)||!jw(w))return $;return PT(w,$,Y,A)}function V9(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return kT(w,$);case"smart":return ZT(w,$,A);default:return $}return $}function kT(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>gU(X,A)))Y.push(A);return Y}function ZT(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(jw($[0])&&jw(w[0]))return xT(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function xT(w,$,Y){let A=[...$];for(let X of w){if(!jw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let Q of J)if(Q in X){if(A.find((W)=>jw(W)&&(Q in W)&&W[Q]===X[Q])){U=!0;break}}if(!U)A.push(X)}return A}function PT(w,$,Y,A){let X=$;if(jw(X)&&A.has(X))return A.get(X);let J={...w};if(jw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let Q=X[U],W=J[U];if(Y.skipNullish&&(Q===null||Q===void 0))continue;if(Q===null||Q===void 0){J[U]=Q;continue}if(jw(Q)&&jw(W))J[U]=C9(W,Q,Y,A);else if(Array.isArray(Q)||Array.isArray(W))J[U]=V9(W,Q,Y.arrayMergeMode||"smart",A);else J[U]=Q}return J}function L9(w,$,Y="replace"){return DT(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function gU(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!gU(w[Y],$[Y]))return!1;return!0}if(jw(w)&&jw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!gU(w[X],$[X]))return!1}return!0}return!1}function jw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class S9{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:Q=!1}=Y;if(X){let j=BX.getWithFileCheck("file",w);if(j){if(Q)console.log(`Configuration loaded from cache: ${w}`);return j}}let W=async()=>{if(!rA(w))return null;try{let j=`?t=${Date.now()}`,B=await import(w+j),f=B.default||B,z="default"in B,G=Object.keys(B).length>0;if(!z&&!G)throw new qX(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new qX(w,Error("Configuration must export a valid object"),"unknown");let T={config:L9($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)BX.setWithFileCheck("file",T,w,J);return T}catch(j){throw j instanceof Error?y1.configLoad(w,j):y1.configLoad(w,Error(String(j)))}};if(U)return tU.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(MU($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);let A=$===void 0?[]:Array.isArray($)?$:[$];for(let J of A){if(!J)continue;if(Y.push(J,`.${J}.config`,`${J}.config`,`.${J}`),w)Y.push(`${w}.${J}.config`,`.${w}.${J}.config`)}let X=new Set;return Y.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess(w){return _T(async()=>{return rA(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!rA(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let Q=MU(w,`${J}${U}`);if(await this.checkFileAccess(Q))A.push(Q)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let Q=MU(w,U);if(await this.checkFileAccess(Q))A.push(Q)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some(($)=>$.test(w))}async validateConfigFile(w){let $=[];try{if(!rA(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class O9{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:Q=!0,verbose:W=!1}=Y,j=async()=>{let B=[],f=[],z={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:Q,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,z);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],z);else return this.validateWithJSONSchema(w,$,z)}catch(G){return B.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:B,warnings:f}}};if(Q)return await tU.track("validateConfiguration",j);return j()}async validateWithSchemaFile(w,$,Y){try{if(!TF($))throw new NX($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new NX($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,Q=Array.isArray($.type)?$.type:[$.type];if(!Q.includes(U)){if(A.push({path:Y,message:`Expected type ${Q.join(" or ")}, got ${U}`,expected:Q.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let Q=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let Q of $.required)if(!(Q in U)){if(A.push({path:Y?`${Y}.${Q}`:Q,message:`Missing required property '${Q}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[Q,W]of Object.entries($.properties))if(Q in U){let j=Y?`${Y}.${Q}`:Q;if(this.validateObjectAgainstSchema(U[Q],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let Q=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!Q.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),Q=this.validateWithRule(U,J,J.path);if(A.push(...Q),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:iT},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function bT(w){if(!w)return"";let $=Array.isArray(w)?w.filter(Boolean):[w];if($.length===0)return"";if($.length===1)return` or alias "${$[0]}"`;return` or aliases ${$.map((Y)=>`"${Y}"`).join(", ")}`}class h9{fileLoader=new S9;envProcessor=new XW;validator=new O9;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let Q;try{Q=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;Q={...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 B=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!B&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),z=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(z||B))throw W;if(f&&(!j||!z))Q={...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)Q={...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 Q={...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(Q.config,X,J,U.name);if(Y?.enabled&&Q)this.cacheResult(U.name||"",Q,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)nw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);Q.metrics=W}return Q}catch(Q){if(Q instanceof Error&&Q.name==="ConfigNotFoundError")throw Q;let W=Date.now()-$;throw nw.error(`Configuration loading failed after ${W}ms:`,[Q instanceof Error?Q:Error(String(Q))]),Q}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:Q,checkEnv:W=!0,arrayStrategy:j="replace",verbose:B=!1}=w,f=J||yX.cwd(),z=[],G=await this.loadLocalConfiguration(A,X,f,U,Q,j,B,W,Y);if(G)return z.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,z,W,A,B);let T=await this.loadHomeConfiguration(A,X,Q,j,B,W);if(T)return z.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,z,W,A,B);let K=await this.loadPackageJsonConfiguration(A,X,f,Q,j,B,W);if(K)return z.push(Ww(f,"package.json")),this.finalizeResult(K,z,W,A,B);if(z.push(...this.getAllSearchPaths(A,X,f,U)),$)throw y1.configNotFound(A,z,X);return{...await this.applyEnvironmentVariables(A,Q,W,B),warnings:[`No configuration file found for "${A}"${bT(X)}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,Q,W){let j=Q?aA(w,X,U):X,B=this.getLocalDirectories(Y,A);for(let f of B){if(U)nw.info(`Searching for configuration in: ${f}`);let z=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(z,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)nw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?aA(w,Y,X):Y,Q=[Ww(B1(),".config",w),Ww(B1(),".config"),B1()];for(let W of Q){if(X)nw.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths(w,W,$),B=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(B){if(X)nw.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let Q=U?aA(w,A,J):A;try{let W=Ww(Y,"package.json");if(!_K(W))return null;let j={};try{j=JSON.parse(DK(W,"utf8"))}catch(z){if(J)nw.warn("Failed to parse package.json:",[z instanceof Error?z:Error(String(z))]);return null}let B=j[w],f=w;if(!B&&$){let z=Array.isArray($)?$:[$];for(let G of z){if(!G)continue;if(j[G]){B=j[G],f=G;break}}}if(B&&typeof B==="object"&&!Array.isArray(B)){if(J)nw.success(`Configuration loaded from package.json: ${f}`);return{config:L9(Q,B,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)nw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:aA(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw y1.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return BX.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);BX.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias){let A=Array.isArray($.alias)?$.alias.join(","):$.alias;Y.push(`alias:${A}`)}if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,Ww(w,"config"),Ww(w,".config"),$?Ww(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(Ww(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[Ww(B1(),".config",w),Ww(B1(),".config"),B1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function aA(w,$,Y=!1){let A=new XW,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,Q=[]){let W={...U};for(let[j,B]of Object.entries(U)){let f=[...Q,j],z=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((K)=>K.toUpperCase()).join("")}`,`${X}_${f.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of z)if(G=yX.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof B==="boolean")W[j]=["true","1","yes"].includes(G.toLowerCase());else if(typeof B==="number"){let K=Number(G);if(!Number.isNaN(K))W[j]=K}else if(Array.isArray(B))try{W[j]=JSON.parse(G)}catch{W[j]=G.split(",").map((K)=>K.trim())}else W[j]=G;else if(B&&typeof B==="object"&&!Array.isArray(B))W[j]=J(B,f)}return W}return J($)}function k9(w){return dU.readFileSync(w,"utf8")}function nU(w,$){let Y=[];function A(X){let J;try{J=dU.readdirSync(X)}catch{return}for(let U of J){let Q=Tw.join(X,U);try{if(dU.statSync(Q).isDirectory())A(Q);else if(U===$)Y.push(X)}catch{continue}}}return A(w),Y}function S(w,$,Y){if(Y||B0.verbose)console.debug(`[tlsx:${w}] ${$}`)}function Z9(){return D9.env.SUDO_PASSWORD}function nT(w){let $=w.toLowerCase();return gT.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function HX(w){if(Array.isArray(w))return w.map((Y)=>HX(Y));if(typeof w==="string")return dT.test(w)?Of:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(nT(Y)){$[Y]=Of;continue}$[Y]=HX(A)}return $}function LX(w){return JSON.stringify(HX(w))}function lT(w){let $=Z9();if(!$||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test(w))return w;let Y=$.replace(/'/g,"'\\''"),A=w.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function z$(w,$={}){let Y=lT(w);try{let{stdout:A,stderr:X}=await mT(Y,{cwd:$.cwd||D9.cwd(),timeout:$.timeout||30000});return{stdout:A.trim(),stderr:X.trim()}}catch(A){let X=Error(`Failed to execute command: ${w}
125
+ Error: ${A.message}`);throw X.stack=A.stack,X}}function x9(w){if(w.domain)return w.domain;if(w.domains?.length)return w.domains[0];throw Error("Either domain or domains must be specified")}function JW(w){let $=Tw.join(vT.homedir(),".stacks","ssl"),Y=w.basePath&&w.basePath.trim()!==""?w.basePath:B0.basePath&&B0.basePath.trim()!==""?B0.basePath:$,A=w.certPath?Tw.isAbsolute(w.certPath)?w.certPath:Tw.join(Y,w.certPath):Tw.join(Y,B0.certPath),X=w.keyPath?Tw.isAbsolute(w.keyPath)?w.keyPath:Tw.join(Y,w.keyPath):Tw.join(Y,B0.keyPath),J=w.caCertPath?Tw.isAbsolute(w.caCertPath)?w.caCertPath:Tw.join(Y,w.caCertPath):Tw.join(Y,B0.caCertPath);return{certPath:A,keyPath:X,caCertPath:J,basePath:Y}}function P9(w){let $=[],Y=new Set;if(w.domain)Y.add(w.domain);if(w.domains?.length)w.domains.forEach((A)=>Y.add(A));for(let A of Y)$.push({type:2,value:A});if(w.altNameIPs?.length)for(let A of w.altNameIPs)$.push({type:7,ip:A});if(w.altNameURIs?.length)for(let A of w.altNameURIs)$.push({type:6,value:A});if(w.subjectAltNames?.length)$.push(...w.subjectAltNames);return S(O.CERT,`Generated ${$.length} Subject Alternative Names`,w.verbose),$}function UW(w){let $=w.notBeforeDays??Nw.DEFAULT_NOT_BEFORE_DAYS,Y=w.validityDays??(w.validityYears?w.validityYears*365:Nw.DEFAULT_VALIDITY_DAYS);S(O.CERT,"Calculating certificate validity dates",w.verbose);let A=new Date(Date.now()-86400*$*1000),X=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),S(O.CERT,`Validity period: ${A.toISOString()} to ${X.toISOString()}`,w.verbose),{notBefore:A,notAfter:X}}function XY(w){if(w<128)return Buffer.from([w]);let $=[],Y=w;while(Y>0)$.unshift(Y&255),Y>>=8;return Buffer.from([128|$.length,...$])}function e0(w,$){let Y=XY($.length);return Buffer.concat([Buffer.from([w]),Y,$])}function jY(w){let $=w.split(".").map(Number),Y=[];Y.push(40*$[0]+$[1]);for(let A=2;A<$.length;A++){let X=$[A],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;Y.push(...J)}return e0(Hw.OID,Buffer.from(Y))}function lU(w){let $;if(typeof w==="bigint"){let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof w==="number")if(w===0)$=Buffer.from([0]);else{let Y=w.toString(16).padStart(2,"0");$=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else $=w;if($[0]&128)$=Buffer.concat([Buffer.from([0]),$]);return e0(Hw.INTEGER,$)}function i9(w,$=0){return e0(Hw.BIT_STRING,Buffer.concat([Buffer.from([$]),w]))}function b9(w){return e0(Hw.OCTET_STRING,w)}function o0(...w){return e0(Hw.SEQUENCE,Buffer.concat(w))}function pT(...w){return e0(Hw.SET,Buffer.concat(w))}function rT(w){return e0(Hw.PRINTABLE_STRING,Buffer.from(w,"ascii"))}function tT(w){return e0(Hw.UTF8_STRING,Buffer.from(w,"utf8"))}function aT(){return Buffer.from([Hw.NULL,0])}function hf(w,$,Y=!0){let A=160|w|(Y?0:0),X=XY($.length);return Buffer.concat([Buffer.from([A]),X,$])}function _f(w){let $=w.getUTCFullYear();if($>=2050){let Y=w.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return e0(Hw.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=($%100).toString().padStart(2,"0"),A=(w.getUTCMonth()+1).toString().padStart(2,"0"),X=w.getUTCDate().toString().padStart(2,"0"),J=w.getUTCHours().toString().padStart(2,"0"),U=w.getUTCMinutes().toString().padStart(2,"0"),Q=w.getUTCSeconds().toString().padStart(2,"0"),W=`${Y}${A}${X}${J}${U}${Q}Z`;return e0(Hw.UTC_TIME,Buffer.from(W,"ascii"))}}function sT(w,$){return o0(_f(w),_f($))}function Df(w){let $=[];for(let Y of w){let A;switch(Y.shortName){case"CN":A=d0.COMMON_NAME;break;case"C":A=d0.COUNTRY;break;case"L":A=d0.LOCALITY;break;case"ST":A=d0.STATE;break;case"O":A=d0.ORGANIZATION;break;case"OU":A=d0.ORGANIZATIONAL_UNIT;break;default:continue}let X=Y.shortName==="C"?rT(Y.value):tT(Y.value),J=o0(jY(A),X);$.push(pT(J))}return o0(...$)}function u9(w){return o0(jY(w),aT())}function oT(w){return w.export({type:"spki",format:"der"})}function eT(w){if(w.includes(":")){let $=w;if(w.includes("::")){let X=w.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],Q=8-J.length-U.length,W=Array.from({length:Q},()=>"0");$=[...J,...W,...U].join(":")}let Y=$.split(":"),A=Buffer.alloc(16);for(let X=0;X<8;X++){let J=Number.parseInt(Y[X]||"0",16);A.writeUInt16BE(J,X*2)}return A}else{let $=w.split(".").map((Y)=>Number.parseInt(Y,10));return Buffer.from($)}}function w7(w){let $=[];for(let Y of w)if(Y.type===2&&Y.value){let A=XY(Y.value.length);$.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=eT(Y.ip),X=XY(A.length);$.push(Buffer.concat([Buffer.from([135]),X,A]))}else if(Y.type===6&&Y.value){let A=XY(Y.value.length);$.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return o0(...$)}function $7(w,$){if(w){if($!==void 0)return o0(e0(1,Buffer.from([255])),lU($));return o0(e0(1,Buffer.from([255])))}return o0()}function Y7(w){let $=0;if(w.digitalSignature)$|=128;if(w.keyEncipherment)$|=32;if(w.keyCertSign)$|=4;if(w.cRLSign)$|=2;let Y=0,A=$;while(A>0&&(A&1)===0)Y++,A>>=1;if($===0)Y=7;return i9(Buffer.from([$]),Y)}function A7(w){let $=[];if(w.serverAuth)$.push(jY(d0.SERVER_AUTH));if(w.clientAuth)$.push(jY(d0.CLIENT_AUTH));return o0(...$)}function YY(w,$,Y){let A=[jY(w)];if($)A.push(e0(1,Buffer.from([255])));return A.push(b9(Y)),o0(...A)}function X7(w){let $=[];if($.push(hf(0,lU(2))),$.push(lU(w.serialNumber)),$.push(u9(d0.SHA256_WITH_RSA)),$.push(Df(w.issuer)),$.push(sT(w.notBefore,w.notAfter)),$.push(Df(w.subject)),$.push(oT(w.publicKey)),w.extensions){let Y=[];if(w.extensions.basicConstraints)Y.push(YY(d0.BASIC_CONSTRAINTS,w.extensions.basicConstraints.critical??!0,$7(w.extensions.basicConstraints.isCA,w.extensions.basicConstraints.pathLenConstraint)));if(w.extensions.keyUsage)Y.push(YY(d0.KEY_USAGE,w.extensions.keyUsage.critical??!0,Y7(w.extensions.keyUsage)));if(w.extensions.extendedKeyUsage)Y.push(YY(d0.EXTENDED_KEY_USAGE,!1,A7(w.extensions.extendedKeyUsage)));if(w.extensions.subjectAltName?.length)Y.push(YY(d0.SUBJECT_ALT_NAME,!1,w7(w.extensions.subjectAltName)));if(w.extensions.subjectKeyIdentifier)Y.push(YY(d0.SUBJECT_KEY_IDENTIFIER,!1,b9(w.extensions.subjectKeyIdentifier)));if(Y.length>0)$.push(hf(3,o0(...Y)))}return o0(...$)}function J7(w,$){let Y=I1.createSign("SHA256");Y.update(w);let A=Y.sign($);return o0(w,u9(d0.SHA256_WITH_RSA),i9(A))}function U7(w,$){let Y=w.toString("base64"),A=[];for(let X=0;X<Y.length;X+=64)A.push(Y.slice(X,X+64));return`-----BEGIN ${$}-----
128
126
  ${A.join(`
129
127
  `)}
130
128
  -----END ${$}-----
131
- `}function IQ(){let w=Z1.randomBytes(20);return w[0]=w[0]&127||1,w}function U2(w=2048){let{privateKey:$,publicKey:Y}=Z1.generateKeyPairSync("rsa",{modulusLength:w});return{privateKey:$,publicKey:Y}}function DE(w){let $=w.export({type:"spki",format:"der"});return Z1.createHash("sha1").update($).digest()}function Q2(w){let $={serialNumber:w.serialNumber||IQ(),notBefore:w.notBefore,notAfter:w.notAfter,subject:w.subject,issuer:w.issuer||w.subject,publicKey:w.publicKey,extensions:{basicConstraints:{isCA:w.isCA??!1,critical:!0,pathLenConstraint:w.pathLenConstraint},subjectKeyIdentifier:DE(w.publicKey)}};if(w.keyUsage)$.extensions.keyUsage={...w.keyUsage,critical:!0};if(w.extendedKeyUsage)$.extensions.extendedKeyUsage=w.extendedKeyUsage;if(w.subjectAltName?.length)$.extensions.subjectAltName=w.subjectAltName;let Y=ZE($),A=kE(Y,w.signingKey);return{certificate:hE(A,"CERTIFICATE"),certificateDer:A}}function W2(w){return w.export({type:"pkcs8",format:"pem"})}function xE(w){return Z1.createPrivateKey(w)}function PE(w){let $=new Z1.X509Certificate(w),Y=$.publicKey,A=[],X=$.subject.split(`
132
- `);for(let J of X){let[U,...W]=J.split("="),Q=W.join("=");if(U&&Q)A.push({shortName:U.trim(),value:Q.trim()})}return{publicKey:Y,subject:A}}async function VQ(w={}){L("ca","Creating new Root CA Certificate",w.verbose);let $=w.keySize||Tw.DEFAULT_KEY_SIZE;L("ca",`Generating ${$}-bit RSA key pair`,w.verbose);let{privateKey:Y,publicKey:A}=U2($),X=[{shortName:"C",value:w.countryName||z0.countryName},{shortName:"ST",value:w.stateName||z0.stateName},{shortName:"L",value:w.localityName||z0.localityName},{shortName:"O",value:w.organization||"Local Development CA"},{shortName:"OU",value:w.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:w.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=MQ({validityYears:w.validityYears||Tw.DEFAULT_CA_VALIDITY_YEARS,verbose:w.verbose}),{certificate:W}=Q2({serialNumber:IQ(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:W2(Y),notBefore:J,notAfter:U}}async function CQ(w){if(L("ca","Generating new certificate",w.verbose),L("ca",`Options: ${cX(w)}`,w.verbose),!w.domain&&!w.domains?.length)throw Error("Either domain or domains must be specified");if(!w.rootCA?.certificate||!w.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:$}=PE(w.rootCA.certificate),Y=xE(w.rootCA.privateKey);L("ca",`Generating ${Tw.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,w.verbose);let A=Tw.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=U2(A),U=w.commonName||$2(w),W=w.certificateAttributes||[{shortName:"C",value:w.countryName||z0.countryName},{shortName:"ST",value:w.stateName||z0.stateName},{shortName:"L",value:w.localityName||z0.localityName},{shortName:"O",value:w.organizationName||z0.organizationName},{shortName:"CN",value:U}],{notBefore:Q,notAfter:B}=MQ({validityDays:w.validityDays||Tw.DEFAULT_VALIDITY_DAYS,verbose:w.verbose}),j=Y2(w),z=w.keyUsage||{digitalSignature:!0,keyEncipherment:!0},G=w.extKeyUsage||{serverAuth:!0},{certificate:K}=Q2({serialNumber:IQ(),notBefore:Q,notAfter:B,subject:W,issuer:$,publicKey:J,signingKey:Y,isCA:w.basicConstraints?.cA??!1,pathLenConstraint:w.basicConstraints?.pathLenConstraint,keyUsage:z,extendedKeyUsage:G,subjectAltName:j});return{certificate:K,privateKey:W2(X),notBefore:Q,notAfter:B}}function B2(w,$){L(_.STORAGE,`Storing certificate and private key with options: ${cX($)}`,$?.verbose);let{certPath:Y,keyPath:A}=RQ({basePath:$?.basePath,certPath:$?.certPath,keyPath:$?.keyPath});L(_.STORAGE,`Certificate path: ${Y}`,$?.verbose),L(_.STORAGE,`Private key path: ${A}`,$?.verbose);let X=BQ.dirname(Y);if(!ew.existsSync(X))L(_.STORAGE,`Creating certificate directory: ${X}`,$?.verbose),ew.mkdirSync(X,{recursive:!0});L(_.STORAGE,"Writing certificate file",$?.verbose),ew.writeFileSync(Y,w.certificate);let J=BQ.dirname(A);if(!ew.existsSync(J))L(_.STORAGE,`Creating private key directory: ${J}`,$?.verbose),ew.mkdirSync(J,{recursive:!0});return L(_.STORAGE,"Writing private key file",$?.verbose),ew.writeFileSync(A,w.privateKey),L(_.STORAGE,"Certificate and private key stored successfully",$?.verbose),Y}function j2(w,$){L(_.STORAGE,"Storing CA certificate",$?.verbose);let{caCertPath:Y}=RQ({basePath:$?.basePath,caCertPath:$?.caCertPath});L(_.STORAGE,`CA certificate path: ${Y}`,$?.verbose);let A=BQ.dirname(Y);if(!ew.existsSync(A))L(_.STORAGE,`Creating CA certificate directory: ${A}`,$?.verbose),ew.mkdirSync(A,{recursive:!0});return L(_.STORAGE,"Writing CA certificate file",$?.verbose),ew.writeFileSync(Y,w),L(_.STORAGE,"CA certificate stored successfully",$?.verbose),Y}function vX(w){let $;if(w.startsWith("-----BEGIN CERTIFICATE-----"))$=w;else $=ez(w);return new bE.X509Certificate($)}function iX(w){return vX(w).fingerprint256.replace(/:/g,"").toUpperCase()}function yQ(w){return z2(vX(w).subject)}function uE(w){let $=[],Y=w.split(`
133
- `);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)$.push({shortName:X.trim(),value:U.trim()})}return $}function z2(w){return uE(w).find(($)=>$.shortName==="CN")?.value||""}function cE(w){let $=[],Y=z2(w.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))$.push(Y);let A=w.subjectAltName;if(A){let X=A.split(", ");for(let J of X)if(J.startsWith("DNS:"))$.push(J.slice(4))}return[...new Set($)]}function OQ(w,$){let Y=vX(w),A=cE(Y);for(let X of A){if(X===$)return!0;if(X.startsWith("*.")){let J=X.slice(2);if($.endsWith(J)&&$.indexOf(".")===$.lastIndexOf("."))return!0}}return!1}async function iE(w,$){if(hX.platform()!=="darwin")return!1;try{let Y=iX(w);if(!Y)return L(_.TRUST,"Could not extract certificate fingerprint",$),!1;try{if(vE("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",$),!0}catch{}return L(_.TRUST,"Certificate fingerprint not found in system keychain",$),!1}catch(Y){return L(_.TRUST,`Error checking certificate trust: ${Y}`,$),!1}}async function LQ(w,$,Y){L(_.TRUST,`Adding certificate to system trust store with options: ${cX(Y)}`,Y?.verbose),L(_.TRUST,"Storing certificate and private key",Y?.verbose);let A=B2(w,Y);L(_.TRUST,"Storing CA certificate",Y?.verbose);let X=j2($,Y),J=hX.platform();L(_.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=lE[J];if(!U){let W=`Unsupported platform: ${J}`;throw L(_.TRUST,`Error: ${W}`,Y?.verbose),Error(W)}return await U.addCertificate(X,Y),L(_.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var gF,wz=30000,DX,Jz="https://acme-staging-v02.api.letsencrypt.org/directory",Uz="https://acme-v02.api.letsencrypt.org/directory",NX,tF="1.2.840.10045.2.1",aF="1.2.840.10045.3.1.7",sF="1.2.840.10045.4.3.2",oF="2.5.4.3",eF="1.2.840.113549.1.9.14",wq="2.5.29.17",MX,zQ,lq,nq=(w)=>w,rq=(w,$)=>{for(var Y in $)lq(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:pq.bind($,Y)})},tq=(w,$)=>()=>(w&&($=w(w=0)),$),Tz,Lz,_1,LY,_z,MN,IN,u9,GX,sU,Z0,s,VN,c9,CN,v9,yN,ON,cU,LN,i9,m9,vU,_N,SN,ZN,kN,KX,Sz,hN,k0,DN,xN,g9,FX,oU,f0,c,PN,d9,bN,l9,uN,cN,iU,vN,n9,p9,iN,mU,mN,gN,dN,lN,nN,qX,Zz,pN,rN="0.15.6",e0,OX,CY,eU,wQ,LX,$Q,YQ,yY,AQ,XQ,H$,kz,hz,fw,w$,Dz,xz,tN,sN,Pz,_X,s3,C0,m,o3,eN,e3,wE,wC,$C,r9,YC,$E,YE,AC,t9,XC,JC,UC,QC,WC,gU,AE,BC,Rw,uz,SX,cz,vz,TQ,iz,mz,ZX,gz,dz,S1,jE,tw,jC,zC,GC,sz,z0,Tw,_,L1,qE,a9="[redacted]",NE,EE,Hw,l0,mE,gE,dE,lE;var G2=t(()=>{gF=mF(import.meta.url);DX=new IY;NX=class NX extends Error{problem;httpStatus;constructor(w,$,Y){super(w);this.name="AcmeError",this.problem=$,this.httpStatus=Y}};MX=new Ez,zQ=new fz,lq=Object.defineProperty;Tz={};rq(Tz,{withErrorRecovery:()=>Mz,tryLoadConfig:()=>fN,loadConfigWithResult:()=>NN,loadConfig:()=>Oz,isRetryableError:()=>jN,isConfigNotFoundError:()=>BN,isBunfigError:()=>Iz,globalPerformanceMonitor:()=>LY,globalCache:()=>_1,getEnvOrDefault:()=>zN,generateConfigTypes:()=>TN,defaultGeneratedDir:()=>xz,defaultConfigDir:()=>Dz,deepMergeWithArrayStrategy:()=>NQ,deepMerge:()=>Vz,createLibraryConfig:()=>HN,config:()=>EN,bunfigPlugin:()=>RN,applyEnvVarsToConfig:()=>RY,TypeGenerationError:()=>YQ,SchemaValidationError:()=>yY,PluginError:()=>XQ,PerformanceMonitor:()=>KQ,FileSystemError:()=>$Q,ErrorFactory:()=>H$,EnvVarError:()=>LX,EnvProcessor:()=>PX,ConfigValidator:()=>EQ,ConfigValidationError:()=>eU,ConfigNotFoundError:()=>OX,ConfigMergeError:()=>wQ,ConfigLoader:()=>fQ,ConfigLoadError:()=>CY,ConfigFileLoader:()=>bX,ConfigCache:()=>GQ,CacheUtils:()=>_z,BunfigError:()=>e0,BrowserConfigError:()=>AQ,ArrayMergeStrategies:()=>kz});tN=tq(async()=>{Lz=import.meta.require,_1=new GQ,LY=new KQ,_z={createKey:aq,isEquivalent:sq,estimateMemoryUsage:oq},MN=HX(tU.cwd(),"config"),IN=HX(tU.cwd(),"src/generated"),u9=TX.env.CLARITY_LOG_DIR||zq($N(),"logs"),GX={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},sU=await YN(),Z0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},s=Z0,VN=Z0.red,c9=Z0.green,CN=Z0.yellow,v9=Z0.blue,yN=Z0.magenta,ON=Z0.cyan,cU=Z0.white,LN=Z0.gray,i9=Z0.bgRed,m9=Z0.bgYellow,vU=Z0.bold,_N=Z0.dim,SN=Z0.italic,ZN=Z0.underline,kN=Z0.reset,KX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Sz={debug:"\uD83D\uDD0D",info:v9("ℹ"),success:c9("✓"),warning:m9(cU(vU(" WARN "))),error:i9(cU(vU(" ERROR ")))},hN=new VX("stacks"),k0=new VX("bunfig",{showTags:!0}),DN=g0(VY.cwd(),"config"),xN=g0(VY.cwd(),"src/generated"),g9=fX.env.CLARITY_LOG_DIR||Bq(UN(),"logs"),FX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:g9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},oU=await QN(),f0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},c=f0,PN=f0.red,d9=f0.green,bN=f0.yellow,l9=f0.blue,uN=f0.magenta,cN=f0.cyan,iU=f0.white,vN=f0.gray,n9=f0.bgRed,p9=f0.bgYellow,iN=f0.bgGray,mU=f0.bold,mN=f0.dim,gN=f0.italic,dN=f0.underline,lN=f0.strikethrough,nN=f0.reset,qX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Zz={debug:"\uD83D\uDD0D",info:l9("ℹ"),success:d9("✓"),warning:p9(iU(mU(" WARN "))),error:n9(iU(mU(" ERROR ")))},pN=new yX("stacks"),e0=class extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},OX=class extends e0{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${A} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}},CY=class extends e0{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}},eU=class extends e0{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},wQ=class extends e0{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},LX=class extends e0{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}},$Q=class extends e0{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},YQ=class extends e0{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},yY=class extends e0{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},AQ=class extends e0{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}},XQ=class extends e0{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},H$={configNotFound(w,$,Y){return new OX(w,$,Y)},configLoad(w,$,Y){return new CY(w,$,Y)},configValidation(w,$,Y){return new eU(w,$,Y)},configMerge(w,$,Y,A){return new wQ(w,$,Y,A)},envVar(w,$,Y,A){return new LX(w,$,Y,A)},fileSystem(w,$,Y){return new $Q(w,$,Y)},typeGeneration(w,$,Y){return new YQ(w,$,Y)},schemaValidation(w,$,Y){return new yY(w,$,Y)},browserConfig(w,$,Y,A){return new AQ(w,$,Y,A)},plugin(w,$,Y){return new XQ(w,$,Y)}},kz={replace:"replace",concat:"concat",smart:"smart"},hz=/^https?:\/\//,fw=new yX("bunfig",{showTags:!0}),w$=new fQ,Dz=d0(i$.cwd(),"config"),xz=d0(i$.cwd(),"src/generated")});sN=RX.env.CLARITY_LOG_DIR||hq(aN(),"logs"),Pz={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:sN,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},_X={...Pz},s3=(async()=>{try{let{loadConfig:w}=await tN().then(()=>Tz),$=await w({name:"clarity",alias:"logging",defaultConfig:Pz,cwd:RX.cwd()});if($)Object.assign(_X,$)}catch{}return _X})();C0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},m=C0,o3=C0.red,eN=C0.green,e3=C0.yellow,wE=C0.blue,wC=C0.magenta,$C=C0.cyan,r9=C0.white,YC=C0.gray,$E=C0.bgRed,YE=C0.bgYellow,AC=C0.bgGray,t9=C0.bold,XC=C0.dim,JC=C0.italic,UC=C0.underline,QC=C0.strikethrough,WC=C0.reset,gU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},AE={debug:"\uD83D\uDD0D",info:wE("ℹ"),success:eN("✓"),warning:YE(r9(t9(" WARN "))),error:$E(r9(t9(" ERROR ")))};BC=new uX("stacks");Rw=class Rw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};uz=class uz extends Rw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};SX=class SX extends Rw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};cz=class cz extends Rw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};vz=class vz extends Rw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};TQ=class TQ extends Rw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};iz=class iz extends Rw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};mz=class mz extends Rw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};ZX=class ZX extends Rw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};gz=class gz extends Rw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};dz=class dz extends Rw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};S1={configNotFound(w,$,Y){return new uz(w,$,Y)},configLoad(w,$,Y){return new SX(w,$,Y)},configValidation(w,$,Y){return new cz(w,$,Y)},configMerge(w,$,Y,A){return new vz(w,$,Y,A)},envVar(w,$,Y,A){return new TQ(w,$,Y,A)},fileSystem(w,$,Y){return new iz(w,$,Y)},typeGeneration(w,$,Y){return new mz(w,$,Y)},schemaValidation(w,$,Y){return new ZX(w,$,Y)},browserConfig(w,$,Y,A){return new gz(w,$,Y,A)},plugin(w,$,Y){return new dz(w,$,Y)}};jE=/^https?:\/\//;tw=new uX("bunfig",{showTags:!0});jC=new az;zC=Ww(xX.cwd(),"config"),GC=Ww(xX.cwd(),"src/generated"),sz={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:VU.join(IU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:VU.join(IU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:VU.join(IU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},z0=sz,Tw={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"},L1={info:(...w)=>console.log(...w),warn:(...w)=>console.warn(...w),success:(...w)=>console.log(...w),error:(...w)=>console.error(...w),debug:(...w)=>console.debug(...w)};qE=FE(GE);NE=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),EE=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;Hw={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},l0={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"};mE={platform:"darwin",async addCertificate(w,$){if(await iE(w,$?.verbose)){L(_.TRUST,"Certificate is already trusted, skipping trust store update",$?.verbose),L1.success("Certificate is already trusted in system keychain");return}L(_.TRUST,"Adding certificate to macOS keychain",$?.verbose),await T$(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${w}`)},async removeCertificate(w,$,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from macOS keychain`,$?.verbose);try{await T$(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),L(_.TRUST,`Removed certificate ${A} from macOS keychain`,$?.verbose)}catch(X){throw L(_.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},gE={platform:"win32",async addCertificate(w,$){L(_.TRUST,"Adding certificate to Windows certificate store",$?.verbose),await T$(`certutil -f -v -addstore -enterprise Root ${w}`)},async removeCertificate(w,$,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from Windows certificate store`,$?.verbose);try{await T$(`certutil -delstore -enterprise Root "${A}"`),L(_.TRUST,`Removed certificate ${A} from Windows certificate store`,$?.verbose)}catch(X){throw L(_.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},dE={platform:"linux",async addCertificate(w,$){L(_.TRUST,"Adding certificate to Linux certificate store",$?.verbose);let Y=hX.homedir(),A=Tw.LINUX_CERT_DB_FILENAME,X=Tw.LINUX_TRUST_ARGS;L(_.TRUST,`Searching for certificate databases in ${Y}`,$?.verbose);let J=QQ(Y,A);if(J.length===0){L1.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}`,$?.verbose);try{L(_.TRUST,`Attempting to delete existing cert for ${z0.commonName}`,$?.verbose),await T$(`certutil -d sql:${U} -D -n ${z0.commonName}`)}catch(W){L(_.TRUST,`Warning: Error deleting existing cert: ${W}`,$?.verbose),console.warn(`Error deleting existing cert: ${W}`)}L(_.TRUST,`Adding new certificate to ${U}`,$?.verbose),await T$(`certutil -d sql:${U} -A -t ${X} -n ${z0.commonName} -i ${w}`),L1.info(`Cert added to ${U}`)}},async removeCertificate(w,$,Y){let A=Y||z0.commonName;L(_.TRUST,`Removing certificate ${A} from Linux certificate store`,$?.verbose);let X=hX.homedir(),J=Tw.LINUX_CERT_DB_FILENAME;L(_.TRUST,`Searching for certificate databases in ${X}`,$?.verbose);let U=QQ(X,J);if(U.length===0){L1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of U){L(_.TRUST,`Processing certificate database in ${W}`,$?.verbose);try{await T$(`certutil -d sql:${W} -D -n "${A}"`),L1.info(`Cert removed from ${W}`)}catch(Q){L(_.TRUST,`Error removing cert from ${W}: ${Q}`,$?.verbose),console.warn(`Error removing cert from ${W}: ${Q}`)}}}},lE={darwin:mE,win32:gE,linux:dE}});var mX=t(()=>{G2()});import{homedir as _Q}from"node:os";import{join as SQ,resolve as Wy}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",pE,ZQ;var kQ=t(()=>{NU();pE={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:SQ(_Q(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:SQ(_Q(),".stacks","ssl","stacks.localhost.crt"),keyPath:SQ(_Q(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},ZQ=pE});function m$(w){try{return iX(w)}catch{return null}}function hQ(w){try{return yQ(w)||null}catch{return null}}function gX(w,$){try{return $.every((Y)=>OQ(w,Y))}catch{return!1}}var dX=t(()=>{mX()});import{existsSync as K2,statSync as F2}from"fs";import{existsSync as oQ,mkdirSync as eE,readdirSync as wf,writeFileSync as $f}from"fs";import{homedir as k1}from"os";import{dirname as q2,resolve as p0}from"path";import g$ from"process";import{join as Yf,relative as Af,resolve as N2}from"path";import Q8 from"process";import{existsSync as o2,mkdirSync as Ry,readdirSync as My,writeFileSync as Iy}from"fs";import{homedir as DQ}from"os";import{dirname as yy,resolve as n0}from"path";import SY from"process";import{join as Xf,relative as Jf,resolve as E2}from"path";import W8 from"process";import{existsSync as e2,mkdirSync as Zy,readdirSync as ky,writeFileSync as hy}from"fs";import{dirname as xy,resolve as B8}from"path";import eQ from"process";import{Buffer as M$}from"buffer";import{createCipheriv as Uf,createDecipheriv as Qf,randomBytes as xQ}from"crypto";import{closeSync as PQ,createReadStream as f2,createWriteStream as Wf,existsSync as bQ,fsyncSync as T2,openSync as H2,writeFileSync as Bf}from"fs";import{access as jf,constants as R2,mkdir as zf,readdir as lX,rename as M2,stat as h1,unlink as nX,writeFile as uQ}from"fs/promises";import{join as D1}from"path";import h0 from"process";import{pipeline as Gf}from"stream/promises";import{createGzip as I2}from"zlib";import x1 from"process";import A$ from"process";import{Buffer as $$}from"buffer";import{createCipheriv as Kf,createDecipheriv as Ff,randomBytes as cQ}from"crypto";import{closeSync as vQ,createReadStream as V2,createWriteStream as qf,existsSync as pX,fsyncSync as C2,openSync as y2,writeFileSync as Nf}from"fs";import{access as Ef,constants as O2,mkdir as ff,readdir as rX,rename as L2,stat as P1,unlink as tX,writeFile as iQ}from"fs/promises";import{isAbsolute as Tf,join as b1,resolve as Hf}from"path";import x from"process";import{pipeline as Rf}from"stream/promises";import{createGzip as _2}from"zlib";import u1 from"process";import X$ from"process";import aX from"process";import{existsSync as sX}from"fs";import{resolve as mQ}from"path";import{existsSync as Mf}from"fs";import{existsSync as If,readdirSync as Vf}from"fs";import{extname as gQ,resolve as S2}from"path";import Cf from"process";import{join as OT,relative as LT,resolve as m2}from"path";import N8 from"process";import{Buffer as Y$}from"buffer";import{createCipheriv as ZT,createDecipheriv as kT,randomBytes as rQ}from"crypto";import{closeSync as tQ,createReadStream as g2,createWriteStream as hT,existsSync as eX,fsyncSync as d2,openSync as l2,writeFileSync as DT}from"fs";import{access as xT,constants as n2,mkdir as PT,readdir as w8,rename as p2,stat as c1,unlink as $8,writeFile as aQ}from"fs/promises";import{isAbsolute as bT,join as v1,resolve as uT}from"path";import P from"process";import{pipeline as cT}from"stream/promises";import{createGzip as r2}from"zlib";import i1 from"process";import J$ from"process";function aE(w,$){this[w]=tE.bind(null,$)}class BW{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!K2(w))return!0;return F2(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=K2(Y)?F2(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class jW{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function yf(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function Of(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function Lf(w){return w.getStats().size*2}function zW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&Y0($[0])&&"id"in $[0]&&$[0].id===3&&Y0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(Y0($)&&Y0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(Y0(w)&&"arr"in w&&Array.isArray(w.arr)&&Y0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&Y0($[0])&&Y0(w[0])){let A=[...$];for(let X of w)if(Y0(X)&&"name"in X){if(!A.find((U)=>Y0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(Y0(X)&&"path"in X){if(!A.find((U)=>Y0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>j8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!Y0($)||!Y0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(Y0(X)&&Y0(Y[A]))Y[A]=zW(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((Q)=>Y0(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(Y0(U)&&"path"in U){if(!J.find((Q)=>Y0(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>j8(W,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(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!j8(w[Y],$[Y]))return!1;return!0}if(Y0(w)&&Y0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!j8(w[X],$[X]))return!1}return!0}return!1}function Y0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function _f(w,$){if(!e2(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return zW($,A)}catch{return null}}catch{return null}}async function Sf({name:w="",cwd:$,defaultConfig:Y}){let A=$||eQ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let W of X){let Q=B8(A,`${U}${W}`),B=await _f(Q,Y);if(B!==null)return B}try{let U=B8(A,"package.json");if(e2(U)){let Q=(await import(U))[w];if(Q&&typeof Q==="object"&&!Array.isArray(Q))try{return zW(Y,Q)}catch{}}}catch{}return Y}function Zf(w,$={}){let Y=W8.cwd();while(Y.includes("storage"))Y=E2(Y,"..");let A=E2(Y,w||"");if($?.relative)return Jf(W8.cwd(),A);return A}async function kf(){try{let w=await Sf({name:"clarity",defaultConfig:A8,cwd:W8.cwd(),endpoint:"",headers:{}});return{...A8,...w}}catch{return A8}}function B0(){if(A$.env.NODE_ENV==="test"||A$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function hf(){if(A$.env.NODE_ENV==="test"||A$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof A$<"u"){let w=A$.type;if(w==="renderer"||w==="worker")return!1;return!!(A$.versions&&(A$.versions.node||A$.versions.bun))}return!1}class wG{async format(w){let $=await hf(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:x1.pid,hostname:$(),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 z8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...$W},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new wG,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??h0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...X8,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...X8};return{...X8,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:$W.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await jf(this.config.logDirectory,R2.F_OK|R2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await zf(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:M$.from(w);try{if(!bQ(this.currentLogFile))await uQ(this.currentLogFile,"",{mode:420});if(X=H2(this.currentLogFile,"a",420),Bf(X,Q,{flag:"a"}),T2(X),X!==void 0)PQ(X),X=void 0;if((await h1(this.currentLogFile)).size===0){if(await uQ(this.currentLogFile,Q,{flag:"w",mode:420}),(await h1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;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(X!==void 0)try{PQ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();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 D1(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 D1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return D1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(B0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return xQ(16).toString("hex")}generateKey(){return xQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=xQ(16),A=Uf("aes-256-gcm",$,Y),X=M$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:M$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=I2(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(M$.from(M$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(B0())return;let w=await h1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await lX(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await h1(Y).catch(()=>null))try{if(await M2(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await nX(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await uQ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await h1(Y).catch(()=>null))await M2(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await lX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await nX(D1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=f2(w),A=Wf($),X=I2();await Gf(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),bQ(this.currentLogFile))try{let w=H2(this.currentLogFile,"r+");T2(w),PQ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!B0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await lX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await nX(D1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?o.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=h0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${o.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!B0()){let B=jG[w],j=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",z;switch(w){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:o.gray(U),level:w}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:o.green(U),level:w}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:w}),console.error(z),W){let G=W.split(`
135
- `);for(let K of G)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:o.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!B0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let Q=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
136
- `;if(W)Q+=`${W}
137
- `;Q=Q.replace(this.ANSI_PATTERN,""),await this.writeToFile(Q)}time(w){let $=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(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
138
- `,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!B0()){let j=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:o.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!B0())console.error(B.trim());await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new z8($,{...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(!bQ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return f2(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=M$.isBuffer(w)?w:M$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),W=Qf("aes-256-gcm",Y,X);return W.setAuthTag(J),M$.concat([W.update(U),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return B0()}isServerMode(){return!B0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!B0()){let J=w.split(`
139
- `),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,Q=`└${"─".repeat(U)}┘`,B=J.map((j)=>{let z=" ".repeat(U-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:o.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:o.cyan(Q),showTimestamp:!1}))}else if(!B0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
140
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(B0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${o.cyan("?")} ${w} (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(""),$(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(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,W=0;if(Y=w.replace(U,(Q,B)=>{if(B==="%")return"%";if(W>=$.length)return Q;let j=$[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return Q}}),W<$.length)Y+=` ${$.slice(W).map((Q)=>typeof Q==="object"?JSON.stringify(Q,null,2):String(Q)).join(" ")}`}if(this.fancy&&!B0()){let U=this.options.showTags!==!1&&this.name?o.gray(this.formatTag(this.name)):"",W=o.blue("◐");console.error(`${W} ${U} ${o.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
141
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||B0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),W!==void 0)this.activeProgressBar.message=W;let Q=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,Q)},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,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||B0())return;h0.stdout.write(`${"\r".padEnd(h0.stdout.columns||80)}\r`),this.log(W,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(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=o.green("━".repeat(A)),U=o.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=$||Y===100?o.green("✓"):o.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${o.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=h0.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,h0.stdout.write(w.lastRenderedLine),$)h0.stdout.write(`
142
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||B0()||!h0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(B0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await lX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=D1(this.config.logDirectory,A);if(w.before)try{if((await h1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await nX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function Y8(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&r($[0])&&"id"in $[0]&&$[0].id===3&&r($[1])&&"id"in $[1]&&$[1].id===4)return $;if(r($)&&r(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(r(w)&&"arr"in w&&Array.isArray(w.arr)&&r($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&r($[0])&&r(w[0])){let A=[...$];for(let X of w)if(r(X)&&"name"in X){if(!A.find((U)=>r(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(r(X)&&"path"in X){if(!A.find((U)=>r(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>G8(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!r($)||!r(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(r(X)&&r(Y[A]))Y[A]=Y8(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((Q)=>r(Q)&&("name"in Q)&&Q.name===U.name))J.push(U)}else if(r(U)&&"path"in U){if(!J.find((Q)=>r(Q)&&("path"in Q)&&Q.path===U.path))J.push(U)}else if(!J.some((W)=>G8(W,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 GW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:Y8(w,$);if(Array.isArray(w))return Y==="replace"?$:Y8(w,$);if(!r($)||!r(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=Y8(U,J);else if(r(J)&&r(U))A[X]=GW(U,J,Y);else A[X]=J}return A}function G8(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!G8(w[Y],$[Y]))return!1;return!0}if(r(w)&&r($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!G8(w[X],$[X]))return!1}return!0}return!1}function r(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function oX(w,$,Y="replace"){if(!o2(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return GW($,X,Y)}catch{return null}}catch{return null}}function Df(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=(q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase(),K=`${A}_${z.map(G).join("_")}`,E=`${A}_${z.map((q)=>q.toUpperCase()).join("_")}`;if(Y)x0.info(`Checking environment variable ${K} for config ${w}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))Q[B]=J(j,z);else{let q=SY.env[K]||SY.env[E];if(q!==void 0){if(Y)x0.info(`Using environment variable ${q?K:E} for config ${w}.${z.join(".")}`);if(typeof j==="number")Q[B]=Number(q);else if(typeof j==="boolean")Q[B]=q.toLowerCase()==="true";else if(Array.isArray(j))try{let N=JSON.parse(q);if(Array.isArray(N))Q[B]=N;else Q[B]=q.split(",").map((f)=>f.trim())}catch{Q[B]=q.split(",").map((N)=>N.trim())}else Q[B]=q}}}return Q}return J(X)}async function xf({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let Q=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?Df(w,X,J):X,B=Y||SY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)x0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${B}`);let z=[w,`.${w}`].filter(Boolean),G=[`${w}.config`,`.${w}.config`].filter(Boolean),K=$?[$,`.${$}`]:[],E=$?[`${$}.config`,`.${$}.config`]:[],q=Array.from(new Set([B,n0(B,"config"),n0(B,".config"),A?n0(B,A):void 0].filter(Boolean)));for(let N of q){if(J)x0.info(`Searching for configuration in: ${N}`);let R=[n0(B,"config"),n0(B,".config")].concat(A?[n0(B,A)]:[]).includes(N)?[...z,...G,...K,...E]:[...G,...z,...E,...K];for(let O of R)for(let y of j){let T=n0(N,`${O}${y}`),M=await oX(T,Q,W);if(M!==null){if(J)x0.success(`Configuration loaded from: ${T}`);return M}}}if(w){let N=n0(DQ(),".config",w),f=["config",`${w}.config`];if($)f.push(`${$}.config`);if(J)x0.info(`Checking user config directory: ${N}`);for(let R of f)for(let O of j){let y=n0(N,`${R}${O}`),T=await oX(y,Q,W);if(T!==null){if(J)x0.success(`Configuration loaded from user config directory: ${y}`);return T}}}if(w){let N=n0(DQ(),".config"),f=[`.${w}.config`];if($)f.push(`.${$}.config`);if(J)x0.info(`Checking user config directory for dotfile configs: ${N}`);for(let R of f)for(let O of j){let y=n0(N,`${R}${O}`),T=await oX(y,Q,W);if(T!==null){if(J)x0.success(`Configuration loaded from user config directory dotfile: ${y}`);return T}}}if(w){let N=DQ(),f=[`.${w}.config`,`.${w}`];if($)f.push(`.${$}.config`),f.push(`.${$}`);if(J)x0.info(`Checking user home directory for dotfile configs: ${N}`);for(let R of f)for(let O of j){let y=n0(N,`${R}${O}`),T=await oX(y,Q,W);if(T!==null){if(J)x0.success(`Configuration loaded from user home directory: ${y}`);return T}}}try{let N=n0(B,"package.json");if(o2(N)){let f=await import(N),R=f[w];if(!R&&$){if(R=f[$],R&&J)x0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)x0.success(`Configuration loaded from package.json: ${R===f[w]?w:$}`);return GW(Q,R,W)}catch(O){if(J)x0.warn("Failed to merge package.json config:",O)}}}catch(N){if(J)x0.warn("Failed to load package.json:",N)}if(J)x0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return Q}function Pf(w,$={}){let Y=Q8.cwd();while(Y.includes("storage"))Y=N2(Y,"..");let A=N2(Y,w||"");if($?.relative)return Af(Q8.cwd(),A);return A}async function bf(){try{let w=await xf({name:"clarity",alias:"logging",defaultConfig:J8,cwd:Q8.cwd()});return{...J8,...w||{}}}catch{return J8}}function H0(){if(X$.env.NODE_ENV==="test"||X$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function uf(){if(X$.env.NODE_ENV==="test"||X$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof X$<"u"){let w=X$.type;if(w==="renderer"||w==="worker")return!1;return!!(X$.versions&&(X$.versions.node||X$.versions.bun))}return!1}class $G{async format(w){let $=await uf(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:u1.pid,hostname:$(),environment:u1.env.NODE_ENV||"development",platform:u1.platform,version:u1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:u1.env.NODE_ENV||u1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class K8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...YW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new $G,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...U8,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...U8};return{...U8,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:YW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await Ef(this.config.logDirectory,O2.F_OK|O2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await ff(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:$$.from(w);try{if(!pX(this.currentLogFile))await iQ(this.currentLogFile,"",{mode:420});if(X=y2(this.currentLogFile,"a",420),Nf(X,Q,{flag:"a"}),C2(X),X!==void 0)vQ(X),X=void 0;if((await P1(this.currentLogFile)).size===0){if(await iQ(this.currentLogFile,Q,{flag:"w",mode:420}),(await P1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;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(X!==void 0)try{vQ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();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 b1(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 b1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return b1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return cQ(16).toString("hex")}generateKey(){return cQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=cQ(16),A=Kf("aes-256-gcm",$,Y),X=$$.isBuffer(w)?w:$$.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=$$.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=_2(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$($$.from($$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let w=await P1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await rX(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await P1(Y).catch(()=>null))try{if(await L2(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await tX(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await iQ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await P1(Y).catch(()=>null))await L2(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await rX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await tX(b1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=V2(w),A=qf($),X=_2();await Rf(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),pX(this.currentLogFile))try{let w=y2(this.currentLogFile,"r+");C2(w),vQ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await rX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await tX(b1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?v.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let w=typeof x.env.NO_COLOR<"u",$=x.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=x.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${v.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),$}supportsHyperlinks(){if(H0())return!1;let w=x.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=x.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(Tf($)||$.startsWith("./")||$.startsWith("../"))$=Hf($);else return null;return pX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":zG[w],G=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:v.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:v.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
143
- `);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:v.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog(w))return;let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
144
- `;if(W)j+=`${W}
145
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(W,Q)=>{},finish:(W)=>{},interrupt:(W,Q)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Q="info")=>{if(!H0()&&x.stdout.isTTY)x.stdout.write(`
146
- `);if(this[Q==="warning"?"warn":Q](W),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":v.blue("◐"),tag:Y,message:`${v.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
147
- `,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":v.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!H0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new K8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(H0())throw Error("createReadStream is not supported in browser environments");if(!pX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return V2(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=$$.isBuffer(w)?w:$$.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=Ff("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=$$.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return H0()}isServerMode(){return!H0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
148
- `),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:v.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(j),showTimestamp:!1}))}else if(!H0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
149
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(H0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${v.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();x.stdin.removeListener("data",Y);try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!1)}catch{}x.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!0)}catch{}x.stdin.resume(),x.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let Q=/%([sdijfo%])/g,B=0;if(Y=w.replace(Q,(j,z)=>{if(z==="%")return"%";if(B>=$.length)return j;let G=$[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<$.length)Y+=` ${$.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${v.blue("◐")} `;console.error(`${B}${Q} ${v.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
150
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!x.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=v.green("━".repeat(A)),U=v.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?v.green("✓"):v.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=x.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,x.stdout.write(w.lastRenderedLine),$)x.stdout.write(`
151
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||H0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await rX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=b1(this.config.logDirectory,A);if(w.before)try{if((await P1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await tX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function YG(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await w()}catch(Q){if(U=Q instanceof Error?Q:Error(String(Q)),W===Y||!X(U))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function AG(w){return w instanceof Yw}function cf(w){return w instanceof F8}function vf(w){if(AG(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class f8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:Q=!0}=Y,B=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix(w),z={...$};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:w}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(Q)return hY.track("applyEnvironmentVariables",B,{configName:w});return B()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=U.map((j)=>this.formatEnvKey(j,A.useCamelCase)),Q=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let j=aX.env[Q]||(B?aX.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=aX.env[Q]?Q:B}try{w[X]=this.parseEnvironmentValue(j,typeof J,Q,A.customParsers,A.configName)}catch(z){if(z instanceof q8)throw z;throw I$.envVar(Q,j,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw I$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(aX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],W=`${Y}_${U.map((Q)=>this.formatEnvKey(Q,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,Y,A);else A.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
129
+ `}function WW(){let w=I1.randomBytes(20);return w[0]=w[0]&127||1,w}function v9(w=2048){let{privateKey:$,publicKey:Y}=I1.generateKeyPairSync("rsa",{modulusLength:w});return{privateKey:$,publicKey:Y}}function W7(w){let $=w.export({type:"spki",format:"der"});return I1.createHash("sha1").update($).digest()}function c9(w){let $={serialNumber:w.serialNumber||WW(),notBefore:w.notBefore,notAfter:w.notAfter,subject:w.subject,issuer:w.issuer||w.subject,publicKey:w.publicKey,extensions:{basicConstraints:{isCA:w.isCA??!1,critical:!0,pathLenConstraint:w.pathLenConstraint},subjectKeyIdentifier:W7(w.publicKey)}};if(w.keyUsage)$.extensions.keyUsage={...w.keyUsage,critical:!0};if(w.extendedKeyUsage)$.extensions.extendedKeyUsage=w.extendedKeyUsage;if(w.subjectAltName?.length)$.extensions.subjectAltName=w.subjectAltName;let Y=X7($),A=J7(Y,w.signingKey);return{certificate:U7(A,"CERTIFICATE"),certificateDer:A}}function m9(w){return w.export({type:"pkcs8",format:"pem"})}function Q7(w){return I1.createPrivateKey(w)}function j7(w){let $=new I1.X509Certificate(w),Y=$.publicKey,A=[],X=$.subject.split(`
130
+ `);for(let J of X){let[U,...Q]=J.split("="),W=Q.join("=");if(U&&W)A.push({shortName:U.trim(),value:W.trim()})}return{publicKey:Y,subject:A}}async function QW(w={}){S("ca","Creating new Root CA Certificate",w.verbose);let $=w.keySize||Nw.DEFAULT_KEY_SIZE;S("ca",`Generating ${$}-bit RSA key pair`,w.verbose);let{privateKey:Y,publicKey:A}=v9($),X=[{shortName:"C",value:w.countryName||B0.countryName},{shortName:"ST",value:w.stateName||B0.stateName},{shortName:"L",value:w.localityName||B0.localityName},{shortName:"O",value:w.organization||"Local Development CA"},{shortName:"OU",value:w.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:w.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=UW({validityYears:w.validityYears||Nw.DEFAULT_CA_VALIDITY_YEARS,verbose:w.verbose}),{certificate:Q}=c9({serialNumber:WW(),notBefore:J,notAfter:U,subject:X,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:Q,privateKey:m9(Y),notBefore:J,notAfter:U}}async function jW(w){if(S("ca","Generating new certificate",w.verbose),S("ca",`Options: ${LX(w)}`,w.verbose),!w.domain&&!w.domains?.length)throw Error("Either domain or domains must be specified");if(!w.rootCA?.certificate||!w.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:$}=j7(w.rootCA.certificate),Y=Q7(w.rootCA.privateKey);S("ca",`Generating ${Nw.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,w.verbose);let A=Nw.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=v9(A),U=w.commonName||x9(w),Q=w.certificateAttributes||[{shortName:"C",value:w.countryName||B0.countryName},{shortName:"ST",value:w.stateName||B0.stateName},{shortName:"L",value:w.localityName||B0.localityName},{shortName:"O",value:w.organizationName||B0.organizationName},{shortName:"CN",value:U}],{notBefore:W,notAfter:j}=UW({validityDays:w.validityDays||Nw.DEFAULT_VALIDITY_DAYS,verbose:w.verbose}),B=P9(w),f=w.keyUsage||{digitalSignature:!0,keyEncipherment:!0},z=w.extKeyUsage||{serverAuth:!0},{certificate:G}=c9({serialNumber:WW(),notBefore:W,notAfter:j,subject:Q,issuer:$,publicKey:J,signingKey:Y,isCA:w.basicConstraints?.cA??!1,pathLenConstraint:w.basicConstraints?.pathLenConstraint,keyUsage:f,extendedKeyUsage:z,subjectAltName:B});return{certificate:G,privateKey:m9(X),notBefore:W,notAfter:j}}function g9(w,$){S(O.STORAGE,`Storing certificate and private key with options: ${LX($)}`,$?.verbose);let{certPath:Y,keyPath:A}=JW({basePath:$?.basePath,certPath:$?.certPath,keyPath:$?.keyPath});S(O.STORAGE,`Certificate path: ${Y}`,$?.verbose),S(O.STORAGE,`Private key path: ${A}`,$?.verbose);let X=pU.dirname(Y);if(!tw.existsSync(X))S(O.STORAGE,`Creating certificate directory: ${X}`,$?.verbose),tw.mkdirSync(X,{recursive:!0});S(O.STORAGE,"Writing certificate file",$?.verbose),tw.writeFileSync(Y,w.certificate);let J=pU.dirname(A);if(!tw.existsSync(J))S(O.STORAGE,`Creating private key directory: ${J}`,$?.verbose),tw.mkdirSync(J,{recursive:!0});return S(O.STORAGE,"Writing private key file",$?.verbose),tw.writeFileSync(A,w.privateKey),S(O.STORAGE,"Certificate and private key stored successfully",$?.verbose),Y}function d9(w,$){S(O.STORAGE,"Storing CA certificate",$?.verbose);let{caCertPath:Y}=JW({basePath:$?.basePath,caCertPath:$?.caCertPath});S(O.STORAGE,`CA certificate path: ${Y}`,$?.verbose);let A=pU.dirname(Y);if(!tw.existsSync(A))S(O.STORAGE,`Creating CA certificate directory: ${A}`,$?.verbose),tw.mkdirSync(A,{recursive:!0});return S(O.STORAGE,"Writing CA certificate file",$?.verbose),tw.writeFileSync(Y,w),S(O.STORAGE,"CA certificate stored successfully",$?.verbose),Y}function SX(w){let $;if(w.startsWith("-----BEGIN CERTIFICATE-----"))$=w;else $=k9(w);return new B7.X509Certificate($)}function OX(w){return SX(w).fingerprint256.replace(/:/g,"").toUpperCase()}function BW(w){return n9(SX(w).subject)}function f7(w){let $=[],Y=w.split(`
131
+ `);for(let A of Y){let[X,...J]=A.split("="),U=J.join("=");if(X&&U)$.push({shortName:X.trim(),value:U.trim()})}return $}function n9(w){return f7(w).find(($)=>$.shortName==="CN")?.value||""}function z7(w){let $=[],Y=n9(w.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))$.push(Y);let A=w.subjectAltName;if(A){let X=A.split(", ");for(let J of X)if(J.startsWith("DNS:"))$.push(J.slice(4))}return[...new Set($)]}function fW(w,$){let Y=SX(w),A=z7(Y);for(let X of A){if(X===$)return!0;if(X.startsWith("*.")){let J=X.slice(2);if($.endsWith(J)&&$.indexOf(".")===$.lastIndexOf("."))return!0}}return!1}async function E7(w,$){if(RX.platform()!=="darwin")return!1;try{let Y=OX(w);if(!Y)return S(O.TRUST,"Could not extract certificate fingerprint",$),!1;try{if(G7("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
132
+ `).some((A)=>{let X=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!X&&X[1].toUpperCase()===Y}))return S(O.TRUST,"Certificate fingerprint found in system keychain",$),!0}catch{}return S(O.TRUST,"Certificate fingerprint not found in system keychain",$),!1}catch(Y){return S(O.TRUST,`Error checking certificate trust: ${Y}`,$),!1}}async function zW(w,$,Y){S(O.TRUST,`Adding certificate to system trust store with options: ${LX(Y)}`,Y?.verbose),S(O.TRUST,"Storing certificate and private key",Y?.verbose);let A=g9(w,Y);S(O.TRUST,"Storing CA certificate",Y?.verbose);let X=d9($,Y),J=RX.platform();S(O.TRUST,`Detected platform: ${J}`,Y?.verbose);let U=q7[J];if(!U){let Q=`Unsupported platform: ${J}`;throw S(O.TRUST,`Error: ${Q}`,Y?.verbose),Error(Q)}return await U.addCertificate(X,Y),S(O.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var FK,kf=30000,MX,uf="https://acme-staging-v02.api.letsencrypt.org/directory",vf="https://acme-v02.api.letsencrypt.org/directory",XX,MK="1.2.840.10045.2.1",yK="1.2.840.10045.3.1.7",IK="1.2.840.10045.4.3.2",CK="2.5.4.3",VK="1.2.840.113549.1.9.14",LK="2.5.29.17",BX,tU,qF,NF=(w)=>w,RF=(w,$)=>{for(var Y in $)qF(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:HF.bind($,Y)})},MF=(w,$)=>()=>(w&&($=w(w=0)),$),ef,Q9,M1,BY,j9,tF,aF,Tf,wX,xU,_0,o,sF,qf,oF,Nf,eF,wT,yU,$T,Hf,Rf,IU,YT,AT,XT,JT,$X,B9,UT,D0,WT,QT,Mf,YX,PU,q0,u,jT,yf,BT,If,fT,zT,CU,GT,Cf,Vf,ET,VU,KT,FT,TT,qT,NT,AX,f9,HT,RT="0.15.6",s0,KX,WY,iU,bU,FX,uU,vU,QY,cU,mU,G$,z9,G9,qw,aw,E9,K9,MT,IT,F9,TX,wC,I0,m,$C,VT,YC,LT,AC,XC,Lf,JC,ST,OT,UC,Sf,WC,QC,jC,BC,fC,LU,hT,zC,Rw,q9,qX,N9,H9,AW,R9,M9,NX,y9,I9,y1,iT,nw,GC,EC,KC,_9,B0,Nw,O,R1,mT,Of="[redacted]",gT,dT,Hw,d0,K7,F7,T7,q7;var l9=a(()=>{FK=KK(import.meta.url);MX=new JY;XX=class XX extends Error{problem;httpStatus;constructor(w,$,Y){super(w);this.name="AcmeError",this.problem=$,this.httpStatus=Y}};BX=new sf,tU=new of,qF=Object.defineProperty;ef={};RF(ef,{withErrorRecovery:()=>Y9,tryLoadConfig:()=>nF,loadConfigWithResult:()=>gF,loadConfig:()=>W9,isRetryableError:()=>iF,isConfigNotFoundError:()=>PF,isBunfigError:()=>A9,globalPerformanceMonitor:()=>BY,globalCache:()=>M1,getEnvOrDefault:()=>bF,generateConfigTypes:()=>lF,defaultGeneratedDir:()=>K9,defaultConfigDir:()=>E9,deepMergeWithArrayStrategy:()=>wW,deepMerge:()=>X9,createLibraryConfig:()=>pF,config:()=>dF,bunfigPlugin:()=>rF,applyEnvVarsToConfig:()=>AY,TypeGenerationError:()=>vU,SchemaValidationError:()=>QY,PluginError:()=>mU,PerformanceMonitor:()=>sU,FileSystemError:()=>uU,ErrorFactory:()=>G$,EnvVarError:()=>FX,EnvProcessor:()=>IX,ConfigValidator:()=>$W,ConfigValidationError:()=>iU,ConfigNotFoundError:()=>KX,ConfigMergeError:()=>bU,ConfigLoader:()=>YW,ConfigLoadError:()=>WY,ConfigFileLoader:()=>CX,ConfigCache:()=>aU,CacheUtils:()=>j9,BunfigError:()=>s0,BrowserConfigError:()=>cU,ArrayMergeStrategies:()=>z9});MT=MF(async()=>{Q9=import.meta.require,M1=new aU,BY=new sU,j9={createKey:yF,isEquivalent:IF,estimateMemoryUsage:CF},tF=QX(kU.cwd(),"config"),aF=QX(kU.cwd(),"src/generated"),Tf=WX.env.CLARITY_LOG_DIR||bK(SF(),"logs"),wX={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},xU=await OF(),_0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},o=_0,sF=_0.red,qf=_0.green,oF=_0.yellow,Nf=_0.blue,eF=_0.magenta,wT=_0.cyan,yU=_0.white,$T=_0.gray,Hf=_0.bgRed,Rf=_0.bgYellow,IU=_0.bold,YT=_0.dim,AT=_0.italic,XT=_0.underline,JT=_0.reset,$X={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},B9={debug:"\uD83D\uDD0D",info:Nf("ℹ"),success:qf("✓"),warning:Rf(yU(IU(" WARN "))),error:Hf(yU(IU(" ERROR ")))},UT=new zX("stacks"),D0=new zX("bunfig",{showTags:!0}),WT=m0(UY.cwd(),"config"),QT=m0(UY.cwd(),"src/generated"),Mf=UX.env.CLARITY_LOG_DIR||PK(kF(),"logs"),YX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Mf,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},PU=await ZF(),q0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},u=q0,jT=q0.red,yf=q0.green,BT=q0.yellow,If=q0.blue,fT=q0.magenta,zT=q0.cyan,CU=q0.white,GT=q0.gray,Cf=q0.bgRed,Vf=q0.bgYellow,ET=q0.bgGray,VU=q0.bold,KT=q0.dim,FT=q0.italic,TT=q0.underline,qT=q0.strikethrough,NT=q0.reset,AX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},f9={debug:"\uD83D\uDD0D",info:If("ℹ"),success:yf("✓"),warning:Vf(CU(VU(" WARN "))),error:Cf(CU(VU(" ERROR ")))},HT=new EX("stacks"),s0=class extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},KX=class extends s0{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${A} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}},WY=class extends s0{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}},iU=class extends s0{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},bU=class extends s0{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},FX=class extends s0{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}},uU=class extends s0{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},vU=class extends s0{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},QY=class extends s0{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}},cU=class extends s0{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}},mU=class extends s0{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},G$={configNotFound(w,$,Y){return new KX(w,$,Y)},configLoad(w,$,Y){return new WY(w,$,Y)},configValidation(w,$,Y){return new iU(w,$,Y)},configMerge(w,$,Y,A){return new bU(w,$,Y,A)},envVar(w,$,Y,A){return new FX(w,$,Y,A)},fileSystem(w,$,Y){return new uU(w,$,Y)},typeGeneration(w,$,Y){return new vU(w,$,Y)},schemaValidation(w,$,Y){return new QY(w,$,Y)},browserConfig(w,$,Y,A){return new cU(w,$,Y,A)},plugin(w,$,Y){return new mU(w,$,Y)}},z9={replace:"replace",concat:"concat",smart:"smart"},G9=/^https?:\/\//,qw=new EX("bunfig",{showTags:!0}),aw=new YW,E9=g0(x$.cwd(),"config"),K9=g0(x$.cwd(),"src/generated")});IT=jX.env.CLARITY_LOG_DIR||UF(yT(),"logs"),F9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:IT,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},TX={...F9},wC=(async()=>{try{let{loadConfig:w}=await MT().then(()=>ef),$=await w({name:"clarity",alias:"logging",defaultConfig:F9,cwd:jX.cwd()});if($)Object.assign(TX,$)}catch{}return TX})();I0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},m=I0,$C=I0.red,VT=I0.green,YC=I0.yellow,LT=I0.blue,AC=I0.magenta,XC=I0.cyan,Lf=I0.white,JC=I0.gray,ST=I0.bgRed,OT=I0.bgYellow,UC=I0.bgGray,Sf=I0.bold,WC=I0.dim,QC=I0.italic,jC=I0.underline,BC=I0.strikethrough,fC=I0.reset,LU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},hT={debug:"\uD83D\uDD0D",info:LT("ℹ"),success:VT("✓"),warning:OT(Lf(Sf(" WARN "))),error:ST(Lf(Sf(" ERROR ")))};zC=new VX("stacks");Rw=class Rw extends Error{timestamp;context;constructor(w,$={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=$,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([$,Y])=>`${$}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}};q9=class q9 extends Rw{code="CONFIG_NOT_FOUND";constructor(w,$,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],X="";if(A.length===1)X=` or alias "${A[0]}"`;else if(A.length>1)X=` or aliases ${A.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:$,searchPathCount:$.length})}};qX=class qX extends Rw{code="CONFIG_LOAD_ERROR";constructor(w,$,Y){super(`Failed to load configuration from "${w}": ${$.message}`,{configPath:w,configName:Y,originalError:$.name,originalMessage:$.message});this.cause=$}};N9=class N9 extends Rw{code="CONFIG_VALIDATION_ERROR";constructor(w,$,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};H9=class H9 extends Rw{code="CONFIG_MERGE_ERROR";constructor(w,$,Y,A){super(`Failed to merge configuration from "${w}" with "${$}": ${Y.message}`,{sourcePath:w,targetPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};AW=class AW extends Rw{code="ENV_VAR_ERROR";constructor(w,$,Y,A){super(`Failed to parse environment variable "${w}" with value "${$}" as ${Y}`,{envKey:w,envValue:$,expectedType:Y,configName:A})}};R9=class R9 extends Rw{code="FILE_SYSTEM_ERROR";constructor(w,$,Y){super(`File system ${w} failed for "${$}": ${Y.message}`,{operation:w,path:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};M9=class M9 extends Rw{code="TYPE_GENERATION_ERROR";constructor(w,$,Y){super(`Failed to generate types from "${w}" to "${$}": ${Y.message}`,{configDir:w,outputPath:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};NX=class NX extends Rw{code="SCHEMA_VALIDATION_ERROR";constructor(w,$,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:$,errorCount:$.length})}};y9=class y9 extends Rw{code="BROWSER_CONFIG_ERROR";constructor(w,$,Y,A){super(`Failed to fetch configuration from "${w}": ${$} ${Y}`,{endpoint:w,status:$,statusText:Y,configName:A})}};I9=class I9 extends Rw{code="PLUGIN_ERROR";constructor(w,$,Y){super(`Plugin "${w}" failed during ${$}: ${Y.message}`,{pluginName:w,operation:$,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};y1={configNotFound(w,$,Y){return new q9(w,$,Y)},configLoad(w,$,Y){return new qX(w,$,Y)},configValidation(w,$,Y){return new N9(w,$,Y)},configMerge(w,$,Y,A){return new H9(w,$,Y,A)},envVar(w,$,Y,A){return new AW(w,$,Y,A)},fileSystem(w,$,Y){return new R9(w,$,Y)},typeGeneration(w,$,Y){return new M9(w,$,Y)},schemaValidation(w,$,Y){return new NX(w,$,Y)},browserConfig(w,$,Y,A){return new y9(w,$,Y,A)},plugin(w,$,Y){return new I9(w,$,Y)}};iT=/^https?:\/\//;nw=new VX("bunfig",{showTags:!0});GC=new h9;EC=Ww(yX.cwd(),"config"),KC=Ww(yX.cwd(),"src/generated"),_9={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(WU.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:QU.join(WU.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:QU.join(WU.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},B0=_9,Nw={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"},O={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},R1={info:(...w)=>console.log(...w),warn:(...w)=>console.warn(...w),success:(...w)=>console.log(...w),error:(...w)=>console.error(...w),debug:(...w)=>console.debug(...w)};mT=cT(uT);gT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),dT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;Hw={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},d0={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};K7={platform:"darwin",async addCertificate(w,$){if(await E7(w,$?.verbose)){S(O.TRUST,"Certificate is already trusted, skipping trust store update",$?.verbose),R1.success("Certificate is already trusted in system keychain");return}S(O.TRUST,"Adding certificate to macOS keychain",$?.verbose),await z$(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${w}`)},async removeCertificate(w,$,Y){let A=Y||B0.commonName;S(O.TRUST,`Removing certificate ${A} from macOS keychain`,$?.verbose);try{await z$(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),S(O.TRUST,`Removed certificate ${A} from macOS keychain`,$?.verbose)}catch(X){throw S(O.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},F7={platform:"win32",async addCertificate(w,$){S(O.TRUST,"Adding certificate to Windows certificate store",$?.verbose),await z$(`certutil -f -v -addstore -enterprise Root ${w}`)},async removeCertificate(w,$,Y){let A=Y||B0.commonName;S(O.TRUST,`Removing certificate ${A} from Windows certificate store`,$?.verbose);try{await z$(`certutil -delstore -enterprise Root "${A}"`),S(O.TRUST,`Removed certificate ${A} from Windows certificate store`,$?.verbose)}catch(X){throw S(O.TRUST,`Error removing certificate: ${X}`,$?.verbose),X}}},T7={platform:"linux",async addCertificate(w,$){S(O.TRUST,"Adding certificate to Linux certificate store",$?.verbose);let Y=RX.homedir(),A=Nw.LINUX_CERT_DB_FILENAME,X=Nw.LINUX_TRUST_ARGS;S(O.TRUST,`Searching for certificate databases in ${Y}`,$?.verbose);let J=nU(Y,A);if(J.length===0){R1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){S(O.TRUST,`Processing certificate database in ${U}`,$?.verbose);try{S(O.TRUST,`Attempting to delete existing cert for ${B0.commonName}`,$?.verbose),await z$(`certutil -d sql:${U} -D -n ${B0.commonName}`)}catch(Q){S(O.TRUST,`Warning: Error deleting existing cert: ${Q}`,$?.verbose),console.warn(`Error deleting existing cert: ${Q}`)}S(O.TRUST,`Adding new certificate to ${U}`,$?.verbose),await z$(`certutil -d sql:${U} -A -t ${X} -n ${B0.commonName} -i ${w}`),R1.info(`Cert added to ${U}`)}},async removeCertificate(w,$,Y){let A=Y||B0.commonName;S(O.TRUST,`Removing certificate ${A} from Linux certificate store`,$?.verbose);let X=RX.homedir(),J=Nw.LINUX_CERT_DB_FILENAME;S(O.TRUST,`Searching for certificate databases in ${X}`,$?.verbose);let U=nU(X,J);if(U.length===0){R1.warn("No certificate databases found. Cannot remove certificate.");return}for(let Q of U){S(O.TRUST,`Processing certificate database in ${Q}`,$?.verbose);try{await z$(`certutil -d sql:${Q} -D -n "${A}"`),R1.info(`Cert removed from ${Q}`)}catch(W){S(O.TRUST,`Error removing cert from ${Q}: ${W}`,$?.verbose),console.warn(`Error removing cert from ${Q}: ${W}`)}}}},q7={darwin:K7,win32:F7,linux:T7}});var hX=a(()=>{l9()});function P$(w){try{return OX(w)}catch{return null}}function GW(w){try{return BW(w)||null}catch{return null}}function EW(w,$){try{return $.every((Y)=>fW(w,Y))}catch{return!1}}var _X=a(()=>{hX()});import{existsSync as p9,statSync as r9}from"fs";import{existsSync as kW,mkdirSync as C7,readdirSync as V7,writeFileSync as L7}from"fs";import{homedir as C1}from"os";import{dirname as t9,resolve as l0}from"path";import i$ from"process";import{join as S7,relative as O7,resolve as a9}from"path";import rX from"process";import{existsSync as Dz,mkdirSync as NV,readdirSync as HV,writeFileSync as RV}from"fs";import{homedir as KW}from"os";import{dirname as IV,resolve as n0}from"path";import zY from"process";import{join as h7,relative as _7,resolve as s9}from"path";import tX from"process";import{existsSync as kz,mkdirSync as OV,readdirSync as hV,writeFileSync as _V}from"fs";import{dirname as kV,resolve as aX}from"path";import ZW from"process";import{Buffer as K$}from"buffer";import{createCipheriv as D7,createDecipheriv as k7,randomBytes as FW}from"crypto";import{closeSync as TW,createReadStream as o9,createWriteStream as Z7,existsSync as qW,fsyncSync as e9,openSync as wz,writeFileSync as x7}from"fs";import{access as P7,constants as $z,mkdir as i7,readdir as DX,rename as Yz,stat as V1,unlink as kX,writeFile as NW}from"fs/promises";import{join as L1}from"path";import k0 from"process";import{pipeline as b7}from"stream/promises";import{createGzip as Az}from"zlib";import S1 from"process";import ew from"process";import{Buffer as sw}from"buffer";import{createCipheriv as u7,createDecipheriv as v7,randomBytes as HW}from"crypto";import{closeSync as RW,createReadStream as Xz,createWriteStream as c7,existsSync as ZX,fsyncSync as Jz,openSync as Uz,writeFileSync as m7}from"fs";import{access as g7,constants as Wz,mkdir as d7,readdir as xX,rename as Qz,stat as O1,unlink as PX,writeFile as MW}from"fs/promises";import{isAbsolute as n7,join as h1,resolve as l7}from"path";import x from"process";import{pipeline as p7}from"stream/promises";import{createGzip as jz}from"zlib";import _1 from"process";import w$ from"process";import iX from"process";import{existsSync as bX}from"fs";import{resolve as yW}from"path";import{existsSync as r7}from"fs";import{existsSync as t7,readdirSync as a7}from"fs";import{extname as IW,resolve as Bz}from"path";import s7 from"process";import{join as oq,relative as eq,resolve as Mz}from"path";import A8 from"process";import{Buffer as ow}from"buffer";import{createCipheriv as YN,createDecipheriv as AN,randomBytes as OW}from"crypto";import{closeSync as hW,createReadStream as yz,createWriteStream as XN,existsSync as vX,fsyncSync as Iz,openSync as Cz,writeFileSync as JN}from"fs";import{access as UN,constants as Vz,mkdir as WN,readdir as cX,rename as Lz,stat as D1,unlink as mX,writeFile as _W}from"fs/promises";import{isAbsolute as QN,join as k1,resolve as jN}from"path";import P from"process";import{pipeline as BN}from"stream/promises";import{createGzip as Sz}from"zlib";import Z1 from"process";import $$ from"process";function M7(w,$){this[w]=R7.bind(null,$)}class dW{cache=new Map;totalHits=0;totalMisses=0;options;constructor(w={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...w}}generateKey(w,$){let Y=$?`:${$}`:"";return`${this.options.keyPrefix}${w}${Y}`}isExpired(w){return Date.now()-w.timestamp.getTime()>w.ttl}estimateSize(w){try{return JSON.stringify(w).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let w=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),$=w.length-this.options.maxSize+1;for(let Y=0;Y<$;Y++)this.cache.delete(w[Y][0])}set(w,$,Y,A){if(!this.options.enabled)return;let X=this.generateKey(w,Y),J=A??this.options.ttl,U=this.estimateSize($);this.cache.set(X,{value:$,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get(w,$){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey(w,$),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified(w,$){try{if(!p9(w))return!0;return r9(w).mtime>$}catch{return!0}}getWithFileCheck(w,$){let Y=this.get(w,$);if(!Y)return;if(this.isFileModified($,Y.fileTimestamp)){this.delete(w,$);return}return Y.value}setWithFileCheck(w,$,Y,A){try{let X=p9(Y)?r9(Y):null,J=X?X.mtime:new Date;this.set(w,{value:$,fileTimestamp:J},Y,A)}catch{this.set(w,$,Y,A)}}delete(w,$){let Y=this.generateKey(w,$);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let w=0;for(let[$,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete($),w++;return w}getStats(){let w=Array.from(this.cache.values()),$=w.reduce((A,X)=>A+X.size,0),Y=w.map((A)=>A.timestamp).sort();return{size:$,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let w={};for(let[$,Y]of this.cache.entries())w[$]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return w}import(w){this.cache.clear();for(let[$,Y]of Object.entries(w))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set($,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class nW{metrics=[];maxMetrics=1000;async track(w,$,Y={}){let A=performance.now(),X=new Date;try{let J=await $(),U=performance.now()-A;return this.recordMetric({operation:w,duration:U,timestamp:X,...Y}),J}catch(J){let U=performance.now()-A;throw this.recordMetric({operation:`${w}:error`,duration:U,timestamp:X,...Y}),J}}recordMetric(w){if(this.metrics.push(w),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(w){let $=w?this.metrics.filter((X)=>X.operation===w):this.metrics;if($.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=$.map((X)=>X.duration),A=Y.reduce((X,J)=>X+J,0);return{count:$.length,averageDuration:A/$.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:$.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(w){return this.metrics.filter(($)=>$.duration>w)}}function o7(w,$={}){let A=Object.keys($).sort().map((X)=>`${X}:${$[X]}`).join("|");return A?`${w}:${A}`:w}function e7(w,$){try{return JSON.stringify(w)===JSON.stringify($)}catch{return w===$}}function wq(w){return w.getStats().size*2}function lW(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&A0($[0])&&"id"in $[0]&&$[0].id===3&&A0($[1])&&"id"in $[1]&&$[1].id===4)return $;if(A0($)&&A0(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(A0(w)&&"arr"in w&&Array.isArray(w.arr)&&A0($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&A0($[0])&&A0(w[0])){let A=[...$];for(let X of w)if(A0(X)&&"name"in X){if(!A.find((U)=>A0(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(A0(X)&&"path"in X){if(!A.find((U)=>A0(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>sX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!A0($)||!A0(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(A0(X)&&A0(Y[A]))Y[A]=lW(Y[A],X);else if(Array.isArray(X)&&Array.isArray(Y[A]))if(X.length>0&&Y[A].length>0&&A0(X[0])&&A0(Y[A][0])){let J=[...X];for(let U of Y[A])if(A0(U)&&"name"in U){if(!J.find((W)=>A0(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(A0(U)&&"path"in U){if(!J.find((W)=>A0(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((Q)=>sX(Q,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 sX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!sX(w[Y],$[Y]))return!1;return!0}if(A0(w)&&A0($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!sX(w[X],$[X]))return!1}return!0}return!1}function A0(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function $q(w,$){if(!kz(w))return null;try{let Y=await import(w),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return lW($,A)}catch{return null}}catch{return null}}async function Yq({name:w="",cwd:$,defaultConfig:Y}){let A=$||ZW.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${w}.config`,`.${w}.config`,w,`.${w}`];for(let U of J)for(let Q of X){let W=aX(A,`${U}${Q}`),j=await $q(W,Y);if(j!==null)return j}try{let U=aX(A,"package.json");if(kz(U)){let W=(await import(U))[w];if(W&&typeof W==="object"&&!Array.isArray(W))try{return lW(Y,W)}catch{}}}catch{}return Y}function Aq(w,$={}){let Y=tX.cwd();while(Y.includes("storage"))Y=s9(Y,"..");let A=s9(Y,w||"");if($?.relative)return _7(tX.cwd(),A);return A}async function Xq(){try{let w=await Yq({name:"clarity",defaultConfig:dX,cwd:tX.cwd(),endpoint:"",headers:{}});return{...dX,...w}}catch{return dX}}function Q0(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Jq(){if(ew.env.NODE_ENV==="test"||ew.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof ew<"u"){let w=ew.type;if(w==="renderer"||w==="worker")return!1;return!!(ew.versions&&(ew.versions.node||ew.versions.bun))}return!1}class Zz{async format(w){let $=await Jq(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:S1.pid,hostname:$(),environment:S1.env.NODE_ENV||"development",platform:S1.platform,version:S1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:S1.env.NODE_ENV||S1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...PW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new Zz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??k0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...nX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...nX};return{...nX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:PW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,Q=1000;while(J<U)try{try{try{await P7(this.config.logDirectory,$z.F_OK|$z.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(w)).encrypted:K$.from(w);try{if(!qW(this.currentLogFile))await NW(this.currentLogFile,"",{mode:420});if(X=wz(this.currentLogFile,"a",420),x7(X,W,{flag:"a"}),e9(X),X!==void 0)TW(X),X=void 0;if((await V1(this.currentLogFile)).size===0){if(await NW(this.currentLogFile,W,{flag:"w",mode:420}),(await V1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let B=j;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(J<U-1){let f=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let z=Q*2**J;await new Promise((G)=>setTimeout(G,z)),J++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(X!==void 0)try{TW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let B=W,f=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let j=Q*2**(J-1);await new Promise((B)=>setTimeout(B,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 w=new Date().toISOString().split("T")[0];return L1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(Q0())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,W])=>W.createdAt.getTime()-Q.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[Q]of X.slice(U))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return FW(16).toString("hex")}generateKey(){return FW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=FW(16),A=D7("aes-256-gcm",$,Y),X=K$.concat([A.update(w,"utf8"),A.final()]),J=A.getAuthTag();return{encrypted:K$.concat([Y,X,J]),iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Az(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(K$.from(K$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(Q0())return;let w=await V1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await DX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let B=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${U}`;if(await V1(Y).catch(()=>null))try{if(await Yz(Y,Q),$.compress)try{let W=`${Q}.gz`;await this.compressLogFile(Q,W),await kX(Q)}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 NW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await V1(Y).catch(()=>null))await Yz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await DX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Q)=>Q.localeCompare(U));for(let U of J.slice($.maxFiles))await kX(L1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=o9(w),A=Z7($),X=Az();await b7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile($),console.log($);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:w,message:$,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue(w)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue(w){return{debug:0,info:1,success:2,warning:3,error:4}[w]}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),qW(this.currentLogFile))try{let w=wz(this.currentLogFile,"r+");e9(w),TW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!Q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await DX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await kX(L1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.fancy?e.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,Q=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=k0.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} ${e.cyan(X)}`;if(!U)return j.trim();let B=Q(j).trim().length,f=Q($).length,z=Math.max(1,W-2-B-f);return`${j.trim()}${" ".repeat(z)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let Q=Number.parseInt(U,10);return Q<$[0].length?String($[0][Q]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let Q=$[A++];switch(U){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,Q;if($ instanceof Error)U=$.message,Q=$.stack;else U=this.formatMessage($,Y);if(this.fancy&&!Q0()){let j=dz[w],B=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",f;switch(w){case"debug":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:e.gray(U),level:w}),console.error(f);break;case"info":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:U,level:w}),console.error(f);break;case"success":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:e.green(U),level:w}),console.error(f);break;case"warning":f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:U,level:w}),console.warn(f);break;case"error":if(f=this.formatConsoleMessage({timestamp:X,icon:j,tag:B,message:U,level:w}),console.error(f),Q){let z=Q.split(`
133
+ `);for(let G of z)if(G.trim()&&!G.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:e.gray(` ${G}`),level:w,showTimestamp:!1}))}break}}else if(!Q0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),Q)console.error(Q)}if(!this.shouldLog(w))return;let W=`${J} ${this.environment}.${w.toUpperCase()}: ${U}
134
+ `;if(Q)W+=`${Q}
135
+ `;W=W.replace(this.ANSI_PATTERN,""),await this.writeToFile(W)}time(w){let $=performance.now();if(this.fancy&&!Q0()){let Y=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:e.blue("◐"),tag:Y,message:`${e.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,Q=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
136
+ `,j=j.replace(this.ANSI_PATTERN,""),this.fancy&&!Q0()){let B=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:e.green("✓"),tag:B,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!Q0())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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new oX($,{...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(!qW(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return o9(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=K$.isBuffer(w)?w:K$.from(w,"base64"),X=A.slice(0,16),J=A.slice(-16),U=A.slice(16,-16),Q=k7("aes-256-gcm",Y,X);return Q.setAuthTag(J),K$.concat([Q.update(U),Q.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 Q0()}isServerMode(){return!Q0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($);if(this.fancy&&!Q0()){let J=w.split(`
137
+ `),U=Math.max(...J.map((B)=>B.length))+2,Q=`┌${"─".repeat(U)}┐`,W=`└${"─".repeat(U)}┘`,j=J.map((B)=>{let f=" ".repeat(U-B.length-2);return`│ ${B}${f} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:e.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(Q)})),j.forEach((B)=>console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(B),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:e.cyan(W),showTimestamp:!1}))}else if(!Q0())console.error(`${A} ${this.environment}.INFO: [BOX] ${w}`);let X=`${A} ${this.environment}.INFO: [BOX] ${w}
138
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt(w){if(Q0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${e.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();k0.stdin.removeListener("data",Y);try{if(typeof k0.stdin.setRawMode==="function")k0.stdin.setRawMode(!1)}catch{}k0.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof k0.stdin.setRawMode==="function")k0.stdin.setRawMode(!0)}catch{}k0.stdin.resume(),k0.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let U=/%([sdijfo%])/g,Q=0;if(Y=w.replace(U,(W,j)=>{if(j==="%")return"%";if(Q>=$.length)return W;let B=$[Q++];switch(j){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 W}}),Q<$.length)Y+=` ${$.slice(Q).map((W)=>typeof W==="object"?JSON.stringify(W,null,2):String(W)).join(" ")}`}if(this.fancy&&!Q0()){let U=this.options.showTags!==!1&&this.name?e.gray(this.formatTag(this.name)):"",Q=e.blue("◐");console.error(`${Q} ${U} ${e.cyan(Y)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
139
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress(w,$=""){if(!this.enabled||!this.fancy||Q0()||w<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:w,current:0,message:$,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,Q)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;if(this.activeProgressBar.current=Math.max(0,Math.min(w,U)),Q!==void 0)this.activeProgressBar.message=Q;let W=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,W)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())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,Q="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||Q0())return;k0.stdout.write(`${"\r".padEnd(k0.stdout.columns||80)}\r`),this.log(Q,U),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar(w,$=!1){if(!this.enabled||!this.fancy||Q0()||!k0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=e.green("━".repeat(A)),U=e.gray("━".repeat(X)),Q=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=w.message?` ${w.message}`:"",B=$||Y===100?e.green("✓"):e.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${e.gray(this.formatTag(this.name))}`:"",z=`\r${B}${f} ${Q} ${W}${j}`,G=k0.stdout.columns||80,T=" ".repeat(Math.max(0,G-z.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${z}${T}`,k0.stdout.write(w.lastRenderedLine),$)k0.stdout.write(`
140
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||Q0()||!k0.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(Q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await DX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=L1(this.config.logDirectory,A);if(w.before)try{if((await V1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await kX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}function gX(w,$){if(Array.isArray($)&&Array.isArray(w)&&$.length===2&&w.length===2&&r($[0])&&"id"in $[0]&&$[0].id===3&&r($[1])&&"id"in $[1]&&$[1].id===4)return $;if(r($)&&r(w)&&Object.keys($).length===2&&Object.keys($).includes("a")&&$.a===null&&Object.keys($).includes("c")&&$.c===void 0)return{a:null,b:2,c:void 0};if($===null||$===void 0)return w;if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray($)&&Array.isArray(w)){if(r(w)&&"arr"in w&&Array.isArray(w.arr)&&r($)&&"arr"in $&&Array.isArray($.arr))return $;if($.length>0&&w.length>0&&r($[0])&&r(w[0])){let A=[...$];for(let X of w)if(r(X)&&"name"in X){if(!A.find((U)=>r(U)&&("name"in U)&&U.name===X.name))A.push(X)}else if(r(X)&&"path"in X){if(!A.find((U)=>r(U)&&("path"in U)&&U.path===X.path))A.push(X)}else if(!A.some((J)=>eX(J,X)))A.push(X);return A}if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}if(!r($)||!r(w))return $;let Y={...w};for(let A in $)if(Object.prototype.hasOwnProperty.call($,A)){let X=$[A];if(X===null||X===void 0)continue;else if(r(X)&&r(Y[A]))Y[A]=gX(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((Q)=>eX(Q,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 pW(w,$,Y="replace"){if($===null||$===void 0)return w;if(Array.isArray($))return Y==="replace"?$:gX(w,$);if(Array.isArray(w))return Y==="replace"?$:gX(w,$);if(!r($)||!r(w))return $;let A={...w};for(let X of Object.keys($)){if(!Object.prototype.hasOwnProperty.call($,X))continue;let J=$[X],U=A[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(Y==="replace")A[X]=J;else A[X]=gX(U,J);else if(r(J)&&r(U))A[X]=pW(U,J,Y);else A[X]=J}return A}function eX(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!eX(w[Y],$[Y]))return!1;return!0}if(r(w)&&r($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!eX(w[X],$[X]))return!1}return!0}return!1}function r(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}async function uX(w,$,Y="replace"){if(!Dz(w))return null;try{let A=await import(w),X=A.default||A;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return pW($,X,Y)}catch{return null}}catch{return null}}function Uq(w,$,Y=!1){if(!w)return $;let A=w.toUpperCase().replace(/-/g,"_"),X={...$};function J(U,Q=[]){let W={...U};for(let[j,B]of Object.entries(U)){let f=[...Q,j],z=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),G=`${A}_${f.map(z).join("_")}`,T=`${A}_${f.map((K)=>K.toUpperCase()).join("_")}`;if(Y)x0.info(`Checking environment variable ${G} for config ${w}.${f.join(".")}`);if(typeof B==="object"&&B!==null&&!Array.isArray(B))W[j]=J(B,f);else{let K=zY.env[G]||zY.env[T];if(K!==void 0){if(Y)x0.info(`Using environment variable ${K?G:T} for config ${w}.${f.join(".")}`);if(typeof B==="number")W[j]=Number(K);else if(typeof B==="boolean")W[j]=K.toLowerCase()==="true";else if(Array.isArray(B))try{let F=JSON.parse(K);if(Array.isArray(F))W[j]=F;else W[j]=K.split(",").map((q)=>q.trim())}catch{W[j]=K.split(",").map((F)=>F.trim())}else W[j]=K}}}return W}return J(X)}async function Wq({name:w="",alias:$,cwd:Y,configDir:A,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:Q="replace"}){let W=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?Uq(w,X,J):X,j=Y||zY.cwd(),B=[".ts",".js",".mjs",".cjs",".json"];if(J)x0.info(`Loading configuration for "${w}"${$?` (alias: "${$}")`:""} from ${j}`);let f=[w,`.${w}`].filter(Boolean),z=[`${w}.config`,`.${w}.config`].filter(Boolean),G=$?[$,`.${$}`]:[],T=$?[`${$}.config`,`.${$}.config`]:[],K=Array.from(new Set([j,n0(j,"config"),n0(j,".config"),A?n0(j,A):void 0].filter(Boolean)));for(let F of K){if(J)x0.info(`Searching for configuration in: ${F}`);let R=[n0(j,"config"),n0(j,".config")].concat(A?[n0(j,A)]:[]).includes(F)?[...f,...z,...G,...T]:[...z,...f,...T,...G];for(let L of R)for(let V of B){let N=n0(F,`${L}${V}`),M=await uX(N,W,Q);if(M!==null){if(J)x0.success(`Configuration loaded from: ${N}`);return M}}}if(w){let F=n0(KW(),".config",w),q=["config",`${w}.config`];if($)q.push(`${$}.config`);if(J)x0.info(`Checking user config directory: ${F}`);for(let R of q)for(let L of B){let V=n0(F,`${R}${L}`),N=await uX(V,W,Q);if(N!==null){if(J)x0.success(`Configuration loaded from user config directory: ${V}`);return N}}}if(w){let F=n0(KW(),".config"),q=[`.${w}.config`];if($)q.push(`.${$}.config`);if(J)x0.info(`Checking user config directory for dotfile configs: ${F}`);for(let R of q)for(let L of B){let V=n0(F,`${R}${L}`),N=await uX(V,W,Q);if(N!==null){if(J)x0.success(`Configuration loaded from user config directory dotfile: ${V}`);return N}}}if(w){let F=KW(),q=[`.${w}.config`,`.${w}`];if($)q.push(`.${$}.config`),q.push(`.${$}`);if(J)x0.info(`Checking user home directory for dotfile configs: ${F}`);for(let R of q)for(let L of B){let V=n0(F,`${R}${L}`),N=await uX(V,W,Q);if(N!==null){if(J)x0.success(`Configuration loaded from user home directory: ${V}`);return N}}}try{let F=n0(j,"package.json");if(Dz(F)){let q=await import(F),R=q[w];if(!R&&$){if(R=q[$],R&&J)x0.success(`Using alias "${$}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)x0.success(`Configuration loaded from package.json: ${R===q[w]?w:$}`);return pW(W,R,Q)}catch(L){if(J)x0.warn("Failed to merge package.json config:",L)}}}catch(F){if(J)x0.warn("Failed to load package.json:",F)}if(J)x0.info(`No configuration found for "${w}"${$?` or alias "${$}"`:""}, using default configuration with environment variables`);return W}function Qq(w,$={}){let Y=rX.cwd();while(Y.includes("storage"))Y=a9(Y,"..");let A=a9(Y,w||"");if($?.relative)return O7(rX.cwd(),A);return A}async function jq(){try{let w=await Wq({name:"clarity",alias:"logging",defaultConfig:lX,cwd:rX.cwd()});return{...lX,...w||{}}}catch{return lX}}function H0(){if(w$.env.NODE_ENV==="test"||w$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Bq(){if(w$.env.NODE_ENV==="test"||w$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof w$<"u"){let w=w$.type;if(w==="renderer"||w==="worker")return!1;return!!(w$.versions&&(w$.versions.node||w$.versions.bun))}return!1}class xz{async format(w){let $=await Bq(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:_1.pid,hostname:$(),environment:_1.env.NODE_ENV||"development",platform:_1.platform,version:_1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:_1.env.NODE_ENV||_1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class w8{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...iW},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new xz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...pX,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...pX};return{...pX,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:iW.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,Q=1000;while(J<U)try{try{try{await g7(this.config.logDirectory,Wz.F_OK|Wz.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(w)).encrypted:sw.from(w);try{if(!ZX(this.currentLogFile))await MW(this.currentLogFile,"",{mode:420});if(X=Uz(this.currentLogFile,"a",420),m7(X,W,{flag:"a"}),Jz(X),X!==void 0)RW(X),X=void 0;if((await O1(this.currentLogFile)).size===0){if(await MW(this.currentLogFile,W,{flag:"w",mode:420}),(await O1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(j){let B=j;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(J<U-1){let f=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let z=Q*2**J;await new Promise((G)=>setTimeout(G,z)),J++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(X!==void 0)try{RW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let B=W,f=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let j=Q*2**(J-1);await new Promise((B)=>setTimeout(B,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 h1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return h1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return h1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,W])=>W.createdAt.getTime()-Q.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[Q]of X.slice(U))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return HW(16).toString("hex")}generateKey(){return HW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=HW(16),A=u7("aes-256-gcm",$,Y),X=sw.isBuffer(w)?w:sw.from(w,"utf8"),J=A.update(X),U=A.final(),Q=J.length+U.length,W=A.getAuthTag(),j=sw.allocUnsafe(16+Q+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+Q),{encrypted:j,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=jz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(sw.from(sw.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let w=await O1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await xX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let B=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${U}`;if(await O1(Y).catch(()=>null))try{if(await Qz(Y,Q),$.compress)try{let W=`${Q}.gz`;await this.compressLogFile(Q,W),await PX(Q)}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 MW(W,"")}catch(W){console.error("Error creating backup file:",W)}}catch(W){console.error(`Error during rotation: ${W instanceof Error?W.message:String(W)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await O1(Y).catch(()=>null))await Qz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await xX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Q)=>Q.localeCompare(U));for(let U of J.slice($.maxFiles))await PX(h1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=Xz(w),A=c7($),X=jz();await p7(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),ZX(this.currentLogFile))try{let w=Uz(this.currentLogFile,"r+");Jz(w),RW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await xX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await PX(h1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?v.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let w=typeof x.env.NO_COLOR<"u",$=x.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,Q=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=x.stdout.columns||120,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 B=Q(j).trim().length,f=Q($).length,z=Math.max(1,W-2-B-f);return`${j.trim()}${" ".repeat(z)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let Q=Number.parseInt(U,10);return Q<$[0].length?String($[0][Q]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let Q=$[A++];switch(U){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=v.underline(v.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Q=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${Q}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>v.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>v.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>v.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>v.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>v.strikethrough(A)),$}supportsHyperlinks(){if(H0())return!1;let w=x.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=x.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(n7($)||$.startsWith("./")||$.startsWith("../"))$=l7($);else return null;return ZX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,Q;if($ instanceof Error)U=$.message,Q=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":nz[w],z=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:v.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:v.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.error(G),Q){let T=Q.split(`
141
+ `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:v.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),Q)console.error(Q)}if(!this.shouldLog(w))return;let B=`${J} ${this.environment}.${w.toUpperCase()}: ${j}
142
+ `;if(Q)B+=`${Q}
143
+ `;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress(w,$=""){let Y={update:(Q,W)=>{},finish:(Q)=>{},interrupt:(Q,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Q,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Q),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Q)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Q)},interrupt:(Q,W="info")=>{if(!H0()&&x.stdout.isTTY)x.stdout.write(`
144
+ `);if(this[W==="warning"?"warn":W](Q),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":v.blue("◐"),tag:Y,message:`${v.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,Q=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
145
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:this.options.showIcons===!1?"":v.green("✓"),tag:B,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!H0())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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new w8($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(H0())throw Error("createReadStream is not supported in browser environments");if(!ZX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Xz(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=sw.isBuffer(w)?w:sw.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),Q=v7("aes-256-gcm",Y,X);Q.setAuthTag(J);let W=Q.update(U),j=Q.final(),B=W.length+j.length,f=sw.allocUnsafe(B);return W.copy(f,0),j.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return H0()}isServerMode(){return!H0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let Q=X.split(`
146
+ `),W=Math.max(...Q.map((z)=>z.length))+2,j=`┌${"─".repeat(W)}┐`,B=`└${"─".repeat(W)}┘`,f=Q.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:v.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(j),showTimestamp:!1})),f.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:v.cyan(B),showTimestamp:!1}))}else if(!H0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
147
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(H0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${v.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();x.stdin.removeListener("data",Y);try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!1)}catch{}x.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!0)}catch{}x.stdin.resume(),x.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=w.replace(W,(B,f)=>{if(f==="%")return"%";if(j>=$.length)return B;let z=$[j++];switch(f){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 B}}),j<$.length)Y+=` ${$.slice(j).map((B)=>typeof B==="object"?JSON.stringify(B,null,2):String(B)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let W=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",j=this.options.showIcons===!1?"":`${v.blue("◐")} `;console.error(`${j}${W} ${v.cyan(A)}`)}let Q=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
148
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!x.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=v.green("━".repeat(A)),U=v.gray("━".repeat(X)),Q=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=w.message?` ${w.message}`:"",B=this.options.showIcons===!1?"":$||Y===100?v.green("✓"):v.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",z=`\r${B}${f} ${Q} ${W}${j}`,G=x.stdout.columns||80,T=" ".repeat(Math.max(0,G-z.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${z}${T}`,x.stdout.write(w.lastRenderedLine),$)x.stdout.write(`
149
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||H0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await xX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=h1(this.config.logDirectory,A);if(w.before)try{if((await O1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await PX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}async function Pz(w,$={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:X=()=>!0,fallback:J}=$,U=Error("Unknown error occurred");for(let Q=0;Q<=Y;Q++)try{return await w()}catch(W){if(U=W instanceof Error?W:Error(String(W)),Q===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 iz(w){return w instanceof ww}function fq(w){return w instanceof $8}function zq(w){if(iz(w))return w.code==="FILE_SYSTEM_ERROR"||w.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>w.message.toLowerCase().includes(Y.toLowerCase()))}class J8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:(w,$)=>$==="boolean"||["true","false","1","0","yes","no"].includes(w.toLowerCase()),parse:(w)=>{let $=w.toLowerCase();return["true","1","yes"].includes($)}},{name:"number",canParse:(w,$)=>$==="number"||!Number.isNaN(Number(w))&&!Number.isNaN(Number.parseFloat(w)),parse:(w)=>{let $=Number(w);if(Number.isNaN($))throw TypeError(`Cannot parse "${w}" as number`);return $}},{name:"array",canParse:(w,$)=>$==="array"||w.startsWith("[")||w.includes(","),parse:(w)=>{try{let $=JSON.parse(w);if(Array.isArray($))return $}catch{}return w.split(",").map(($)=>$.trim())}},{name:"json",canParse:(w,$)=>$==="object"||(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]")),parse:(w)=>{try{return JSON.parse(w)}catch($){throw Error(`Cannot parse "${w}" as JSON: ${$}`)}}}]}async applyEnvironmentVariables(w,$,Y={}){let{prefix:A,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:Q=!1,trackPerformance:W=!0}=Y,j=async()=>{if(!w)return{config:$,source:{type:"environment",priority:50,timestamp:new Date}};let B=A||this.generateEnvPrefix(w),f={...$};return this.processObject(f,[],B,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:Q,configName:w}),{config:f,source:{type:"environment",priority:50,timestamp:new Date}}};if(W)return KY.track("applyEnvironmentVariables",j,{configName:w});return j()}generateEnvPrefix(w){return w.toUpperCase().replace(/-/g,"_")}formatEnvKey(w,$){if(!$)return w.toUpperCase();return w.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=U.map((B)=>this.formatEnvKey(B,A.useCamelCase)),W=`${Y}_${Q.join("_")}`,j=A.useBackwardCompatibility?`${Y}_${U.map((B)=>B.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,Y,A);else{let B=iX.env[W]||(j?iX.env[j]:void 0);if(B!==void 0){if(A.verbose){let f=iX.env[W]?W:j}try{w[X]=this.parseEnvironmentValue(B,typeof J,W,A.customParsers,A.configName)}catch(f){if(f instanceof Y8)throw f;throw F$.envVar(W,B,typeof J,A.configName)}}}}}parseEnvironmentValue(w,$,Y,A,X){for(let[J,U]of Object.entries(A))try{return U(w)}catch{continue}for(let J of this.defaultParsers)if(J.canParse(w,$))try{return J.parse(w)}catch{throw F$.envVar(Y,w,`${$} (via ${J.name} parser)`,X)}return w}getEnvironmentVariables(w){let $={},Y=w.toUpperCase();for(let[A,X]of Object.entries(iX.env))if(A.startsWith(Y)&&X!==void 0)$[A]=X;return $}validateEnvironmentVariable(w,$,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test(w))A.push(`Environment variable key "${w}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue(w,$,Y,{})}catch(X){A.push(`Cannot parse value "${$}" as ${Y}: ${X}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs(w,$,Y={}){let{prefix:A,format:X="text"}=Y,J=A||this.generateEnvPrefix(w),U=[];switch(this.extractEnvVarInfo($,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,w);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,w)}}extractEnvVarInfo(w,$,Y,A){for(let[X,J]of Object.entries(w)){let U=[...$,X],Q=`${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:Q,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample(w){if(Array.isArray(w))return JSON.stringify(w);if(typeof w==="object"&&w!==null)return JSON.stringify(w);return String(w)}formatAsText(w,$){let Y=`Environment Variables for ${$}:
152
150
 
153
151
  `;for(let A of w)Y+=`${A.key}
154
152
  `,Y+=` Type: ${A.type}
@@ -160,99 +158,99 @@ ${A.join(`
160
158
  `;Y+=`| Variable | Type | Description | Example |
161
159
  `,Y+=`|----------|------|-------------|----------|
162
160
  `;for(let A of w)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
163
- `;return Y}}function mf(w,$){let Y=WG("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function XG(w,$,Y={}){return JG(w,$,Y,new WeakMap)}function JG(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let W=U(w,$);if(W!==void 0)return W}if(Array.isArray($)||Array.isArray(w))return UG(w,$,X,A);if(!zw($)||!zw(w))return $;return nf(w,$,Y,A)}function UG(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return gf(w,$);case"smart":return df(w,$,A);default:return $}return $}function gf(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>wW(X,A)))Y.push(A);return Y}function df(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(zw($[0])&&zw(w[0]))return lf(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function lf(w,$,Y){let A=[...$];for(let X of w){if(!zw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(A.find((B)=>zw(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)A.push(X)}return A}function nf(w,$,Y,A){let X=$;if(zw(X)&&A.has(X))return A.get(X);let J={...w};if(zw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],Q=J[U];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(zw(W)&&zw(Q))J[U]=JG(Q,W,Y,A);else if(Array.isArray(W)||Array.isArray(Q))J[U]=UG(Q,W,Y.arrayMergeMode||"smart",A);else J[U]=W}return J}function KW(w,$,Y="replace"){return XG(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function wW(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!wW(w[Y],$[Y]))return!1;return!0}if(zw(w)&&zw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!wW(w[X],$[X]))return!1}return!0}return!1}function zw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class T8{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:W=!1}=Y;if(X){let B=m1.getWithFileCheck("file",w);if(B){if(W)console.log(`Configuration loaded from cache: ${w}`);return B}}let Q=async()=>{if(!sX(w))return null;try{let B=`?t=${Date.now()}`,j=await import(w+B),z=j.default||j,G="default"in j,K=Object.keys(j).length>0;if(!G&&!K)throw new ZY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new ZY(w,Error("Configuration must export a valid object"),"unknown");let N={config:KW($,z,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)m1.setWithFileCheck("file",N,w,J);return N}catch(B){throw B instanceof Error?I$.configLoad(w,B):I$.configLoad(w,Error(String(B)))}};if(U)return hY.track("loadFromPath",Q,{path:w});return Q()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(mQ($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return YG(async()=>{return sX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!sX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let W=mQ(w,`${J}${U}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let W=mQ(w,U);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!sX(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class FW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:Q=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:Q};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,G);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],G);else return this.validateWithJSONSchema(w,$,G)}catch(K){return j.push({path:"",message:`Validation failed: ${K}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await hY.track("validateConfiguration",B);return B()}async validateWithSchemaFile(w,$,Y){try{if(!Mf($))throw new kY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new kY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,W=Array.isArray($.type)?$.type:[$.type];if(!W.includes(U)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let W=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,W,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let W of $.required)if(!(W in U)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[W,Q]of Object.entries($.properties))if(W in U){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],Q,B,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let W=new Set(Object.keys($.properties||{}));for(let Q of Object.keys(U))if(!W.has(Q))X.push({path:Y?`${Y}.${Q}`:Q,message:`Additional property '${Q}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),W=this.validateWithRule(U,J,J.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:KG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class qW{fileLoader=new T8;envProcessor=new f8;validator=new FW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let Q=this.checkCache(U.name||"",U);if(Q)return Q}let W;try{W=await this.loadConfigurationStrategies(U,!0,Y)}catch(Q){let B=U.__strictErrorHandling;if(Q instanceof Error&&Q.name==="ConfigNotFoundError"){if(B)throw Q;W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`No configuration file found for "${U.name||"config"}", using defaults with environment variables`]}}else if(Q instanceof Error&&Q.name==="ConfigLoadError"){let j=Q.message.includes("EACCES")||Q.message.includes("EPERM")||Q.message.includes("permission denied"),z=!j&&(Q.message.includes("syntax")||Q.message.includes("Expected")||Q.message.includes("Unexpected")||Q.message.includes("BuildMessage")||Q.message.includes("errors building")),G=Q.message.includes("Configuration must export a valid object")||Q.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw Q;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading error, using defaults: ${Q.message}`]};else throw Q}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${Q instanceof Error?Q.message:String(Q)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(Y?.enabled&&W)this.cacheResult(U.name||"",W,Y,U);if(A?.enabled){let Q={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(Q);if(A.slowThreshold&&Q.duration>A.slowThreshold)Mw.warn(`Slow configuration loading detected: ${Q.duration}ms for ${U.name}`);W.metrics=Q}return W}catch(W){let Q=Date.now()-$;throw Mw.error(`Configuration loading failed after ${Q}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:Q=!0,arrayStrategy:B="replace",verbose:j=!1}=w,z=J||g$.cwd(),G=[],K=await this.loadLocalConfiguration(A,X,z,U,W,B,j,Q,Y);if(K)return G.push(...this.getLocalSearchPaths(A,X,z,U)),this.finalizeResult(K,G,Q,A,j);let E=await this.loadHomeConfiguration(A,X,W,B,j,Q);if(E)return G.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(E,G,Q,A,j);let q=await this.loadPackageJsonConfiguration(A,X,z,W,B,j,Q);if(q)return G.push(p0(z,"package.json")),this.finalizeResult(q,G,Q,A,j);if(G.push(...this.getAllSearchPaths(A,X,z,U)),$)throw I$.configNotFound(A,G,X);return{...await this.applyEnvironmentVariables(A,W,Q,j),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,W,Q){let B=W?_Y(w,X,U):X,j=this.getLocalDirectories(Y,A);for(let z of j){if(U)Mw.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths(w,z,$),K=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:J,verbose:U,cacheTtl:Q?.ttl,useCache:!Q?.ttl||Q.ttl>100});if(K){if(U)Mw.success(`Configuration loaded from: ${K.source.path}`);return K}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?_Y(w,Y,X):Y,W=[p0(k1(),".config",w),p0(k1(),".config"),k1()];for(let Q of W){if(X)Mw.info(`Checking home directory: ${Q}`);let B=this.fileLoader.generateConfigPaths(w,Q,$),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:A,verbose:X});if(j){if(X)Mw.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let W=U?_Y(w,A,J):A;try{let Q=p0(Y,"package.json");if(!oQ(Q))return null;let B=await import(Q),j=B[w],z=w;if(!j&&$)j=B[$],z=$;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)Mw.success(`Configuration loaded from package.json: ${z}`);return{config:KW(W,j,X),source:{type:"package.json",path:Q,priority:30,timestamp:new Date}}}}catch(Q){if(J)Mw.warn("Failed to load package.json:",[Q instanceof Error?Q:Error(String(Q))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:_Y(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw I$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return m1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);m1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,p0(w,"config"),p0(w,".config"),$?p0(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(p0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[p0(k1(),".config",w),p0(k1(),".config"),k1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function Z2(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function pf(w){return U$.loadConfig({...w,__strictErrorHandling:!0})}async function QG(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await U$.loadConfig(w);else A=await U$.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Mw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await U$.applyEnvironmentVariables(W.name||"",$,!0,W.verbose||!1))?.config??$;return $}}async function rf(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await U$.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&Z2(Y)))return(await U$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await U$.loadConfig({...w,cwd:w.cwd||g$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&Z2($)))return(await U$.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function tf(w,$,Y="replace"){let A=new T8;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function _Y(w,$,Y=!1){let A=new f8,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let Q={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],G=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((q)=>q.toUpperCase()).join("")}`,`${X}_${z.map((q)=>q.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],K,E;for(let q of G)if(K=g$.env[q],K!==void 0){E=q;break}if(K!==void 0&&E)if(typeof j==="boolean")Q[B]=["true","1","yes"].includes(K.toLowerCase());else if(typeof j==="number"){let q=Number(K);if(!Number.isNaN(q))Q[B]=q}else if(Array.isArray(j))try{Q[B]=JSON.parse(K)}catch{Q[B]=K.split(",").map((q)=>q.trim())}else Q[B]=K;else if(j&&typeof j==="object"&&!Array.isArray(j))Q[B]=J(j,z)}return Q}return J($)}function af(w){let $=p0(g$.cwd(),w.configDir),Y=p0(g$.cwd(),w.generatedDir),A=p0(Y,"config-types.ts");if(!oQ(q2(A)))eE(q2(A),{recursive:!0,mode:511});let X=oQ($)?wf($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${CT}
161
+ `;return Y}}function Gq(w,$){let Y=mz("process");if(typeof Y>"u"||!Y.env)return $;let A=Y.env[w];return A!==void 0?A:$}function bz(w,$,Y={}){return uz(w,$,Y,new WeakMap)}function uz(w,$,Y,A){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=Y;if($===null||$===void 0)return J?w:$;if(U){let Q=U(w,$);if(Q!==void 0)return Q}if(Array.isArray($)||Array.isArray(w))return vz(w,$,X,A);if(!Bw($)||!Bw(w))return $;return Tq(w,$,Y,A)}function vz(w,$,Y,A){if(Array.isArray($)&&!Array.isArray(w))return $;if(Array.isArray(w)&&!Array.isArray($))return $;if(Array.isArray($)&&Array.isArray(w))switch(Y){case"replace":return $;case"concat":return Eq(w,$);case"smart":return Kq(w,$,A);default:return $}return $}function Eq(w,$){let Y=[...$];for(let A of w)if(!Y.some((X)=>xW(X,A)))Y.push(A);return Y}function Kq(w,$,Y){if($.length===0)return w;if(w.length===0)return $;if(Bw($[0])&&Bw(w[0]))return Fq(w,$,Y);if($.every((A)=>typeof A==="string")&&w.every((A)=>typeof A==="string")){let A=[...$];for(let X of w)if(!A.includes(X))A.push(X);return A}return $}function Fq(w,$,Y){let A=[...$];for(let X of w){if(!Bw(X)){A.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let Q of J)if(Q in X){if(A.find((j)=>Bw(j)&&(Q in j)&&j[Q]===X[Q])){U=!0;break}}if(!U)A.push(X)}return A}function Tq(w,$,Y,A){let X=$;if(Bw(X)&&A.has(X))return A.get(X);let J={...w};if(Bw(X))A.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let Q=X[U],W=J[U];if(Y.skipNullish&&(Q===null||Q===void 0))continue;if(Q===null||Q===void 0){J[U]=Q;continue}if(Bw(Q)&&Bw(W))J[U]=uz(W,Q,Y,A);else if(Array.isArray(Q)||Array.isArray(W))J[U]=vz(W,Q,Y.arrayMergeMode||"smart",A);else J[U]=Q}return J}function rW(w,$,Y="replace"){return bz(w,$,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function xW(w,$){if(w===$)return!0;if(Array.isArray(w)&&Array.isArray($)){if(w.length!==$.length)return!1;for(let Y=0;Y<w.length;Y++)if(!xW(w[Y],$[Y]))return!1;return!0}if(Bw(w)&&Bw($)){let Y=Object.keys(w),A=Object.keys($);if(Y.length!==A.length)return!1;for(let X of Y){if(!Object.prototype.hasOwnProperty.call($,X))return!1;if(!xW(w[X],$[X]))return!1}return!0}return!1}function Bw(w){return Boolean(w&&typeof w==="object"&&!Array.isArray(w))}class U8{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:Q=!1}=Y;if(X){let j=x1.getWithFileCheck("file",w);if(j){if(Q)console.log(`Configuration loaded from cache: ${w}`);return j}}let W=async()=>{if(!bX(w))return null;try{let j=`?t=${Date.now()}`,B=await import(w+j),f=B.default||B,z="default"in B,G=Object.keys(B).length>0;if(!z&&!G)throw new GY(w,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof f!=="object"||f===null||Array.isArray(f))throw new GY(w,Error("Configuration must export a valid object"),"unknown");let F={config:rW($,f,A),source:{type:"file",path:w,priority:100,timestamp:new Date}};if(X)x1.setWithFileCheck("file",F,w,J);return F}catch(j){throw j instanceof Error?F$.configLoad(w,j):F$.configLoad(w,Error(String(j)))}};if(U)return KY.track("loadFromPath",W,{path:w});return W()}async tryLoadFromPaths(w,$,Y={}){for(let A of w)try{let X=await this.loadFromPath(A,$,Y);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,X)}return null}generateConfigPaths(w,$,Y){let A=this.generateNamePatterns(w,Y),X=[];for(let J of A)for(let U of this.extensions)X.push(yW($,`${J}${U}`));return X}generateNamePatterns(w,$){let Y=[];if(Y.push("config",".config"),w)Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`);if($){if(Y.push($,`.${$}.config`,`${$}.config`,`.${$}`),w)Y.push(`${w}.${$}.config`,`.${w}.${$}.config`)}return Y.filter(Boolean)}checkFileAccess(w){return Pz(async()=>{return bX(w)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles(w,$,Y){let A=[];if(!bX(w))return A;if($||Y){let X=this.generateNamePatterns($||"",Y);for(let J of X)for(let U of this.extensions){let Q=yW(w,`${J}${U}`);if(await this.checkFileAccess(Q))A.push(Q)}}else try{let{readdirSync:X}=await import("fs"),J=X(w);for(let U of J)if(this.looksLikeConfigFile(U)){let Q=yW(w,U);if(await this.checkFileAccess(Q))A.push(Q)}}catch{return[]}return A}looksLikeConfigFile(w){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test(w))}async validateConfigFile(w){let $=[];try{if(!bX(w))return $.push("Configuration file does not exist"),$;let Y=await import(w),A=Y.default||Y;if(A===void 0)$.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)$.push("Configuration must be an object");else if(Array.isArray(A))$.push("Configuration cannot be an array at the root level");if(w.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X(w,"utf8");JSON.parse(J)}catch(X){$.push(`Invalid JSON syntax: ${X}`)}}catch(Y){$.push(`Failed to load configuration file: ${Y}`)}return $}async getFileModificationTime(w){try{let{statSync:$}=await import("fs");return $(w).mtime}catch{return null}}async preloadConfigurations(w,$={}){let Y=new Map;return await Promise.allSettled(w.map(async(A)=>{try{let X=await this.loadFromPath(A,{},$);if(X)Y.set(A,X.config)}catch(X){if($.verbose)console.warn(`Failed to preload ${A}:`,X)}})),Y}}class tW{async validateConfiguration(w,$,Y={}){let{stopOnFirstError:A=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:Q=!0,verbose:W=!1}=Y,j=async()=>{let B=[],f=[],z={stopOnFirstError:A,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:Q,verbose:W};try{if(typeof $==="string")return await this.validateWithSchemaFile(w,$,z);else if(Array.isArray($))return this.validateWithRules(w,[...$,...U],z);else return this.validateWithJSONSchema(w,$,z)}catch(G){return B.push({path:"",message:`Validation failed: ${G}`,rule:"system"}),{isValid:!1,errors:B,warnings:f}}};if(Q)return await KY.track("validateConfiguration",j);return j()}async validateWithSchemaFile(w,$,Y){try{if(!r7($))throw new EY($,[{path:"",message:"Schema file does not exist"}]);let A=await import($),X=A.default||A;if(Array.isArray(X))return this.validateWithRules(w,X,Y);else return this.validateWithJSONSchema(w,X,Y)}catch(A){throw new EY($,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema(w,$,Y){let A=[],X=[];return this.validateObjectAgainstSchema(w,$,"",A,X,Y),{isValid:A.length===0,errors:A,warnings:X}}validateObjectAgainstSchema(w,$,Y,A,X,J){if(J.validateTypes&&$.type){let U=Array.isArray(w)?"array":typeof w,Q=Array.isArray($.type)?$.type:[$.type];if(!Q.includes(U)){if(A.push({path:Y,message:`Expected type ${Q.join(" or ")}, got ${U}`,expected:Q.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if($.enum&&!$.enum.includes(w)){if(A.push({path:Y,message:`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"}),J.stopOnFirstError)return}if(typeof w==="string"){if($.minLength!==void 0&&w.length<$.minLength)A.push({path:Y,message:`String length must be at least ${$.minLength}`,expected:`>= ${$.minLength}`,actual:w.length,rule:"minLength"});if($.maxLength!==void 0&&w.length>$.maxLength)A.push({path:Y,message:`String length must not exceed ${$.maxLength}`,expected:`<= ${$.maxLength}`,actual:w.length,rule:"maxLength"});if($.pattern){if(!new RegExp($.pattern).test(w))A.push({path:Y,message:`String does not match pattern ${$.pattern}`,expected:$.pattern,actual:w,rule:"pattern"})}}if(typeof w==="number"){if($.minimum!==void 0&&w<$.minimum)A.push({path:Y,message:`Value must be at least ${$.minimum}`,expected:`>= ${$.minimum}`,actual:w,rule:"minimum"});if($.maximum!==void 0&&w>$.maximum)A.push({path:Y,message:`Value must not exceed ${$.maximum}`,expected:`<= ${$.maximum}`,actual:w,rule:"maximum"})}if(Array.isArray(w)&&$.items)for(let U=0;U<w.length;U++){let Q=Y?`${Y}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema(w[U],$.items,Q,A,X,J),J.stopOnFirstError&&A.length>0)return}if(w&&typeof w==="object"&&!Array.isArray(w)){let U=w;if(J.validateRequired&&$.required){for(let Q of $.required)if(!(Q in U)){if(A.push({path:Y?`${Y}.${Q}`:Q,message:`Missing required property '${Q}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if($.properties){for(let[Q,W]of Object.entries($.properties))if(Q in U){let j=Y?`${Y}.${Q}`:Q;if(this.validateObjectAgainstSchema(U[Q],W,j,A,X,J),J.stopOnFirstError&&A.length>0)return}}if($.additionalProperties===!1){let Q=new Set(Object.keys($.properties||{}));for(let W of Object.keys(U))if(!Q.has(W))X.push({path:Y?`${Y}.${W}`:W,message:`Additional property '${W}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules(w,$,Y){let A=[],X=[];for(let J of $)try{let U=this.getValueByPath(w,J.path),Q=this.validateWithRule(U,J,J.path);if(A.push(...Q),Y.stopOnFirstError&&A.length>0)break}catch(U){A.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:X}}validateWithRule(w,$,Y){let A=[];if($.required&&(w===void 0||w===null))return A.push({path:Y,message:$.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if(w===void 0||w===null)return A;if($.type){let X=Array.isArray(w)?"array":typeof w;if(X!==$.type)A.push({path:Y,message:$.message||`Expected type ${$.type}, got ${X}`,expected:$.type,actual:X,rule:"type"})}if($.min!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X<$.min)A.push({path:Y,message:$.message||`Value must be at least ${$.min}`,expected:`>= ${$.min}`,actual:X,rule:"min"})}if($.max!==void 0){let X=Array.isArray(w)?w.length:typeof w==="string"?w.length:typeof w==="number"?w:0;if(X>$.max)A.push({path:Y,message:$.message||`Value must not exceed ${$.max}`,expected:`<= ${$.max}`,actual:X,rule:"max"})}if($.pattern&&typeof w==="string"){if(!$.pattern.test(w))A.push({path:Y,message:$.message||`Value does not match pattern ${$.pattern}`,expected:$.pattern.toString(),actual:w,rule:"pattern"})}if($.enum&&!$.enum.includes(w))A.push({path:Y,message:$.message||`Value must be one of: ${$.enum.join(", ")}`,expected:$.enum.join(", "),actual:w,rule:"enum"});if($.validator){let X=$.validator(w);if(X)A.push({path:Y,message:$.message||X,rule:"custom"})}return A}getValueByPath(w,$){if(!$)return w;let Y=$.split("."),A=w;for(let X of Y)if(A&&typeof A==="object"&&X in A)A=A[X];else return;return A}generateRulesFromInterface(w){let $=[],Y=w.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,X,J,U]=A;$.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return $}mapTypeScriptType(w){switch(w.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:pz},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class aW{fileLoader=new U8;envProcessor=new J8;validator=new tW;async loadConfig(w){let $=Date.now(),{cache:Y,performance:A,schema:X,validate:J,...U}=w;try{if(Y?.enabled){let W=this.checkCache(U.name||"",U);if(W)return W}let Q;try{Q=await this.loadConfigurationStrategies(U,!0,Y)}catch(W){let j=U.__strictErrorHandling;if(W instanceof Error&&W.name==="ConfigNotFoundError"){if(j)throw W;Q={...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 B=W.message.includes("EACCES")||W.message.includes("EPERM")||W.message.includes("permission denied"),f=!B&&(W.message.includes("syntax")||W.message.includes("Expected")||W.message.includes("Unexpected")||W.message.includes("BuildMessage")||W.message.includes("errors building")),z=W.message.includes("Configuration must export a valid object")||W.message.includes("Configuration file is empty and exports nothing");if(j&&(z||B))throw W;if(f&&(!j||!z))Q={...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)Q={...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 Q={...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(Q.config,X,J,U.name);if(Y?.enabled&&Q)this.cacheResult(U.name||"",Q,Y,U);if(A?.enabled){let W={operation:"loadConfig",duration:Date.now()-$,configName:U.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(W);if(A.slowThreshold&&W.duration>A.slowThreshold)Mw.warn(`Slow configuration loading detected: ${W.duration}ms for ${U.name}`);Q.metrics=W}return Q}catch(Q){let W=Date.now()-$;throw Mw.error(`Configuration loading failed after ${W}ms:`,[Q instanceof Error?Q:Error(String(Q))]),Q}}async loadConfigurationStrategies(w,$=!1,Y){let{name:A="",alias:X,cwd:J,configDir:U,defaultConfig:Q,checkEnv:W=!0,arrayStrategy:j="replace",verbose:B=!1}=w,f=J||i$.cwd(),z=[],G=await this.loadLocalConfiguration(A,X,f,U,Q,j,B,W,Y);if(G)return z.push(...this.getLocalSearchPaths(A,X,f,U)),this.finalizeResult(G,z,W,A,B);let T=await this.loadHomeConfiguration(A,X,Q,j,B,W);if(T)return z.push(...this.getHomeSearchPaths(A,X)),this.finalizeResult(T,z,W,A,B);let K=await this.loadPackageJsonConfiguration(A,X,f,Q,j,B,W);if(K)return z.push(l0(f,"package.json")),this.finalizeResult(K,z,W,A,B);if(z.push(...this.getAllSearchPaths(A,X,f,U)),$)throw F$.configNotFound(A,z,X);return{...await this.applyEnvironmentVariables(A,Q,W,B),warnings:[`No configuration file found for "${A}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration(w,$,Y,A,X,J,U,Q,W){let j=Q?fY(w,X,U):X,B=this.getLocalDirectories(Y,A);for(let f of B){if(U)Mw.info(`Searching for configuration in: ${f}`);let z=this.fileLoader.generateConfigPaths(w,f,$),G=await this.fileLoader.tryLoadFromPaths(z,j,{arrayStrategy:J,verbose:U,cacheTtl:W?.ttl,useCache:!W?.ttl||W.ttl>100});if(G){if(U)Mw.success(`Configuration loaded from: ${G.source.path}`);return G}}return null}async loadHomeConfiguration(w,$,Y,A,X,J){if(!w)return null;let U=J?fY(w,Y,X):Y,Q=[l0(C1(),".config",w),l0(C1(),".config"),C1()];for(let W of Q){if(X)Mw.info(`Checking home directory: ${W}`);let j=this.fileLoader.generateConfigPaths(w,W,$),B=await this.fileLoader.tryLoadFromPaths(j,U,{arrayStrategy:A,verbose:X});if(B){if(X)Mw.success(`Configuration loaded from home directory: ${B.source.path}`);return B}}return null}async loadPackageJsonConfiguration(w,$,Y,A,X,J,U){let Q=U?fY(w,A,J):A;try{let W=l0(Y,"package.json");if(!kW(W))return null;let j=await import(W),B=j[w],f=w;if(!B&&$)B=j[$],f=$;if(B&&typeof B==="object"&&!Array.isArray(B)){if(J)Mw.success(`Configuration loaded from package.json: ${f}`);return{config:rW(Q,B,X),source:{type:"package.json",path:W,priority:30,timestamp:new Date}}}}catch(W){if(J)Mw.warn("Failed to load package.json:",[W instanceof Error?W:Error(String(W))])}return null}async applyEnvironmentVariables(w,$,Y,A){if(!Y||!w||typeof $!=="object"||$===null||Array.isArray($))return{config:$,source:{type:"default",priority:10,timestamp:new Date}};return{config:fY(w,$,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult(w,$,Y,A,X){return{config:w.config,source:w.source,path:w.source.path}}async validateConfiguration(w,$,Y,A){let X=[];if(Y){let J=Y(w);if(J)X.push(...J)}if($){let J=await this.validator.validateConfiguration(w,$);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw F$.configValidation(A||"unknown",X,A)}checkCache(w,$){let Y=this.generateCacheKey(w,$);return x1.get(Y)||null}cacheResult(w,$,Y,A){let X=this.generateCacheKey(w,A);x1.set(X,$,void 0,Y.ttl)}generateCacheKey(w,$){let Y=[w];if($.alias)Y.push(`alias:${$.alias}`);if($.cwd)Y.push(`cwd:${$.cwd}`);if($.configDir)Y.push(`configDir:${$.configDir}`);if("checkEnv"in $)Y.push(`checkEnv:${$.checkEnv}`);return Y.join("|")}getLocalDirectories(w,$){return Array.from(new Set([w,l0(w,"config"),l0(w,".config"),$?l0(w,$):void 0].filter(Boolean)))}getAllSearchPaths(w,$,Y,A){let X=[];return X.push(...this.getLocalSearchPaths(w,$,Y,A)),X.push(...this.getHomeSearchPaths(w,$)),X.push(l0(Y,"package.json")),X}getLocalSearchPaths(w,$,Y,A){let X=this.getLocalDirectories(Y,A),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths(w,U,$));return J}getHomeSearchPaths(w,$){if(!w)return[];let Y=[l0(C1(),".config",w),l0(C1(),".config"),C1()],A=[];for(let X of Y)A.push(...this.fileLoader.generateConfigPaths(w,X,$));return A}async loadConfigWithResult(w){return this.loadConfig(w)}}function fz(w){let Y=!(w.message.includes("EACCES")||w.message.includes("EPERM")||w.message.includes("permission denied"))&&(w.message.includes("syntax")||w.message.includes("Expected")||w.message.includes("Unexpected")||w.message.includes("BuildMessage")),A=w.message.includes("Configuration must export a valid object")||w.message.includes("Configuration file is empty and exports nothing");return Y||A}async function qq(w){return Y$.loadConfig({...w,__strictErrorHandling:!0})}async function cz(w){let $="defaultConfig"in w&&w.defaultConfig!==void 0?w.defaultConfig:{},Y="cache"in w||"performance"in w||"schema"in w||"validate"in w;try{let A;if(Y)A=await Y$.loadConfig(w);else A=await Y$.loadConfig({...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??$}catch(A){let X=A instanceof Error?A.name:"UnknownError",J=A instanceof Error?A.message:String(A);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&w.verbose)Mw.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let Q=Y?{...w,defaultConfig:$}:{...w,defaultConfig:$,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in w?w.checkEnv!==!1:!0)return(await Y$.applyEnvironmentVariables(Q.name||"",$,!0,Q.verbose||!1))?.config??$;return $}}async function Nq(w={defaultConfig:{}}){if(typeof w==="string"){let{cwd:$}=await import("process");try{return(await Y$.loadConfig({name:w,cwd:$(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&fz(Y)))return(await Y$.applyEnvironmentVariables(w,{},!0,!1)).config;throw Y}}try{return(await Y$.loadConfig({...w,cwd:w.cwd||i$.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch($){if($ instanceof Error&&($.name==="ConfigNotFoundError"||$.name==="ConfigLoadError"&&fz($)))return(await Y$.applyEnvironmentVariables(w.name||"",w.defaultConfig||{},w.checkEnv!==!1,w.verbose||!1)).config;throw $}}async function Hq(w,$,Y="replace"){let A=new U8;try{let X=await A.loadFromPath(w,$,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function fY(w,$,Y=!1){let A=new J8,X=w.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,Q=[]){let W={...U};for(let[j,B]of Object.entries(U)){let f=[...Q,j],z=[`${X}_${f.join("_").toUpperCase()}`,`${X}_${f.map((K)=>K.toUpperCase()).join("")}`,`${X}_${f.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],G,T;for(let K of z)if(G=i$.env[K],G!==void 0){T=K;break}if(G!==void 0&&T)if(typeof B==="boolean")W[j]=["true","1","yes"].includes(G.toLowerCase());else if(typeof B==="number"){let K=Number(G);if(!Number.isNaN(K))W[j]=K}else if(Array.isArray(B))try{W[j]=JSON.parse(G)}catch{W[j]=G.split(",").map((K)=>K.trim())}else W[j]=G;else if(B&&typeof B==="object"&&!Array.isArray(B))W[j]=J(B,f)}return W}return J($)}function Rq(w){let $=l0(i$.cwd(),w.configDir),Y=l0(i$.cwd(),w.generatedDir),A=l0(Y,"config-types.ts");if(!kW(t9(A)))C7(t9(A),{recursive:!0,mode:511});let X=kW($)?V7($).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${aq}
164
162
  export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
165
- `;$f(A,J,{mode:438})}function sf(w){let $=null,Y=null,A=()=>{if(!Y)Y=QG(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Mw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let W=X[U];return A(),W},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,W){if(!$)$={...X};return $[U]=W,!0}})}function of(w){let $=S2(Cf.cwd(),w?.configDir||"./config");function Y(){if(!If($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=Vf($).filter((Q)=>X.has(gQ(Q))).map((Q)=>({base:Q.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:Q})),W=new Map;for(let{base:Q,file:B}of U){let j=gQ(B).toLowerCase(),z=W.get(Q);if(!z){W.set(Q,B);continue}let G=gQ(z).toLowerCase();if(J.indexOf(j)<J.indexOf(G))W.set(Q,B)}return Array.from(W.entries()).map(([Q,B])=>({base:Q,file:B})).sort((Q,B)=>Q.base.localeCompare(B.base))}function A(){let X=Y(),J=X.map((B)=>B.base),U=J.length?J.map((B)=>`'${B}'`).join(" | "):"string",W=X.length?`{
166
- ${X.map((B)=>{let j=S2($,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
163
+ `;L7(A,J,{mode:438})}function Mq(w){let $=null,Y=null,A=()=>{if(!Y)Y=cz(w).then((J)=>{return $=J,J},(J)=>{let U="defaultConfig"in w?w.defaultConfig:{};if($=U,"verbose"in w&&w.verbose)Mw.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return Y},X="defaultConfig"in w?w.defaultConfig:{};return $=X,A(),new Proxy({},{get(J,U){if($)return $[U];let Q=X[U];return A(),Q},has(J,U){return U in($||X)},ownKeys(){return Object.keys($||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor($||X,U)},set(J,U,Q){if(!$)$={...X};return $[U]=Q,!0}})}function yq(w){let $=Bz(s7.cwd(),w?.configDir||"./config");function Y(){if(!t7($))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=a7($).filter((W)=>X.has(IW(W))).map((W)=>({base:W.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:W})),Q=new Map;for(let{base:W,file:j}of U){let B=IW(j).toLowerCase(),f=Q.get(W);if(!f){Q.set(W,j);continue}let z=IW(f).toLowerCase();if(J.indexOf(B)<J.indexOf(z))Q.set(W,j)}return Array.from(Q.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",Q=X.length?`{
164
+ ${X.map((j)=>{let B=Bz($,j.file).replace(/\\/g,"/");return` '${j.base}': typeof import('${B}').default`}).join(`,
167
165
  `)}
168
166
  }`:"Record<string, any>";return`export type ConfigNames = ${U}
169
- export type ConfigByName = ${W}
167
+ export type ConfigByName = ${Q}
170
168
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
171
169
  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 _T(w,$={}){let Y=N8.cwd();while(Y.includes("storage"))Y=m2(Y,"..");let A=m2(Y,w||"");if($?.relative)return LT(N8.cwd(),A);return A}function M0(){if(J$.env.NODE_ENV==="test"||J$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function vT(){if(J$.env.NODE_ENV==="test"||J$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof J$<"u"){let w=J$.type;if(w==="renderer"||w==="worker")return!1;return!!(J$.versions&&(J$.versions.node||J$.versions.bun))}return!1}class EG{async format(w){let $=await vT(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:i1.pid,hostname:$(),environment:i1.env.NODE_ENV||"development",platform:i1.platform,version:i1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:i1.env.NODE_ENV||i1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class d${name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...E8},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new EG,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...sQ,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...sQ};return{...sQ,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:E8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await xT(this.config.logDirectory,n2.F_OK|n2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await PT(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let Q=this.validateEncryptionConfig()?(await this.encrypt(w)).encrypted:Y$.from(w);try{if(!eX(this.currentLogFile))await aQ(this.currentLogFile,"",{mode:420});if(X=l2(this.currentLogFile,"a",420),DT(X,Q,{flag:"a"}),d2(X),X!==void 0)tQ(X),X=void 0;if((await c1(this.currentLogFile)).size===0){if(await aQ(this.currentLogFile,Q,{flag:"w",mode:420}),(await c1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(J<U-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,z);let G=W*2**J;await new Promise((K)=>setTimeout(K,G)),J++;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(X!==void 0)try{tQ(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(Q){if(J===U-1){let j=Q,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),Q}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();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 v1(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 v1(this.config.logDirectory,`${this.name}.log`);let w=new Date().toISOString().split("T")[0];return v1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,Q])=>Q.createdAt.getTime()-W.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[W]of X.slice(U))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return rQ(16).toString("hex")}generateKey(){return rQ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=rQ(16),A=ZT("aes-256-gcm",$,Y),X=Y$.isBuffer(w)?w:Y$.from(w,"utf8"),J=A.update(X),U=A.final(),W=J.length+U.length,Q=A.getAuthTag(),B=Y$.allocUnsafe(16+W+16);return Y.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),Q.copy(B,16+W),{encrypted:B,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=r2(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(Y$.from(Y$.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let w=await c1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await w8(this.config.logDirectory),J=X.filter((Q)=>Q.startsWith(this.name)&&/\.log\.\d+$/.test(Q)).sort((Q,B)=>{let j=Number.parseInt(Q.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${U}`;if(await c1(Y).catch(()=>null))try{if(await p2(Y,W),$.compress)try{let Q=`${W}.gz`;await this.compressLogFile(W,Q),await $8(W)}catch(Q){console.error("Error compressing rotated file:",Q)}if(J.length===0&&!X.some((Q)=>Q.endsWith(".log.1")))try{let Q=`${Y}.1`;await aQ(Q,"")}catch(Q){console.error("Error creating backup file:",Q)}}catch(Q){console.error(`Error during rotation: ${Q instanceof Error?Q.message:String(Q)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=Y.replace(/\.log$/,`-${X}.log`);if(await c1(Y).catch(()=>null))await p2(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await w8(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice($.maxFiles))await $8(v1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=g2(w),A=hT($),X=r2();await cT(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),eX(this.currentLogFile))try{let w=l2(this.currentLogFile,"r+");d2(w),tQ(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await w8(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await $8(v1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?g.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let w=typeof P.env.NO_COLOR<"u",$=P.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof P.stderr<"u"&&P.stderr.isTTY||typeof P.stdout<"u"&&P.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,W=(K)=>K.replace(this.ANSI_PATTERN,"");if(!this.fancy){let K=[];if(U)K.push($);if(J==="warning")K.push("WARN");else if(J==="error")K.push("ERROR");else if(Y)K.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)K.push(A.replace(/[[\]]/g,""));return K.push(X),K.join(" ")}let Q=P.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${Y} ${X}`;else if(J==="info"||J==="success")B=`${Y} ${A} ${X}`;else B=`${Y} ${A} ${g.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W($).length,G=Math.max(1,Q-2-j-z);return`${B.trim()}${" ".repeat(G)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<$[0].length?String($[0][W]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let W=$[A++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,Q="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),$}supportsHyperlinks(){if(M0())return!1;let w=P.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=P.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(bT($)||$.startsWith("./")||$.startsWith("../"))$=uT($);else return null;return eX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,W;if($ instanceof Error)U=$.message,W=$.stack;else U=this.formatMessage($,Y);let{consoleText:Q,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":lT[w],G=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",K;switch(w){case"debug":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:g.gray(Q),level:w}),console.error(K);break;case"info":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"success":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:g.green(Q),level:w}),console.error(K);break;case"warning":K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.warn(K);break;case"error":if(K=this.formatConsoleMessage({timestamp:X,icon:z,tag:G,message:Q,level:w}),console.error(K),W){let E=W.split(`
173
- `);for(let q of E)if(q.trim()&&!q.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:g.gray(` ${q}`),level:w,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),W)console.error(W)}let j=`${J} ${this.environment}.${w.toUpperCase()}: ${B}
174
- `;if(W)j+=`${W}
175
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress(w,$=""){let Y={update:(W,Q)=>{},finish:(W)=>{},interrupt:(W,Q)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,Q)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),Q!==void 0)this.activeProgressBar.message=Q;if(this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,Q="info")=>{if(!M0()&&P.stdout.isTTY)P.stdout.write(`
176
- `);if(this[Q==="warning"?"warn":Q](W),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":g.blue("◐"),tag:Y,message:`${g.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
177
- `,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":g.green("✓"),tag:j,message:`${J}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug(w,...$){await this.log("debug",w,...$)}async info(w,...$){await this.log("info",w,...$)}async success(w,...$){await this.log("success",w,...$)}async warn(w,...$){await this.log("warning",w,...$)}async error(w,...$){await this.log("error",w,...$)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new d$($,{...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(!eX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return g2(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Y$.isBuffer(w)?w:Y$.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),W=kT("aes-256-gcm",Y,X);W.setAuthTag(J);let Q=W.update(U),B=W.final(),j=Q.length+B.length,z=Y$.allocUnsafe(j);return Q.copy(z,0),B.copy(z,Q.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let W=X.split(`
178
- `),Q=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(Q)}┐`,j=`└${"─".repeat(Q)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:g.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(j),showTimestamp:!1}))}else if(!M0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
179
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(M0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${g.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();P.stdin.removeListener("data",Y);try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!1)}catch{}P.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!0)}catch{}P.stdin.resume(),P.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let Q=/%([sdijfo%])/g,B=0;if(Y=w.replace(Q,(j,z)=>{if(z==="%")return"%";if(B>=$.length)return j;let G=$[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<$.length)Y+=` ${$.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:X}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let Q=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${g.blue("◐")} `;console.error(`${B}${Q} ${g.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
180
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!P.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=g.green("━".repeat(A)),U=g.gray("━".repeat(X)),W=`[${J}${U}]`,Q=`${Y}%`.padStart(4),B=w.message?` ${w.message}`:"",j=this.options.showIcons===!1?"":$||Y===100?g.green("✓"):g.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${Q}${B}`,K=P.stdout.columns||80,E=" ".repeat(Math.max(0,K-G.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${G}${E}`,P.stdout.write(w.lastRenderedLine),$)P.stdout.write(`
181
- `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await w8(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=v1(this.config.logDirectory,A);if(w.before)try{if((await c1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await $8(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}var rE,tE=(w)=>w,sE=(w,$)=>{for(var Y in $)rE(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:aE.bind($,Y)})},oE=(w,$)=>()=>(w&&($=w(w=0)),$),s2,WG,m1,hY,BG,ef,wT,k2,A8,$W,D0,o,$T,h2,YT,D2,AT,XT,dQ,JT,x2,P2,lQ,UT,QT,WT,BT,X8,jG,jT,x0,zT,GT,b2,J8,YW,R0,v,KT,u2,FT,c2,qT,NT,nQ,ET,v2,i2,fT,pQ,TT,HT,RT,MT,IT,U8,zG,VT,CT="0.15.6",Yw,F8,ZY,AW,XW,q8,JW,UW,kY,QW,WW,I$,GG,KG,Mw,U$,FG,qG,yT,ST,NG,E8,GO,y0,g,IO,iT,VO,mT,CO,yO,t2,OO,gT,dT,LO,a2,_O,SO,ZO,kO,hO,sQ,lT,DO;var NW=t(()=>{rE=Object.defineProperty;s2={};sE(s2,{withErrorRecovery:()=>YG,tryLoadConfig:()=>tf,loadConfigWithResult:()=>pf,loadConfig:()=>QG,isRetryableError:()=>vf,isConfigNotFoundError:()=>cf,isBunfigError:()=>AG,globalPerformanceMonitor:()=>hY,globalCache:()=>m1,getEnvOrDefault:()=>mf,generateConfigTypes:()=>af,defaultGeneratedDir:()=>qG,defaultConfigDir:()=>FG,deepMergeWithArrayStrategy:()=>KW,deepMerge:()=>XG,createLibraryConfig:()=>sf,config:()=>rf,bunfigPlugin:()=>of,applyEnvVarsToConfig:()=>_Y,TypeGenerationError:()=>UW,SchemaValidationError:()=>kY,PluginError:()=>WW,PerformanceMonitor:()=>jW,FileSystemError:()=>JW,ErrorFactory:()=>I$,EnvVarError:()=>q8,EnvProcessor:()=>f8,ConfigValidator:()=>FW,ConfigValidationError:()=>AW,ConfigNotFoundError:()=>F8,ConfigMergeError:()=>XW,ConfigLoader:()=>qW,ConfigLoadError:()=>ZY,ConfigFileLoader:()=>T8,ConfigCache:()=>BW,CacheUtils:()=>BG,BunfigError:()=>Yw,BrowserConfigError:()=>QW,ArrayMergeStrategies:()=>GG});yT=oE(async()=>{WG=import.meta.require,m1=new BW,hY=new jW,BG={createKey:yf,isEquivalent:Of,estimateMemoryUsage:Lf},ef=B8(eQ.cwd(),"config"),wT=B8(eQ.cwd(),"src/generated"),k2=W8.env.CLARITY_LOG_DIR||Xf(Zf(),"logs"),A8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:k2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},$W=await kf(),D0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},o=D0,$T=D0.red,h2=D0.green,YT=D0.yellow,D2=D0.blue,AT=D0.magenta,XT=D0.cyan,dQ=D0.white,JT=D0.gray,x2=D0.bgRed,P2=D0.bgYellow,lQ=D0.bold,UT=D0.dim,QT=D0.italic,WT=D0.underline,BT=D0.reset,X8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},jG={debug:"\uD83D\uDD0D",info:D2("ℹ"),success:h2("✓"),warning:P2(dQ(lQ(" WARN "))),error:x2(dQ(lQ(" ERROR ")))},jT=new z8("stacks"),x0=new z8("bunfig",{showTags:!0}),zT=n0(SY.cwd(),"config"),GT=n0(SY.cwd(),"src/generated"),b2=Q8.env.CLARITY_LOG_DIR||Yf(Pf(),"logs"),J8={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:b2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},YW=await bf(),R0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},v=R0,KT=R0.red,u2=R0.green,FT=R0.yellow,c2=R0.blue,qT=R0.magenta,NT=R0.cyan,nQ=R0.white,ET=R0.gray,v2=R0.bgRed,i2=R0.bgYellow,fT=R0.bgGray,pQ=R0.bold,TT=R0.dim,HT=R0.italic,RT=R0.underline,MT=R0.strikethrough,IT=R0.reset,U8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},zG={debug:"\uD83D\uDD0D",info:c2("ℹ"),success:u2("✓"),warning:i2(nQ(pQ(" WARN "))),error:v2(nQ(pQ(" ERROR ")))},VT=new K8("stacks"),Yw=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},F8=class extends Yw{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},ZY=class extends Yw{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},AW=class extends Yw{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},XW=class extends Yw{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},q8=class extends Yw{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},JW=class extends Yw{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},UW=class extends Yw{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},kY=class extends Yw{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},QW=class extends Yw{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},WW=class extends Yw{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},I$={configNotFound(w,$,Y){return new F8(w,$,Y)},configLoad(w,$,Y){return new ZY(w,$,Y)},configValidation(w,$,Y){return new AW(w,$,Y)},configMerge(w,$,Y,A){return new XW(w,$,Y,A)},envVar(w,$,Y,A){return new q8(w,$,Y,A)},fileSystem(w,$,Y){return new JW(w,$,Y)},typeGeneration(w,$,Y){return new UW(w,$,Y)},schemaValidation(w,$,Y){return new kY(w,$,Y)},browserConfig(w,$,Y,A){return new QW(w,$,Y,A)},plugin(w,$,Y){return new WW(w,$,Y)}},GG={replace:"replace",concat:"concat",smart:"smart"},KG=/^https?:\/\//,Mw=new K8("bunfig",{showTags:!0}),U$=new qW,FG=p0(g$.cwd(),"config"),qG=p0(g$.cwd(),"src/generated")});ST=N8.env.CLARITY_LOG_DIR||OT(_T(),"logs"),NG={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:ST,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},E8={...NG},GO=(async()=>{try{let{loadConfig:w}=await yT().then(()=>s2),$=await w({name:"clarity",alias:"logging",defaultConfig:NG,cwd:N8.cwd()});if($)Object.assign(E8,$)}catch{}return E8})();y0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},g=y0,IO=y0.red,iT=y0.green,VO=y0.yellow,mT=y0.blue,CO=y0.magenta,yO=y0.cyan,t2=y0.white,OO=y0.gray,gT=y0.bgRed,dT=y0.bgYellow,LO=y0.bgGray,a2=y0.bold,_O=y0.dim,SO=y0.italic,ZO=y0.underline,kO=y0.strikethrough,hO=y0.reset,sQ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},lT={debug:"\uD83D\uDD0D",info:mT("ℹ"),success:iT("✓"),warning:dT(t2(a2(" WARN "))),error:gT(t2(a2(" ERROR ")))};DO=new d$("stacks")});var d1={};fB(d1,{shouldReusePort:()=>g1,safeStringify:()=>Iw,safeDeleteFile:()=>TW,resolvePathRewrite:()=>fW,redactSensitive:()=>R8,isValidRootCA:()=>EW,isSingleProxyOptions:()=>xY,isSingleProxyConfig:()=>oT,isProcessElevated:()=>DY,isMultiProxyOptions:()=>l$,isMultiProxyConfig:()=>HG,getSudoPassword:()=>V$,getPrimaryDomain:()=>M8,extractHostname:()=>sT,execSudoSync:()=>Q$,debugLog:()=>F,authorizeSystemAccess:()=>pT});import{execSync as H8}from"node:child_process";import*as TG from"node:fs/promises";function V$(){return process.env.SUDO_PASSWORD}function DY(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function pT(w={}){if(process.platform==="win32")return!0;if(DY()||!!V$())return!0;let $=w.exec??H8;try{return $("sudo -n true",{stdio:"ignore"}),!0}catch{if(!w.interactive)return!1}try{return $("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function Q$(w){if(DY())return H8(w,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let $=V$(),Y=w.replace(/'/g,"'\\''");if($)return H8(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return H8(`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 F(w,$,Y){if(Y)nT.debug(`[rpx:${w}] ${$}`)}function g1(){let w=process.env.RPX_REUSE_PORT;return w==="1"||w==="true"}function aT(w){let $=w.toLowerCase();return rT.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function R8(w){if(Array.isArray(w))return w.map((Y)=>R8(Y));if(typeof w==="string")return tT.test(w)?fG:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(aT(Y)){$[Y]=fG;continue}$[Y]=R8(A)}return $}function Iw(w,$){return JSON.stringify(R8(w),null,$)}function sT(w){if(l$(w))return w.proxies.map(($)=>{let Y=$.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(xY(w)){let $=w.to||"stacks.localhost";return[$.startsWith("http")?new URL($).hostname:$]}return["stacks.localhost"]}function EW(w){return typeof w==="object"&&w!==null&&"certificate"in w&&"privateKey"in w&&typeof w.certificate==="string"&&typeof w.privateKey==="string"}function M8(w){if(!w)return"stacks.localhost";if(l$(w)&&w.proxies.length>0)return w.proxies[0].to||"stacks.localhost";if(xY(w))return w.to||"stacks.localhost";return"stacks.localhost"}function HG(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}function l$(w){return"proxies"in w&&Array.isArray(w.proxies)}function xY(w){return"to"in w&&typeof w.to==="string"}function oT(w){return!!(w&&("to"in w)&&!("proxies"in w))}function fW(w,$){if(!$||$.length===0)return null;for(let Y of $)if(w===Y.from||w.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?w.slice(Y.from.length)||"/":w;return{targetHost:A,targetPath:X}}return null}async function TW(w,$){try{await TG.unlink(w),F("certificates",`Successfully deleted: ${w}`,$)}catch(Y){if(Y.code!=="ENOENT")F("certificates",`Warning: Could not delete ${w}: ${Y}`,$)}}var nT,fG="[redacted]",rT,tT;var X0=t(()=>{NW();nT=new d$("rpx",{showTags:!1});rT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),tT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as I8}from"node:child_process";import{homedir as eT}from"node:os";import{join as wH}from"node:path";function V8(){return wH(eT(),"Library/Keychains/login.keychain-db")}function RW(){return[y$,V8()]}function RG(w,$=HW){let Y=I8(`security find-certificate -a -c "${$}" -Z "${w}" 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 MW(w){if(process.platform!=="darwin")return;let $=m$(w.caPath);if(!$)return;let Y=w.commonName??HW,A=w.keychains??RW();for(let X of A)for(let J of RG(X,Y)){if(J===$)continue;try{if(X.startsWith("/Library"))Q$(`security delete-certificate -Z ${J} "${X}"`);else I8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});F("ssl",`Removed stale Root CA ${J} from ${X}`,w.verbose)}catch{}}}function IW(w,$,Y){if(process.platform!=="darwin")return C8(w,Y);try{let X=I8(`security verify-cert -c "${w}" -s "${$}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return F("ssl",`verify-cert ${$}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function C8(w,$){let Y=m$(w);if(!Y)return!1;for(let A of RW())try{let X=I8(`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 F("ssl",`Root CA fingerprint found in ${A}`,$?.verbose),!0}}catch{}return!1}var C$="-d -r trustRoot -p ssl -p basic",y$="/Library/Keychains/System.keychain",HW="rpx.localhost";var VW=t(()=>{dX();X0()});import{execSync as CW}from"node:child_process";import G0 from"node:fs/promises";import*as yW from"node:os";import{homedir as l1}from"node:os";import*as VG from"node:path";import{join as K0}from"node:path";import*as O$ from"node:process";function OW(w,$){return[...new Set(w.filter(Boolean))].map((Y)=>({serverName:Y,cert:$.cert,key:$.key}))}function LW(w,$,Y){let A=K0(l1(),".stacks","ssl"),X=[...new Set([$,...w,"rpx.localhost"])];return{https:{certPath:y8,keyPath:K0(A,"rpx.localhost.key"),caCertPath:K0(A,"rpx.localhost.ca.crt"),commonName:$},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function CG(w){return{caCertPath:K0(w,YH),caKeyPath:K0(w,AH)}}async function XH(w,$){try{let[Y,A]=await Promise.all([G0.readFile(w.caCertPath,"utf8"),G0.readFile(w.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return F("ssl",`Root CA files at ${w.caCertPath} look malformed, will regenerate`,$),null;return{certificate:Y,privateKey:A}}catch(Y){return F("ssl",`No existing Root CA at ${w.caCertPath} (${Y.code||Y}), will create one`,$),null}}function MG(w){let $=new Set;$.add(w);let Y=w.split(".");if(Y.length>=3){let A=Y[Y.length-1],X=Y[Y.length-2],J=new Set(["co","com","org","net","ac","gov","edu"]);if(!(Y.length===3&&A.length===2&&J.has(X)))$.add(`*.${Y.slice(1).join(".")}`)}return Array.from($)}function yG(w){let Y=M8(w).replace(/\*/g,"wildcard"),A=K0(l1(),".stacks","ssl"),X=A;if(typeof w?.https==="object")return X=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:A,{caCertPath:w.https.caCertPath||K0(X,`${Y}.ca.crt`),certPath:w.https.certPath||K0(X,`${Y}.crt`),keyPath:w.https.keyPath||K0(X,`${Y}.key`)};return{caCertPath:K0(X,`${Y}.ca.crt`),certPath:K0(X,`${Y}.crt`),keyPath:K0(X,`${Y}.key`)}}function IG(w){let $=new Set;if(l$(w))w.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";MG(A).forEach((X)=>$.add(X))});else if(xY(w)){let Y=w.to||"rpx.localhost";MG(Y).forEach((A)=>$.add(A))}else $.add("rpx.localhost");return $.add("localhost"),$.add("*.localhost"),$}async function n1(w){if(L$&&!w.forceRegenerate){F("ssl","Using cached SSL configuration",w.verbose);return}O8();let $=l$(w)?w.proxies.map((j)=>j.to):[w.to];F("ssl",`Generating certificate for domains: ${$.join(", ")}`,w.verbose);let Y=PY(w,w.verbose),A=Y.basePath||K0(l1(),".stacks","ssl");await G0.mkdir(A,{recursive:!0});let X=CG(A),J=await XH(X,w.verbose),U=!1;if(!J){if(w.verbose)H.info("Generating Root CA certificate (one-time)...");J=await VQ(Y);try{await Promise.all([G0.writeFile(X.caCertPath,J.certificate),G0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,F("ssl",`Persisted Root CA at ${X.caCertPath}`,w.verbose)}catch(j){throw F("ssl",`Error saving Root CA files: ${j}`,w.verbose),Error(`Failed to save Root CA files: ${j}`)}}else F("ssl",`Reusing existing Root CA from ${X.caCertPath}`,w.verbose);if(w.verbose)H.info(`Generating host certificate for: ${$.join(", ")}`);let W=await CQ({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([G0.writeFile(Y.certPath,W.certificate),G0.writeFile(Y.keyPath,W.privateKey),G0.writeFile(Y.caCertPath,J.certificate)]),F("ssl","Certificate files saved successfully",w.verbose)}catch(j){throw F("ssl",`Error saving certificate files: ${j}`,w.verbose),Error(`Failed to save certificate files: ${j}`)}if(U?!1:await LG(X.caCertPath,{verbose:w.verbose,regenerateUntrustedCerts:!0})){if(F("ssl","Root CA already trusted, skipping trust store update",w.verbose),w.verbose)H.success("Root CA is already trusted in system trust store");if(L$={key:W.privateKey,cert:W.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);return}if(w.verbose)H.info("Adding certificate to system trust store (may require sudo permission)...");let B=!1;if(O$.platform==="darwin")try{MW({caPath:X.caCertPath,verbose:w.verbose});let j=V8();try{CW(`security add-trusted-cert ${C$} -k "${j}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(Q$(`security add-trusted-cert ${C$} -k ${y$} "${X.caCertPath}"`),w.verbose)H.success("Successfully added Root CA to system trust store");B=!0;let z=K0(A,"trust-rpx-cert.sh"),G=`#!/bin/bash
170
+ `}return{name:"bunfig-plugin",setup(X){X.onResolve({filter:/^virtual:bunfig-types$/},(J)=>{return{path:J.path,namespace:"bunfig-virtual"}}),X.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function wN(w,$={}){let Y=A8.cwd();while(Y.includes("storage"))Y=Mz(Y,"..");let A=Mz(Y,w||"");if($?.relative)return eq(A8.cwd(),A);return A}function M0(){if($$.env.NODE_ENV==="test"||$$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function fN(){if($$.env.NODE_ENV==="test"||$$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $$<"u"){let w=$$.type;if(w==="renderer"||w==="worker")return!1;return!!($$.versions&&($$.versions.node||$$.versions.bun))}return!1}class sz{async format(w){let $=await fN(),Y=await this.getMetadata($);return JSON.stringify({timestamp:w.timestamp.toISOString(),level:w.level,name:w.name,message:w.message,metadata:Y})}async getMetadata(w){if(w){let{hostname:$}=await import("os");return{pid:Z1.pid,hostname:$(),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 FY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(w,$={}){this.name=w,this.config={...X8},this.options=this.normalizeOptions($),this.formatter=this.options.formatter||new sz,this.enabled=$.enabled??!0,this.fancy=$.fancy??!0,this.tagFormat=$.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=$.timestampPosition??"right",this.environment=$.environment??P.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig($);let Y={...$},A=$.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(w){if(!this.fingersCrossedConfig)return!1;let $={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return $[w]>=$[Y]}initializeFingersCrossedConfig(w){if(!w.fingersCrossedEnabled&&w.fingersCrossed)return{...DW,...w.fingersCrossed};if(!w.fingersCrossedEnabled)return null;if(!w.fingersCrossed)return{...DW};return{...DW,...w.fingersCrossed}}normalizeOptions(w){let $={format:"json",level:"info",logDirectory:X8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...$,...Object.fromEntries(Object.entries(w).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=$.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile(w){let Y=(async()=>{let X,J=0,U=3,Q=1000;while(J<U)try{try{try{await UN(this.config.logDirectory,Vz.F_OK|Vz.W_OK)}catch(j){if(j instanceof Error&&"code"in j)if(j.code==="ENOENT")await WN(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(w)).encrypted:ow.from(w);try{if(!vX(this.currentLogFile))await _W(this.currentLogFile,"",{mode:420});if(X=Cz(this.currentLogFile,"a",420),JN(X,W,{flag:"a"}),Iz(X),X!==void 0)hW(X),X=void 0;if((await D1(this.currentLogFile)).size===0){if(await _W(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 B=j;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(J<U-1){let f=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${J+1}/${U}:`,f);let z=Q*2**J;await new Promise((G)=>setTimeout(G,z)),J++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(X!==void 0)try{hW(X)}catch(j){console.error("Debug: [writeToFile] Error closing file descriptor:",j)}}}catch(W){if(J===U-1){let B=W,f=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",f),W}J++;let j=Q*2**(J-1);await new Promise((B)=>setTimeout(B,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 w=new Date().toISOString().split("T")[0];return k1(this.config.logDirectory,`${this.name}-${w}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let w=this.config.rotation,$;switch(w.frequency){case"daily":$=86400000;break;case"weekly":$=604800000;break;case"monthly":$=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},$)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let Y=typeof $.interval==="number"?$.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,Q],[,W])=>W.createdAt.getTime()-Q.createdAt.getTime()),J=typeof $.maxKeys==="number"?$.maxKeys:1,U=Math.max(1,J);if(X.length>U)for(let[Q]of X.slice(U))this.encryptionKeys.delete(Q),this.keys.delete(Q)}generateKeyId(){return OW(16).toString("hex")}generateKey(){return OW(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let w=this.keys.get(this.currentKeyId);if(!w)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:w,id:this.currentKeyId}}encrypt(w){let{key:$}=this.getCurrentKey(),Y=OW(16),A=YN("aes-256-gcm",$,Y),X=ow.isBuffer(w)?w:ow.from(w,"utf8"),J=A.update(X),U=A.final(),Q=J.length+U.length,W=A.getAuthTag(),j=ow.allocUnsafe(16+Q+16);return Y.copy(j,0),J.copy(j,16),U.copy(j,16+J.length),W.copy(j,16+Q),{encrypted:j,iv:Y}}async compressData(w){return new Promise(($,Y)=>{let A=Sz(),X=[];A.on("data",(J)=>X.push(J)),A.on("end",()=>$(ow.from(ow.concat(X)))),A.on("error",Y),A.write(w),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let w={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let $=this.config.rotation.encrypt;return{...w,...$}}return w}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let w=await D1(this.currentLogFile).catch(()=>null);if(!w)return;let $=this.config.rotation;if(typeof $==="boolean")return;if($.maxSize&&w.size>=$.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await cX(this.config.logDirectory),J=X.filter((W)=>W.startsWith(this.name)&&/\.log\.\d+$/.test(W)).sort((W,j)=>{let B=Number.parseInt(W.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(j.match(/\.log\.(\d+)$/)?.[1]||"0")-B}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,Q=`${Y}.${U}`;if(await D1(Y).catch(()=>null))try{if(await Lz(Y,Q),$.compress)try{let W=`${Q}.gz`;await this.compressLogFile(Q,W),await mX(Q)}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 D1(Y).catch(()=>null))await Lz(Y,J)}if(this.currentLogFile=A,$.maxFiles){let J=(await cX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,Q)=>Q.localeCompare(U));for(let U of J.slice($.maxFiles))await mX(k1(this.config.logDirectory,U))}}}async compressLogFile(w,$){let Y=yz(w),A=XN($),X=Sz();await BN(Y,X,A)}async handleFingersCrossedBuffer(w,$){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(w)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile($);console.log($)}}shouldLog(w){if(!this.enabled)return!1;let $={debug:0,info:1,success:2,warning:3,error:4};return $[w]>=$[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((w)=>{if(w instanceof Promise)return w.catch(($)=>{console.error("Error in pending write operation:",$)});return Promise.resolve()})),vX(this.currentLogFile))try{let w=Cz(this.currentLogFile,"r+");Iz(w),hW(w)}catch(w){console.error(`Error flushing file: ${w}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let w of this.pendingOperations)if(typeof w.cancel==="function")w.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(w){console.error("Error waiting for pending operations:",w)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await cX(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of $)try{await mX(k1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch(w){console.error("Error cleaning up temporary files:",w)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(w){if(!w)return"";return`${this.tagFormat.prefix}${w}${this.tagFormat.suffix}`}formatFileTimestamp(w){return`[${w.toISOString()}]`}formatConsoleTimestamp(w){return this.shouldStyleConsole()?g.gray(w.toLocaleTimeString()):w.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let w=typeof P.env.NO_COLOR<"u",$=P.env.FORCE_COLOR==="0";if(w||$)return!1;return!!(typeof P.stderr<"u"&&P.stderr.isTTY||typeof P.stdout<"u"&&P.stdout.isTTY)}formatConsoleMessage(w){let{timestamp:$,icon:Y="",tag:A="",message:X,level:J,showTimestamp:U=!0}=w,Q=(G)=>G.replace(this.ANSI_PATTERN,"");if(!this.fancy){let G=[];if(U)G.push($);if(J==="warning")G.push("WARN");else if(J==="error")G.push("ERROR");else if(Y)G.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)G.push(A.replace(/[[\]]/g,""));return G.push(X),G.join(" ")}let W=P.stdout.columns||120,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 B=Q(j).trim().length,f=Q($).length,z=Math.max(1,W-2-B-f);return`${j.trim()}${" ".repeat(z)}${$}`}formatMessage(w,$){if($.length===1&&Array.isArray($[0]))return w.replace(/\{(\d+)\}/g,(J,U)=>{let Q=Number.parseInt(U,10);return Q<$[0].length?String($[0][Q]):J});let Y=/%([sdijfo%])/g,A=0,X=w.replace(Y,(J,U)=>{if(U==="%")return"%";if(A>=$.length)return J;let Q=$[A++];switch(U){case"s":return String(Q);case"d":case"i":return Number(Q).toString();case"j":case"o":return JSON.stringify(Q,null,2);default:return J}});if(A<$.length)X+=` ${$.slice(A).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown(w){if(!w)return w;let $=w;return $=$.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,X)=>{let J=g.underline(g.blue(A)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let Q=`file://${encodeURI(U)}`,W="\x1B]8;;",j="\x1B\\";return`\x1B]8;;${Q}\x1B\\${J}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${X}\x1B\\${J}\x1B]8;;\x1B\\`;return J}),$=$.replace(/`([^`]+)`/g,(Y,A)=>g.bgGray(A)),$=$.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>g.bold(A)),$=$.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>g.italic(A)),$=$.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>g.italic(A)),$=$.replace(/~([^~]+)~/g,(Y,A)=>g.strikethrough(A)),$}supportsHyperlinks(){if(M0())return!1;let w=P.env;if(!w)return!1;if(w.TERM_PROGRAM==="iTerm.app"||w.TERM_PROGRAM==="vscode"||w.TERM_PROGRAM==="WezTerm")return!0;if(w.WT_SESSION)return!0;if(w.TERM==="xterm-kitty")return!0;let $=w.VTE_VERSION?Number.parseInt(w.VTE_VERSION,10):0;if(!Number.isNaN($)&&$>=5000)return!0;return!1}toAbsoluteFilePath(w){try{let $=w;if($.startsWith("file://"))$=$.replace(/^file:\/\//,"");if($.startsWith("~")){let Y=P.env.HOME||"";if(Y)$=$.replace(/^~(?=$|\/)/,Y)}if(QN($)||$.startsWith("./")||$.startsWith("../"))$=jN($);else return null;return vX($)?$:null}catch{return null}}buildOutputTexts(w){let $=this.shouldStyleConsole()?this.formatMarkdown(w):w,Y=w.replace(this.ANSI_PATTERN,"");return{consoleText:$,fileText:Y}}async log(w,$,...Y){if(!this.shouldLog(w))return;let A=new Date,X=this.formatConsoleTimestamp(A),J=this.formatFileTimestamp(A),U,Q;if($ instanceof Error)U=$.message,Q=$.stack;else U=this.formatMessage($,Y);let{consoleText:W,fileText:j}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let f=this.options.showIcons===!1?"":FN[w],z=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",G;switch(w){case"debug":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:g.gray(W),level:w}),console.error(G);break;case"info":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"success":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:g.green(W),level:w}),console.error(G);break;case"warning":G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.warn(G);break;case"error":if(G=this.formatConsoleMessage({timestamp:X,icon:f,tag:z,message:W,level:w}),console.error(G),Q){let T=Q.split(`
171
+ `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:g.gray(` ${K}`),level:w,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${J} ${this.environment}.${w.toUpperCase()}: ${U}`),Q)console.error(Q)}let B=`${J} ${this.environment}.${w.toUpperCase()}: ${j}
172
+ `;if(Q)B+=`${Q}
173
+ `;if(B=B.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(B)}progress(w,$=""){let Y={update:(Q,W)=>{},finish:(Q)=>{},interrupt:(Q,W)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,w||1),current:0,message:$||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(Q,W)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,Q),this.activeProgressBar.total),W!==void 0)this.activeProgressBar.message=W;if(this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(Q)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,Q)},interrupt:(Q,W="info")=>{if(!M0()&&P.stdout.isTTY)P.stdout.write(`
174
+ `);if(this[W==="warning"?"warn":W](Q),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&P.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time(w){let $=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":g.blue("◐"),tag:Y,message:`${g.cyan(w)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),X=Math.round(A-$),J=`${w} completed in ${X}ms`,U=new Date,Q=this.formatConsoleTimestamp(U),j=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(Y)j+=` ${JSON.stringify(Y)}`;if(j+=`
175
+ `,j=j.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?g.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:Q,icon:this.options.showIcons===!1?"":g.green("✓"),tag:B,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 w=this.config.rotation,{encrypt:$}=w;return!!$}async only(w){if(!this.enabled)return;return await w()}isEnabled(){return this.enabled}setEnabled(w){this.enabled=w}extend(w){let $=`${this.name}:${w}`,Y=new FY($,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!vX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return yz(this.currentLogFile,{encoding:"utf8"})}async decrypt(w){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let $=this.config.rotation;if(!$.encrypt||typeof $.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=ow.isBuffer(w)?w:ow.from(w,"base64"),X=A.subarray(0,16),J=A.subarray(A.length-16),U=A.subarray(16,A.length-16),Q=AN("aes-256-gcm",Y,X);Q.setAuthTag(J);let W=Q.update(U),j=Q.final(),B=W.length+j.length,f=ow.allocUnsafe(B);return W.copy(f,0),j.copy(f,W.length),f.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey(w,$){this.currentKeyId=w,this.keys.set(w,$)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box(w){if(!this.enabled)return;let $=new Date,Y=this.formatConsoleTimestamp($),A=this.formatFileTimestamp($),{consoleText:X,fileText:J}=this.buildOutputTexts(w);if(this.shouldStyleConsole()){let Q=X.split(`
176
+ `),W=Math.max(...Q.map((z)=>z.length))+2,j=`┌${"─".repeat(W)}┐`,B=`└${"─".repeat(W)}┘`,f=Q.map((z)=>{return this.formatConsoleMessage({timestamp:Y,message:g.cyan(z),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(j),showTimestamp:!1})),f.forEach((z)=>console.error(z)),console.error(this.formatConsoleMessage({timestamp:Y,message:g.cyan(B),showTimestamp:!1}))}else if(!M0())console.error(`${A} ${this.environment}.INFO: [BOX] ${J}`);let U=`${A} ${this.environment}.INFO: [BOX] ${J}
177
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt(w){if(M0())return Promise.resolve(!0);return new Promise(($)=>{console.error(`${g.cyan("?")} ${w} (y/n) `);let Y=(A)=>{let X=A.toString().trim().toLowerCase();P.stdin.removeListener("data",Y);try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!1)}catch{}P.stdin.pause(),console.error(""),$(X==="y"||X==="yes")};try{if(typeof P.stdin.setRawMode==="function")P.stdin.setRawMode(!0)}catch{}P.stdin.resume(),P.stdin.once("data",Y)})}setFancy(w){this.fancy=w}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start(w,...$){if(!this.enabled)return;let Y=w;if($&&$.length>0){let W=/%([sdijfo%])/g,j=0;if(Y=w.replace(W,(B,f)=>{if(f==="%")return"%";if(j>=$.length)return B;let z=$[j++];switch(f){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 B}}),j<$.length)Y+=` ${$.slice(j).map((B)=>typeof B==="object"?JSON.stringify(B,null,2):String(B)).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 Q=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
178
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(Q)}renderProgressBar(w,$=!1){if(!this.enabled||!this.shouldStyleConsole()||!P.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round(w.current/w.total*100))),A=Math.round(w.barLength*Y/100),X=w.barLength-A,J=g.green("━".repeat(A)),U=g.gray("━".repeat(X)),Q=`[${J}${U}]`,W=`${Y}%`.padStart(4),j=w.message?` ${w.message}`:"",B=this.options.showIcons===!1?"":$||Y===100?g.green("✓"):g.blue("▶"),f=this.options.showTags!==!1&&this.name?` ${g.gray(this.formatTag(this.name))}`:"",z=`\r${B}${f} ${Q} ${W}${j}`,G=P.stdout.columns||80,T=" ".repeat(Math.max(0,G-z.replace(this.ANSI_PATTERN,"").length));if(w.lastRenderedLine=`${z}${T}`,P.stdout.write(w.lastRenderedLine),$)P.stdout.write(`
179
+ `)}finishProgressBar(w,$){if(!this.enabled||!this.fancy||M0()||!P.stdout.isTTY){this.activeProgressBar=null;return}if(w.current<w.total)w.current=w.total;if($)w.message=$;this.renderProgressBar(w,!0),this.activeProgressBar=null}async clear(w={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let $=await cX(this.config.logDirectory),Y=[];for(let A of $){if(!(w.name?new RegExp(w.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let J=k1(this.config.logDirectory,A);if(w.before)try{if((await D1(J)).mtime>=w.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}Y.push(J)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await mX(A),console.warn(`Deleted log file: ${A}`)}catch(X){console.error(`Failed to delete log file ${A}:`,X)}console.warn("Log clearing process finished.")}catch($){console.error("Error during log clearing process:",$)}}}var H7,R7=(w)=>w,y7=(w,$)=>{for(var Y in $)H7(w,Y,{get:$[Y],enumerable:!0,configurable:!0,set:M7.bind($,Y)})},I7=(w,$)=>()=>(w&&($=w(w=0)),$),_z,mz,x1,KY,gz,Iq,Cq,zz,dX,PW,Z0,e,Vq,Gz,Lq,Ez,Sq,Oq,CW,hq,Kz,Fz,VW,_q,Dq,kq,Zq,nX,dz,xq,x0,Pq,iq,Tz,lX,iW,R0,v,bq,qz,uq,Nz,vq,cq,LW,mq,Hz,Rz,gq,SW,dq,nq,lq,pq,rq,pX,nz,tq,aq="0.15.6",ww,$8,GY,bW,uW,Y8,vW,cW,EY,mW,gW,F$,lz,pz,Mw,Y$,rz,tz,sq,$N,az,X8,B3,C0,g,R3,zN,M3,GN,y3,I3,Oz,C3,EN,KN,V3,hz,L3,S3,O3,h3,_3,DW,FN,D3;var oz=a(()=>{H7=Object.defineProperty;_z={};y7(_z,{withErrorRecovery:()=>Pz,tryLoadConfig:()=>Hq,loadConfigWithResult:()=>qq,loadConfig:()=>cz,isRetryableError:()=>zq,isConfigNotFoundError:()=>fq,isBunfigError:()=>iz,globalPerformanceMonitor:()=>KY,globalCache:()=>x1,getEnvOrDefault:()=>Gq,generateConfigTypes:()=>Rq,defaultGeneratedDir:()=>tz,defaultConfigDir:()=>rz,deepMergeWithArrayStrategy:()=>rW,deepMerge:()=>bz,createLibraryConfig:()=>Mq,config:()=>Nq,bunfigPlugin:()=>yq,applyEnvVarsToConfig:()=>fY,TypeGenerationError:()=>cW,SchemaValidationError:()=>EY,PluginError:()=>gW,PerformanceMonitor:()=>nW,FileSystemError:()=>vW,ErrorFactory:()=>F$,EnvVarError:()=>Y8,EnvProcessor:()=>J8,ConfigValidator:()=>tW,ConfigValidationError:()=>bW,ConfigNotFoundError:()=>$8,ConfigMergeError:()=>uW,ConfigLoader:()=>aW,ConfigLoadError:()=>GY,ConfigFileLoader:()=>U8,ConfigCache:()=>dW,CacheUtils:()=>gz,BunfigError:()=>ww,BrowserConfigError:()=>mW,ArrayMergeStrategies:()=>lz});sq=I7(async()=>{mz=import.meta.require,x1=new dW,KY=new nW,gz={createKey:o7,isEquivalent:e7,estimateMemoryUsage:wq},Iq=aX(ZW.cwd(),"config"),Cq=aX(ZW.cwd(),"src/generated"),zz=tX.env.CLARITY_LOG_DIR||h7(Aq(),"logs"),dX={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},PW=await Xq(),Z0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,reset:"\x1B[0m"},e=Z0,Vq=Z0.red,Gz=Z0.green,Lq=Z0.yellow,Ez=Z0.blue,Sq=Z0.magenta,Oq=Z0.cyan,CW=Z0.white,hq=Z0.gray,Kz=Z0.bgRed,Fz=Z0.bgYellow,VW=Z0.bold,_q=Z0.dim,Dq=Z0.italic,kq=Z0.underline,Zq=Z0.reset,nX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},dz={debug:"\uD83D\uDD0D",info:Ez("ℹ"),success:Gz("✓"),warning:Fz(CW(VW(" WARN "))),error:Kz(CW(VW(" ERROR ")))},xq=new oX("stacks"),x0=new oX("bunfig",{showTags:!0}),Pq=n0(zY.cwd(),"config"),iq=n0(zY.cwd(),"src/generated"),Tz=rX.env.CLARITY_LOG_DIR||S7(Qq(),"logs"),lX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Tz,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},iW=await jq(),R0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},v=R0,bq=R0.red,qz=R0.green,uq=R0.yellow,Nz=R0.blue,vq=R0.magenta,cq=R0.cyan,LW=R0.white,mq=R0.gray,Hz=R0.bgRed,Rz=R0.bgYellow,gq=R0.bgGray,SW=R0.bold,dq=R0.dim,nq=R0.italic,lq=R0.underline,pq=R0.strikethrough,rq=R0.reset,pX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},nz={debug:"\uD83D\uDD0D",info:Nz("ℹ"),success:qz("✓"),warning:Rz(LW(SW(" WARN "))),error:Hz(LW(SW(" ERROR ")))},tq=new w8("stacks"),ww=class extends Error{timestamp;context;constructor($,Y={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},$8=class extends ww{code="CONFIG_NOT_FOUND";constructor($,Y,A){let X=A?` or alias "${A}"`:"";super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:Y,searchPathCount:Y.length})}},GY=class extends ww{code="CONFIG_LOAD_ERROR";constructor($,Y,A){super(`Failed to load configuration from "${$}": ${Y.message}`,{configPath:$,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},bW=class extends ww{code="CONFIG_VALIDATION_ERROR";constructor($,Y,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},uW=class extends ww{code="CONFIG_MERGE_ERROR";constructor($,Y,A,X){super(`Failed to merge configuration from "${$}" with "${Y}": ${A.message}`,{sourcePath:$,targetPath:Y,configName:X,originalError:A.name,originalMessage:A.message});this.cause=A}},Y8=class extends ww{code="ENV_VAR_ERROR";constructor($,Y,A,X){super(`Failed to parse environment variable "${$}" with value "${Y}" as ${A}`,{envKey:$,envValue:Y,expectedType:A,configName:X})}},vW=class extends ww{code="FILE_SYSTEM_ERROR";constructor($,Y,A){super(`File system ${$} failed for "${Y}": ${A.message}`,{operation:$,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},cW=class extends ww{code="TYPE_GENERATION_ERROR";constructor($,Y,A){super(`Failed to generate types from "${$}" to "${Y}": ${A.message}`,{configDir:$,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},EY=class extends ww{code="SCHEMA_VALIDATION_ERROR";constructor($,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:Y,errorCount:Y.length})}},mW=class extends ww{code="BROWSER_CONFIG_ERROR";constructor($,Y,A,X){super(`Failed to fetch configuration from "${$}": ${Y} ${A}`,{endpoint:$,status:Y,statusText:A,configName:X})}},gW=class extends ww{code="PLUGIN_ERROR";constructor($,Y,A){super(`Plugin "${$}" failed during ${Y}: ${A.message}`,{pluginName:$,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},F$={configNotFound(w,$,Y){return new $8(w,$,Y)},configLoad(w,$,Y){return new GY(w,$,Y)},configValidation(w,$,Y){return new bW(w,$,Y)},configMerge(w,$,Y,A){return new uW(w,$,Y,A)},envVar(w,$,Y,A){return new Y8(w,$,Y,A)},fileSystem(w,$,Y){return new vW(w,$,Y)},typeGeneration(w,$,Y){return new cW(w,$,Y)},schemaValidation(w,$,Y){return new EY(w,$,Y)},browserConfig(w,$,Y,A){return new mW(w,$,Y,A)},plugin(w,$,Y){return new gW(w,$,Y)}},lz={replace:"replace",concat:"concat",smart:"smart"},pz=/^https?:\/\//,Mw=new w8("bunfig",{showTags:!0}),Y$=new aW,rz=l0(i$.cwd(),"config"),tz=l0(i$.cwd(),"src/generated")});$N=A8.env.CLARITY_LOG_DIR||oq(wN(),"logs"),az={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},X8={...az},B3=(async()=>{try{let{loadConfig:w}=await sq().then(()=>_z),$=await w({name:"clarity",alias:"logging",defaultConfig:az,cwd:A8.cwd()});if($)Object.assign(X8,$)}catch{}return X8})();C0={red:(w)=>`\x1B[31m${w}\x1B[0m`,green:(w)=>`\x1B[32m${w}\x1B[0m`,yellow:(w)=>`\x1B[33m${w}\x1B[0m`,blue:(w)=>`\x1B[34m${w}\x1B[0m`,magenta:(w)=>`\x1B[35m${w}\x1B[0m`,cyan:(w)=>`\x1B[36m${w}\x1B[0m`,white:(w)=>`\x1B[37m${w}\x1B[0m`,gray:(w)=>`\x1B[90m${w}\x1B[0m`,bgRed:(w)=>`\x1B[41m${w}\x1B[0m`,bgYellow:(w)=>`\x1B[43m${w}\x1B[0m`,bgGray:(w)=>`\x1B[100m${w}\x1B[0m`,bold:(w)=>`\x1B[1m${w}\x1B[0m`,dim:(w)=>`\x1B[2m${w}\x1B[0m`,italic:(w)=>`\x1B[3m${w}\x1B[0m`,underline:(w)=>`\x1B[4m${w}\x1B[0m`,strikethrough:(w)=>`\x1B[9m${w}\x1B[0m`,reset:"\x1B[0m"},g=C0,R3=C0.red,zN=C0.green,M3=C0.yellow,GN=C0.blue,y3=C0.magenta,I3=C0.cyan,Oz=C0.white,C3=C0.gray,EN=C0.bgRed,KN=C0.bgYellow,V3=C0.bgGray,hz=C0.bold,L3=C0.dim,S3=C0.italic,O3=C0.underline,h3=C0.strikethrough,_3=C0.reset,DW={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},FN={debug:"\uD83D\uDD0D",info:GN("ℹ"),success:zN("✓"),warning:KN(Oz(hz(" WARN "))),error:EN(Oz(hz(" ERROR ")))};D3=new FY("stacks")});var P1={};rQ(P1,{shouldReusePort:()=>qY,safeStringify:()=>A$,safeDeleteFile:()=>eW,resolvePathRewrite:()=>oW,redactSensitive:()=>Q8,isValidRootCA:()=>sW,isSingleProxyOptions:()=>NY,isSingleProxyConfig:()=>yN,isProcessElevated:()=>TY,isMultiProxyOptions:()=>b$,isMultiProxyConfig:()=>B8,getSudoPassword:()=>T$,getPrimaryDomain:()=>j8,extractHostname:()=>MN,execSudoSync:()=>q$,debugLog:()=>E,authorizeSystemAccess:()=>qN});import{execSync as W8}from"node:child_process";import*as w2 from"node:fs/promises";function T$(){return process.env.SUDO_PASSWORD}function TY(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function qN(w={}){if(process.platform==="win32")return!0;if(TY()||!!T$())return!0;let $=w.exec??W8;try{return $("sudo -n true",{stdio:"ignore"}),!0}catch{if(!w.interactive)return!1}try{return $("sudo -v",{stdio:"inherit"}),!0}catch{return!1}}function q$(w){if(TY())return W8(w,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let $=T$(),Y=w.replace(/'/g,"'\\''");if($)return W8(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return W8(`sudo -n sh -c '${Y}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function E(w,$,Y){if(Y)TN.debug(`[rpx:${w}] ${$}`)}function qY(){let w=process.env.RPX_REUSE_PORT;return w==="1"||w==="true"}function RN(w){let $=w.toLowerCase();return NN.has($)||$.endsWith("password")||$.includes("secret")||$.includes("token")}function Q8(w){if(Array.isArray(w))return w.map((Y)=>Q8(Y));if(typeof w==="string")return HN.test(w)?ez:w;if(!w||typeof w!=="object")return w;let $={};for(let[Y,A]of Object.entries(w)){if(RN(Y)){$[Y]=ez;continue}$[Y]=Q8(A)}return $}function A$(w,$){return JSON.stringify(Q8(w),null,$)}function MN(w){if(b$(w))return w.proxies.map(($)=>{let Y=$.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(NY(w)){let $=w.to||"stacks.localhost";return[$.startsWith("http")?new URL($).hostname:$]}return["stacks.localhost"]}function sW(w){return typeof w==="object"&&w!==null&&"certificate"in w&&"privateKey"in w&&typeof w.certificate==="string"&&typeof w.privateKey==="string"}function j8(w){if(!w)return"stacks.localhost";if(b$(w)&&w.proxies.length>0)return w.proxies[0].to||"stacks.localhost";if(NY(w))return w.to||"stacks.localhost";return"stacks.localhost"}function B8(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}function b$(w){return"proxies"in w&&Array.isArray(w.proxies)}function NY(w){return"to"in w&&typeof w.to==="string"}function yN(w){return!!(w&&("to"in w)&&!("proxies"in w))}function oW(w,$){if(!$||$.length===0)return null;for(let Y of $)if(w===Y.from||w.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,X=Y.stripPrefix===!0?w.slice(Y.from.length)||"/":w;return{targetHost:A,targetPath:X}}return null}async function eW(w,$){try{await w2.unlink(w),E("certificates",`Successfully deleted: ${w}`,$)}catch(Y){if(Y.code!=="ENOENT")E("certificates",`Warning: Could not delete ${w}: ${Y}`,$)}}var TN,ez="[redacted]",NN,HN;var f0=a(()=>{oz();TN=new FY("rpx",{showTags:!1});NN=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),HN=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as f8}from"node:child_process";import{homedir as IN}from"node:os";import{join as CN}from"node:path";function z8(){return CN(IN(),"Library/Keychains/login.keychain-db")}function $Q(){return[H$,z8()]}function $2(w,$=wQ){let Y=f8(`security find-certificate -a -c "${$}" -Z "${w}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let X of Y.split(`
180
+ `)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)A.push(J[1].toUpperCase())}return A}function YQ(w){if(process.platform!=="darwin")return;let $=P$(w.caPath);if(!$)return;let Y=w.commonName??wQ,A=w.keychains??$Q();for(let X of A)for(let J of $2(X,Y)){if(J===$)continue;try{if(X.startsWith("/Library"))q$(`security delete-certificate -Z ${J} "${X}"`);else f8(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});E("ssl",`Removed stale Root CA ${J} from ${X}`,w.verbose)}catch{}}}function AQ(w,$,Y){if(process.platform!=="darwin")return G8(w,Y);try{let X=f8(`security verify-cert -c "${w}" -s "${$}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return E("ssl",`verify-cert ${$}: ${X?"trusted":"not trusted"}`,Y?.verbose),X}catch{return!1}}function G8(w,$){let Y=P$(w);if(!Y)return!1;for(let A of $Q())try{let X=f8(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let J of X.split(`
181
+ `))if(J.toUpperCase().includes("SHA-256")){if(J.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return E("ssl",`Root CA fingerprint found in ${A}`,$?.verbose),!0}}catch{}return!1}var N$="-d -r trustRoot -p ssl -p basic",H$="/Library/Keychains/System.keychain",wQ="rpx.localhost";var XQ=a(()=>{_X();f0()});import{execSync as JQ}from"node:child_process";import z0 from"node:fs/promises";import*as UQ from"node:os";import{homedir as i1}from"node:os";import*as X2 from"node:path";import{join as G0}from"node:path";import*as R$ from"node:process";function J2(w,$){return[...new Set(w.filter(Boolean))].map((Y)=>({serverName:Y,cert:$.cert,key:$.key}))}function U2(w,$,Y){let A=G0(i1(),".stacks","ssl"),X=[...new Set([$,...w,"rpx.localhost"])];return{https:{certPath:WQ,keyPath:G0(A,"rpx.localhost.key"),caCertPath:G0(A,"rpx.localhost.ca.crt"),commonName:$},verbose:Y,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function W2(w){return{caCertPath:G0(w,LN),caKeyPath:G0(w,SN)}}async function ON(w,$){try{let[Y,A]=await Promise.all([z0.readFile(w.caCertPath,"utf8"),z0.readFile(w.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return E("ssl",`Root CA files at ${w.caCertPath} look malformed, will regenerate`,$),null;return{certificate:Y,privateKey:A}}catch(Y){return E("ssl",`No existing Root CA at ${w.caCertPath} (${Y.code||Y}), will create one`,$),null}}function Y2(w){let $=new Set;$.add(w);let Y=w.split(".");if(Y.length>=3){let A=Y[Y.length-1],X=Y[Y.length-2],J=new Set(["co","com","org","net","ac","gov","edu"]);if(!(Y.length===3&&A.length===2&&J.has(X)))$.add(`*.${Y.slice(1).join(".")}`)}return Array.from($)}function Q2(w){let Y=j8(w).replace(/\*/g,"wildcard"),A=G0(i1(),".stacks","ssl"),X=A;if(typeof w?.https==="object")return X=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:A,{caCertPath:w.https.caCertPath||G0(X,`${Y}.ca.crt`),certPath:w.https.certPath||G0(X,`${Y}.crt`),keyPath:w.https.keyPath||G0(X,`${Y}.key`)};return{caCertPath:G0(X,`${Y}.ca.crt`),certPath:G0(X,`${Y}.crt`),keyPath:G0(X,`${Y}.key`)}}function A2(w){let $=new Set;if(b$(w))w.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";Y2(A).forEach((X)=>$.add(X))});else if(NY(w)){let Y=w.to||"rpx.localhost";Y2(Y).forEach((A)=>$.add(A))}else $.add("rpx.localhost");return $.add("localhost"),$.add("*.localhost"),$}async function HY(w){if(M$&&!w.forceRegenerate){E("ssl","Using cached SSL configuration",w.verbose);return}QQ();let $=b$(w)?w.proxies.map((B)=>B.to):[w.to];E("ssl",`Generating certificate for domains: ${$.join(", ")}`,w.verbose);let Y=RY(w,w.verbose),A=Y.basePath||G0(i1(),".stacks","ssl");await z0.mkdir(A,{recursive:!0});let X=W2(A),J=await ON(X,w.verbose),U=!1;if(!J){if(w.verbose)H.info("Generating Root CA certificate (one-time)...");J=await QW(Y);try{await Promise.all([z0.writeFile(X.caCertPath,J.certificate),z0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,E("ssl",`Persisted Root CA at ${X.caCertPath}`,w.verbose)}catch(B){throw E("ssl",`Error saving Root CA files: ${B}`,w.verbose),Error(`Failed to save Root CA files: ${B}`)}}else E("ssl",`Reusing existing Root CA from ${X.caCertPath}`,w.verbose);if(w.verbose)H.info(`Generating host certificate for: ${$.join(", ")}`);let Q=await jW({...Y,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([z0.writeFile(Y.certPath,Q.certificate),z0.writeFile(Y.keyPath,Q.privateKey),z0.writeFile(Y.caCertPath,J.certificate)]),E("ssl","Certificate files saved successfully",w.verbose)}catch(B){throw E("ssl",`Error saving certificate files: ${B}`,w.verbose),Error(`Failed to save certificate files: ${B}`)}if(U?!1:await B2(X.caCertPath,{verbose:w.verbose,regenerateUntrustedCerts:!0})){if(E("ssl","Root CA already trusted, skipping trust store update",w.verbose),w.verbose)H.success("Root CA is already trusted in system trust store");if(M$={key:Q.privateKey,cert:Q.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);return}if(w.verbose)H.info("Adding certificate to system trust store (may require sudo permission)...");let j=!1;if(R$.platform==="darwin")try{YQ({caPath:X.caCertPath,verbose:w.verbose});let B=z8();try{JQ(`security add-trusted-cert ${N$} -k "${B}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(q$(`security add-trusted-cert ${N$} -k ${H$} "${X.caCertPath}"`),w.verbose)H.success("Successfully added Root CA to system trust store");j=!0;let f=G0(A,"trust-rpx-cert.sh"),z=`#!/bin/bash
184
182
  echo "Trusting RPX Root CA"
185
183
  # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
186
184
  # non-interactive. Without it, fall back to a normal sudo prompt.
187
185
  if [ -n "$SUDO_PASSWORD" ]
188
186
  then
189
187
  printf '%s
190
- ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${C$} -k ${y$} "${X.caCertPath}"
188
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${N$} -k ${H$} "${X.caCertPath}"
191
189
  else
192
- sudo security add-trusted-cert ${C$} -k ${y$} "${X.caCertPath}"
190
+ sudo security add-trusted-cert ${N$} -k ${H$} "${X.caCertPath}"
193
191
  fi
194
192
  echo "Root CA trusted! Please restart your browser."
195
193
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
196
- `;await G0.writeFile(z,G,{mode:493})}catch(j){if(w.verbose)H.warn(`Could not add Root CA to trust store automatically: ${j}`);let z=K0(A,"trust-rpx-cert.sh"),G=`#!/bin/bash
194
+ `;await z0.writeFile(f,z,{mode:493})}catch(B){if(w.verbose)H.warn(`Could not add Root CA to trust store automatically: ${B}`);let f=G0(A,"trust-rpx-cert.sh"),z=`#!/bin/bash
197
195
  echo "Trusting RPX Root CA"
198
196
  # SUDO_PASSWORD (e.g. from a Stacks app's .env) makes the trust step
199
197
  # non-interactive. Without it, fall back to a normal sudo prompt.
200
198
  if [ -n "$SUDO_PASSWORD" ]
201
199
  then
202
200
  printf '%s
203
- ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${C$} -k ${y$} "${X.caCertPath}"
201
+ ' "$SUDO_PASSWORD" | sudo -S -p '' security add-trusted-cert ${N$} -k ${H$} "${X.caCertPath}"
204
202
  else
205
- sudo security add-trusted-cert ${C$} -k ${y$} "${X.caCertPath}"
203
+ sudo security add-trusted-cert ${N$} -k ${H$} "${X.caCertPath}"
206
204
  fi
207
205
  echo "Root CA trusted! Please restart your browser."
208
206
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
209
- `;if(await G0.writeFile(z,G,{mode:493}),w.verbose)H.info(`Created a trust helper script at: ${z}`),H.info(`If you're still having certificate issues, run: sh ${z}`)}else if(O$.platform==="linux")try{let{exec:j}=await import("node:child_process"),z="/usr/local/share/ca-certificates/rpx",G=`
207
+ `;if(await z0.writeFile(f,z,{mode:493}),w.verbose)H.info(`Created a trust helper script at: ${f}`),H.info(`If you're still having certificate issues, run: sh ${f}`)}else if(R$.platform==="linux")try{let{exec:B}=await import("node:child_process"),f="/usr/local/share/ca-certificates/rpx",z=`
210
208
  mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
211
209
  cp "${X.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
212
210
  update-ca-certificates
213
211
  echo "RPX Root CA installed. Please restart your browser."
214
- `,K=K0(yW.tmpdir(),`rpx-trust-${Date.now()}.sh`);await G0.writeFile(K,G,{mode:493}),await new Promise((E)=>{j(`sudo bash "${K}"`,(q)=>{if(q){if(w.verbose)H.warn(`Could not trust certificates: ${q}`);E(!1)}else{if(w.verbose)H.success("Successfully added certificates to system trust store");E(!0)}})}),await G0.unlink(K).catch(()=>{}),B=!0}catch(j){if(w.verbose)H.warn(`Failed to trust certificates: ${j}`)}else if(O$.platform==="win32")try{let j=`
212
+ `,G=G0(UQ.tmpdir(),`rpx-trust-${Date.now()}.sh`);await z0.writeFile(G,z,{mode:493}),await new Promise((T)=>{B(`sudo bash "${G}"`,(K)=>{if(K){if(w.verbose)H.warn(`Could not trust certificates: ${K}`);T(!1)}else{if(w.verbose)H.success("Successfully added certificates to system trust store");T(!0)}})}),await z0.unlink(G).catch(()=>{}),j=!0}catch(B){if(w.verbose)H.warn(`Failed to trust certificates: ${B}`)}else if(R$.platform==="win32")try{let B=`
215
213
  $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${X.caCertPath.replace(/\//g,"\\")}")
216
214
  $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
217
215
  $store.Open("ReadWrite")
218
216
  $store.Add($cert)
219
217
  $store.Close()
220
218
  Write-Host "Root CA trusted successfully!"
221
- `,z=K0(yW.tmpdir(),"rpx-trust.ps1");if(await G0.writeFile(z,j),CW(`powershell -ExecutionPolicy Bypass -File "${z}"`),w.verbose)H.success("Successfully added certificate to Windows trust store");B=!0}catch(j){if(w.verbose)H.warn(`Could not trust certificate: ${j}`)}else try{await LQ(W,J.certificate,Y),B=!0}catch(j){if(w.verbose)H.warn(`Could not add certificate to trust store: ${j}`)}if(L$={key:W.privateKey,cert:W.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);if(!B&&w.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function O8(){L$=null}async function W$(w){if(!w)return null;if(L$)return L$;let $=PY(w);try{let[Y,A,X]=await Promise.all([G0.access($.keyPath).then(()=>!0).catch(()=>!1),G0.access($.certPath).then(()=>!0).catch(()=>!1),$.caCertPath?G0.access($.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return F("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${$.keyPath}, ${$.certPath}`,w.verbose),null;let J="regenerateUntrustedCerts"in w,U=w.regenerateUntrustedCerts,W=J?U!==!1:!0;F("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${W}`,w.verbose);let Q=$.basePath||K0(l1(),".stacks","ssl"),B=CG(Q);if(!(W?await LG(B.caCertPath,w):!0))return F("ssl","Root CA exists but is not trusted, will regenerate",w.verbose),null;let[z,G,K]=await Promise.all([G0.readFile($.keyPath,"utf8"),G0.readFile($.certPath,"utf8"),X&&$.caCertPath?G0.readFile($.caCertPath,"utf8"):Promise.resolve(void 0)]);if(K&&!K.includes("-----BEGIN CERTIFICATE-----"))return F("ssl","Invalid root CA certificate content, will regenerate",w.verbose),null;if(l$(w))try{let{X509Certificate:E}=await import("node:crypto"),N=new E(G).subjectAltName||"",R=w.proxies.map((O)=>O.to).filter((O)=>!N.includes(`DNS:${O}`));if(R.length>0)return F("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,w.verbose),null}catch(E){F("ssl",`Could not verify cert SANs: ${E}`,w.verbose)}return F("ssl","Successfully loaded existing certificates",w.verbose),L$={key:z,cert:G,ca:K},L$}catch(Y){return F("ssl",`Error checking existing certificates: ${Y}`,w.verbose),null}}function PY(w,$){let Y=M8(w);F("ssl",`Primary domain: ${Y}`,$);let A=yG(w),X=K0(l1(),".stacks","ssl");if(typeof w.https==="object"){let J=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:w.https.caCertPath||A.caCertPath,certPath:w.https.certPath||A.certPath,keyPath:w.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:w.https.commonName||Y,organizationName:w.https.organizationName||"Local Development",countryName:w.https.countryName||"US",stateName:w.https.stateName||"California",localityName:w.https.localityName||"Playa Vista",validityDays:w.https.validityDays||825,verbose:$||!1,subjectAltNames:Array.from(IG(w)).map((W)=>({type:2,value:W}))};if(EW(w.https.rootCA))U.rootCA=w.https.rootCA;return U}return{domain:Y,hostCertCN:Y,basePath:X,...A,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:Y,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:$||!1,subjectAltNames:Array.from(IG(w)).map((J)=>({type:2,value:J}))}}async function OG(w,$){let Y=yG({to:w,verbose:$}),A=[Y.caCertPath,Y.certPath,Y.keyPath];F("certificates","Attempting to clean up relating certificates",$),await Promise.all(A.map((X)=>TW(X,$)))}async function LG(w,$){try{if(F("ssl",`Checking if certificate is trusted: ${w}`,$?.verbose),O$.platform==="darwin"){if($?.serverName)return IW(w,$.serverName,{verbose:$?.verbose});return C8(w,{verbose:$?.verbose})}else if(O$.platform==="win32")try{let Y=hQ(w)||"";if(!Y)return F("ssl","Could not extract certificate subject",$?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(CW(A).toString().includes(Y))return F("ssl","Certificate found in trusted root store",$?.verbose),!0;return F("ssl","Certificate not found in trusted root store",$?.verbose),!1}catch(Y){return F("ssl",`Error checking certificate trust on Windows: ${Y}`,$?.verbose),!1}else if(O$.platform==="linux")try{let Y=m$(w);if(!Y)return F("ssl","Could not extract certificate fingerprint",$?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await G0.readdir(X)}catch{continue}for(let U of J){let W=m$(VG.join(X,U));if(W&&W===Y)return F("ssl",`Certificate fingerprint found in ${X}`,$?.verbose),!0}}return F("ssl","Certificate not found in system trust stores",$?.verbose),!1}catch(Y){return F("ssl",`Error checking certificate trust on Linux: ${Y}`,$?.verbose),!1}return F("ssl",`Platform ${O$.platform} not supported for certificate trust check`,$?.verbose),!1}catch(Y){return F("ssl",`Error checking if certificate is trusted: ${Y}`,$?.verbose),!1}}var L$=null,y8,YH="rpx-root-ca.crt",AH="rpx-root-ca.key";var L8=t(()=>{mX();nw();kQ();VW();X0();VW();dX();dX();y8=K0(l1(),".stacks","ssl","rpx.localhost.crt")});function JH(w){return{enabled:w?.enabled??!1,path:w?.path??"/",interval:w?.interval??1e4,timeout:w?.timeout??2000,healthyThreshold:w?.healthyThreshold??2,unhealthyThreshold:w?.unhealthyThreshold??3}}function UH(w){return(Array.isArray(w)?w:[w]).map((Y)=>{let A=typeof Y==="string"?{url:Y}:Y;return{url:A.url,weight:A.weight&&A.weight>0?A.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function _W(w){return(Array.isArray(w)?w:[w]).map((Y)=>typeof Y==="string"?Y:Y.url)}function _$(w){if(!w)return"localhost:5173";let $=Array.isArray(w)?w[0]:w;if(!$)return"localhost:5173";return typeof $==="string"?$:$.url}function p1(w,$){return{upstreams:UH(w),strategy:$?.strategy??"round-robin",healthCheck:JH($?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function QH(w){let $=w.upstreams.filter((Y)=>Y.healthy);if($.length===0&&w.upstreams.length===1)return w.upstreams;return $}function WH(w,$){let Y=w.cursor%$.length;return w.cursor=(w.cursor+1)%$.length,$[Y]}function BH(w,$){if(w.wrrCurrentWeights.length!==$.length)w.wrrCurrentWeights=$.map(()=>0);let Y=$.reduce((X,J)=>X+J.weight,0),A=0;for(let X=0;X<$.length;X++)if(w.wrrCurrentWeights[X]+=$[X].weight,w.wrrCurrentWeights[X]>w.wrrCurrentWeights[A])A=X;return w.wrrCurrentWeights[A]-=Y,$[A]}function jH(w){let $=w[0];for(let Y=1;Y<w.length;Y++)if(w[Y].activeConnections<$.activeConnections)$=w[Y];return $}function _G(w){let $=QH(w);if($.length===0)return;if($.length===1)return $[0];switch(w.strategy){case"weighted-round-robin":return BH(w,$);case"least-connections":return jH($);case"round-robin":default:return WH(w,$)}}function _8(w,$){if($.consecutiveFailures=0,$.consecutiveSuccesses+=1,!$.healthy&&$.consecutiveSuccesses>=w.healthCheck.healthyThreshold)$.healthy=!0}function bY(w,$){if($.consecutiveSuccesses=0,$.consecutiveFailures+=1,$.healthy&&$.consecutiveFailures>=w.healthCheck.unhealthyThreshold)$.healthy=!1}function zH(w){let $=w.lastIndexOf(":");if($===-1)return{hostname:w,port:80};let Y=Number(w.slice($+1));return{hostname:w.slice(0,$),port:Number.isFinite(Y)?Y:80}}async function GH(w,$){let{hostname:Y,port:A}=zH($.url),X=new AbortController,J=setTimeout(()=>X.abort(),w.healthCheck.timeout);try{(await fetch(`http://${Y}:${A}${w.healthCheck.path}`,{signal:X.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),_8(w,$)}catch{bY(w,$)}finally{clearTimeout(J)}}function r1(w){if(!w.healthCheck.enabled||w.healthCheckTimer||w.upstreams.length<2)return;let $=setInterval(()=>{for(let Y of w.upstreams)GH(w,Y)},w.healthCheck.interval);$.unref?.(),w.healthCheckTimer=$}function n$(w){if(w.healthCheckTimer)clearInterval(w.healthCheckTimer),w.healthCheckTimer=null}import{createHash as ZG,timingSafeEqual as SG}from"node:crypto";import{readFileSync as KH}from"node:fs";function uY(w,$){let Y=Buffer.from(w,"utf8"),A=Buffer.from($,"utf8");if(Y.length!==A.length)return SG(Y,Y),!1;return SG(Y,A)}function qH(w,$){let Y=(G)=>ZG("md5").update(G).digest(),A=Buffer.from(w,"utf8"),X=Buffer.from($,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let G=A.length;G>0;G-=16)U.push(J.subarray(0,Math.min(G,16)));for(let G=A.length;G>0;G>>=1)U.push(G&1?Buffer.from([0]):A.subarray(0,1));let W=Y(Buffer.concat(U));for(let G=0;G<1000;G++){let K=[];if(K.push(G&1?A:W.subarray(0,16)),G%3)K.push(X);if(G%7)K.push(A);K.push(G&1?W.subarray(0,16):A),W=Y(Buffer.concat(K))}let Q="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",B=(G,K)=>{let E="",q=G;for(let N=0;N<K;N++)E+=Q[q&63],q>>=6;return E},j=W,z="";return z+=B(j[0]<<16|j[6]<<8|j[12],4),z+=B(j[1]<<16|j[7]<<8|j[13],4),z+=B(j[2]<<16|j[8]<<8|j[14],4),z+=B(j[3]<<16|j[9]<<8|j[15],4),z+=B(j[4]<<16|j[10]<<8|j[5],4),z+=B(j[11],2),`$apr1$${$}$${z}`}function NH(w,$){if(/^\$2[aby]?\$/.test($))try{return Bun.password.verifySync(w,$)}catch{return!1}if($.startsWith("$apr1$")){let A=$.split("$")[2]??"";return uY(qH(w,A),$)}if($.startsWith("{SHA}")){let Y=ZG("sha1").update(w,"utf8").digest("base64");return uY(`{SHA}${Y}`,$)}return uY(w,$)}function EH(w){let $=new Map;for(let Y of w.split(`
222
- `)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;$.set(A.slice(0,X),A.slice(X+1))}return $}function t1(w){if(!w)return;let $=(w.realm??"").trim()||"Restricted",Y=[];if(w.username)Y.push({username:w.username,password:w.password??""});for(let J of w.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if(w.htpasswdFile)try{A=EH(KH(w.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:$,verify:(J,U)=>{let W=!1;for(let Q of Y)if(uY(J,Q.username)&&uY(U,Q.password))W=!0;if(A){let Q=A.get(J);if(Q&&NH(U,Q))W=!0}return W}}}function kG(w,$,Y){if($.startsWith(FH))return;let A=w.headers.get("authorization")??"",X=A.indexOf(" "),J=X===-1?A:A.slice(0,X),U=X===-1?"":A.slice(X+1).trim();if(J.toLowerCase()==="basic"&&U){let Q="";try{Q=Buffer.from(U,"base64").toString("utf8")}catch{Q=""}let B=Q.indexOf(":");if(B>=0&&Y.verify(Q.slice(0,B),Q.slice(B+1)))return}let W=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${W}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var FH="/.well-known/acme-challenge/";var cY=()=>{};function HH(w){return TH.has(w.toUpperCase())}function RH(){let w=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(w)&&w>0?w:30000}function MH(w){let $=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite($)&&$>0?$:w*8}function IH(){let w=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(w)&&w>0?w:0}function VH(){let w=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(w)&&w>0?w:0}function CH(){let w=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(w)&&w>0?w:256}class bG{socket=null;buf=new Uint8Array(yH);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(w){let $=this.socket,Y=$.write(w);while(Y<w.length){if(this.closed)throw S8;await new Promise((A)=>{this.drainWaiter=A}),Y+=$.write(w.subarray(Y))}}wakeDrain(){let w=this.drainWaiter;if(w)this.drainWaiter=null,w()}push(w){if(this.bodyQueue){let $=w.length<=this.bodyRemaining?w.length:this.bodyRemaining;if($>0)this.bodyQueue.push(w.slice(0,$)),this.queuedBytes+=$;if(this.bodyRemaining-=$,$<w.length)this.appendToBuf(w.subarray($));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(w),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>OH)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=LH)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(w){let $=this.len+w.length;if($>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,$));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set(w,this.len),this.len=$}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let w=this.waiter;if(w)this.waiter=null,w()}waitForData(w){if(this.len>w||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class uG{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=RH();maxWaiters;checkoutIdleMs=IH();inUse=new Set;constructor(w,$,Y,A=""){this.host=w;this.port=$;this.maxTotal=Y;this.key=A;this.maxWaiters=MH(Y)}trackCheckout(w){if(w.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(w),this.ensureSweeper()}dial(){let w=new bG;return fH({hostname:this.host,port:this.port,socket:{data:($,Y)=>w.push(Y),drain:()=>w.wakeDrain(),close:()=>w.markClosed(),end:()=>w.markClosed(),error:()=>w.markClosed(),connectError:()=>w.markClosed(),timeout:()=>w.markTimedOut()}}).then(($)=>{let Y=$;Y.setNoDelay?.(!0);let A=VH();if(A>0)Y.timeout?.(A);return w.socket=$,w})}acquireIdleSync(){while(this.idle.length){let w=this.idle.pop();if(!w.closed)return w.socket?.ref(),w.pos=0,w.len=0,this.trackCheckout(w),w;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw p$;let w=await this.waitForSlot();if(w===p$)throw p$;if(w)return w.pos=0,w.len=0,this.trackCheckout(w),w}this.open++;try{let w=await this.dial();return this.trackCheckout(w),w}catch(w){throw this.open--,this.wakeWaiter(),w}}waitForSlot(){return new Promise((w)=>{let $=!1,Y=(J)=>{if($)return;$=!0,clearTimeout(X),w(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(p$)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release(w){if(this.inUse.delete(w),w.closed){this.open--,this.wakeWaiter();return}w.clearStreaming(),w.compact(),w.fresh=!1;let $=this.waiters.shift();if($){w.socket?.ref(),this.trackCheckout(w),$(w);return}w.idleSince=Date.now(),w.socket?.unref(),this.idle.push(w),this.ensureSweeper()}destroy(w){this.inUse.delete(w),w.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let w=this.waiters.shift();if(w)w(null)}ensureSweeper(){if(this.sweeper)return;let w=this.checkoutIdleMs>0?Math.min(SW,this.checkoutIdleMs):SW;this.sweeper=setInterval(()=>this.sweep(),w),this.sweeper.unref?.()}sweep(){let w=Date.now(),$=w-SW;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=$)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=w-this.checkoutIdleMs;for(let A of this.inUse)if(!A.closed&&A.lastActivityAt>0&&A.lastActivityAt<=Y)A.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&Z8.get(this.key)===this)Z8.delete(this.key)}}}function hH(w,$){let Y=Z8.get(w);if(!Y){let A=w.lastIndexOf(":"),X=A===-1?w:w.slice(0,A),J=A===-1?80:Number(w.slice(A+1));Y=new uG(X,J,$,w),Z8.set(w,Y)}return Y}function hG(w,$,Y){for(let A=Y+3;A<$;A++)if(w[A]===10&&w[A-1]===13&&w[A-2]===10&&w[A-3]===13)return A-3;return-1}function DH(w,$,Y){let A=PG.decode(w.subarray($,Y)),X=A.indexOf(`\r
223
- `),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),W=Number.parseInt(J.slice(U+1,U+5),10),Q=J.startsWith("HTTP/1.0"),B=[],j=-1,z=!1,G=Q,K=!1,E=!1,q=X===-1?A.length:X+2;while(q<A.length){let N=A.indexOf(`\r
224
- `,q);if(N===-1)N=A.length;let f=A.slice(q,N);if(q=N+2,f==="")continue;let R=f.indexOf(":");if(R===-1)continue;let O=f.slice(0,R),y=f.slice(R+1).trim(),T=O.charCodeAt(0)|32;if(T===99||T===116||T===107){let M=O.toLowerCase();if(M==="content-length"){let V=/^\d+$/.test(y)?Number(y):Number.NaN;if(!Number.isSafeInteger(V)||j>=0&&j!==V)E=!0;else j=V;continue}if(M==="transfer-encoding"){if(y.toLowerCase().includes("chunked"))z=!0;continue}if(M==="connection"){let V=y.toLowerCase();if(V.includes("close"))G=!0;if(V.includes("keep-alive"))K=!0;continue}if(M==="keep-alive")continue}B.push([O,y])}if(Q&&K)G=!1;if(z&&j>=0)j=-1;return{status:W,headerEnd:Y,headers:B,contentLength:j,chunked:z,closeConn:G,malformed:E}}function xH(w,$){return $||w===204||w===304}async function cG(w){let{hostPort:$,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:W}=w,Q=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw vY;let B=null;if(W){let K=X.get("content-length"),E=K?Number.parseInt(K,10):Number.NaN;if(Number.isNaN(E)||E>DG)throw vY;if(B=await mH(W),B===null)throw vY}let j=iH(Y,A,X,$,J,U,B),z=j;if(B&&B.length)z=new Uint8Array(j.length+B.length),z.set(j),z.set(B,j.length);let G=hH($,w.maxPerHost??CH());for(let K=0;;K++){if(K>0)await new Promise((q)=>{setTimeout(q,K)});let E;try{E=G.acquireIdleSync()??await G.acquireOrDial()}catch(q){if(q!==p$&&K<4)continue;throw q}try{let q=E.socket.write(z);if(q<z.length)await E.writeAll(z.subarray(q));return await bH(G,E,Q)}catch(q){let N=q===S8&&K<4&&(E.fresh||HH(Y));if(G.destroy(E),N)continue;if(q===S8)throw Error("upstream closed connection");throw q}}}async function PH(w){let $=hG(w.buf,w.len,w.pos);while($===-1){if(w.closed){if(w.timedOut)throw ZW;if(w.len===w.pos)throw S8;throw Error("upstream closed mid-header")}if(w.len-w.pos>xG)throw Error("upstream header block too large");await w.waitForData(w.len),$=hG(w.buf,w.len,w.pos)}return $}async function bH(w,$,Y){let A;for(;;){let J=await PH($);if(A=DH($.buf,$.pos,J),$.pos=J+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw w.destroy($),Error("upstream sent malformed response framing");let X=A.headers;if(xH(A.status,Y))return vG(w,$,A.closeConn),new Response(null,{status:A.status,headers:X});if(A.chunked)return new Response(vH(w,$,A.closeConn),{status:A.status,headers:X});if(A.contentLength>=0){if($.len-$.pos>=A.contentLength){let U=$.pos+A.contentLength,W=$.len>U,Q=null;if(A.contentLength>=_H)Q=$.buf.subarray($.pos,U),$.buf=new Uint8Array(SH);else if(A.contentLength>0)Q=$.buf.slice($.pos,U);if($.pos=0,$.len=0,A.closeConn||W)w.destroy($);else w.release($);return new Response(Q,{status:A.status,headers:X})}return new Response(uH(w,$,A.contentLength,A.closeConn),{status:A.status,headers:X})}return new Response(cH($),{status:A.status,headers:X})}function vG(w,$,Y){if(Y||$.pos!==$.len)w.destroy($);else w.release($)}function uH(w,$,Y,A){let X=$.len-$.pos,J=X>0?$.buf.slice($.pos,$.len):null;$.pos=0,$.len=0,$.bodyQueue=[],$.bodyRemaining=Y-X,$.queuedBytes=0,$.streamingBody=!0;let U=(W)=>{if($.bodyQueue=null,A||$.len>0)w.destroy($);else w.release($);W.close()};return new ReadableStream({start(W){if(J)W.enqueue(J);if($.bodyRemaining===0&&$.bodyQueue.length===0)U(W)},async pull(W){for(;;){let Q=$.bodyQueue;if(Q&&Q.length>0){let B=Q.shift();if($.queuedBytes-=B.length,$.resumeIfDrained(),W.enqueue(B),$.bodyRemaining===0&&Q.length===0)U(W);return}if($.bodyRemaining===0){if($.bodyQueue)U(W);return}if($.closed){$.bodyQueue=null,w.destroy($),W.error(Error("upstream closed mid-body"));return}await $.waitForBody()}},cancel(){$.bodyQueue=null,w.destroy($)}})}function cH(w){return w.streamingBody=!0,new ReadableStream({async pull($){for(;;){if(w.len>w.pos){$.enqueue(w.buf.slice(w.pos,w.len)),w.pos=w.len,w.resumeIfDrained();return}if(w.closed){w.destroy(),$.close();return}await w.waitForData(w.len)}},cancel(){w.destroy()}})}function vH(w,$,Y){$.streamingBody=!0;let A=0,X=!1;async function J(){for(;;){for(let U=$.pos;U+1<$.len;U++)if($.buf[U]===13&&$.buf[U+1]===10){let W=PG.decode($.buf.subarray($.pos,U));return $.pos=U+2,W}if($.closed)throw Error("upstream closed mid-chunk-header");if($.len-$.pos>xG)throw Error("upstream chunk header too large");await $.waitForData($.len)}}return new ReadableStream({async pull(U){for(;;){if(A>0){if($.len===$.pos){if($.closed){w.destroy($),U.error(Error("upstream closed mid-chunk"));return}await $.waitForData($.len);continue}let j=Math.min(A,$.len-$.pos);if(U.enqueue($.buf.slice($.pos,$.pos+j)),$.pos+=j,A-=j,$.resumeIfDrained(),A===0)X=!0;return}if(X)await J(),X=!1;let W=await J(),Q=W.indexOf(";"),B=Number.parseInt(Q===-1?W:W.slice(0,Q),16);if(!Number.isInteger(B)||B<0){w.destroy($),U.error(Error("upstream sent malformed chunk size"));return}if(B===0){for(;;)if(await J()==="")break;vG(w,$,Y),U.close();return}A=B}},cancel(){w.destroy($)}})}function iH(w,$,Y,A,X,J,U){let W=`${w} ${$} HTTP/1.1\r
219
+ `,f=G0(UQ.tmpdir(),"rpx-trust.ps1");if(await z0.writeFile(f,B),JQ(`powershell -ExecutionPolicy Bypass -File "${f}"`),w.verbose)H.success("Successfully added certificate to Windows trust store");j=!0}catch(B){if(w.verbose)H.warn(`Could not trust certificate: ${B}`)}else try{await zW(Q,J.certificate,Y),j=!0}catch(B){if(w.verbose)H.warn(`Could not add certificate to trust store: ${B}`)}if(M$={key:Q.privateKey,cert:Q.certificate,ca:J.certificate},w.verbose)H.success(`Certificate generated successfully for ${$.length} domain${$.length>1?"s":""}`);if(!j&&w.verbose)H.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),H.warn("This will bypass the warning and you should only need to do it once")}function QQ(){M$=null}async function y$(w){if(!w)return null;if(M$)return M$;let $=RY(w);try{let[Y,A,X]=await Promise.all([z0.access($.keyPath).then(()=>!0).catch(()=>!1),z0.access($.certPath).then(()=>!0).catch(()=>!1),$.caCertPath?z0.access($.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return E("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${$.keyPath}, ${$.certPath}`,w.verbose),null;let J="regenerateUntrustedCerts"in w,U=w.regenerateUntrustedCerts,Q=J?U!==!1:!0;E("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${Q}`,w.verbose);let W=$.basePath||G0(i1(),".stacks","ssl"),j=W2(W);if(!(Q?await B2(j.caCertPath,w):!0))return E("ssl","Root CA exists but is not trusted, will regenerate",w.verbose),null;let[f,z,G]=await Promise.all([z0.readFile($.keyPath,"utf8"),z0.readFile($.certPath,"utf8"),X&&$.caCertPath?z0.readFile($.caCertPath,"utf8"):Promise.resolve(void 0)]);if(G&&!G.includes("-----BEGIN CERTIFICATE-----"))return E("ssl","Invalid root CA certificate content, will regenerate",w.verbose),null;if(b$(w))try{let{X509Certificate:T}=await import("node:crypto"),F=new T(z).subjectAltName||"",R=w.proxies.map((L)=>L.to).filter((L)=>!F.includes(`DNS:${L}`));if(R.length>0)return E("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,w.verbose),null}catch(T){E("ssl",`Could not verify cert SANs: ${T}`,w.verbose)}return E("ssl","Successfully loaded existing certificates",w.verbose),M$={key:f,cert:z,ca:G},M$}catch(Y){return E("ssl",`Error checking existing certificates: ${Y}`,w.verbose),null}}function RY(w,$){let Y=j8(w);E("ssl",`Primary domain: ${Y}`,$);let A=Q2(w),X=G0(i1(),".stacks","ssl");if(typeof w.https==="object"){let J=w.https.basePath&&w.https.basePath.trim()!==""?w.https.basePath:X,U={domain:Y,hostCertCN:Y,basePath:J,caCertPath:w.https.caCertPath||A.caCertPath,certPath:w.https.certPath||A.certPath,keyPath:w.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:w.https.commonName||Y,organizationName:w.https.organizationName||"Local Development",countryName:w.https.countryName||"US",stateName:w.https.stateName||"California",localityName:w.https.localityName||"Playa Vista",validityDays:w.https.validityDays||825,verbose:$||!1,subjectAltNames:Array.from(A2(w)).map((Q)=>({type:2,value:Q}))};if(sW(w.https.rootCA))U.rootCA=w.https.rootCA;return U}return{domain:Y,hostCertCN:Y,basePath:X,...A,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:Y,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:$||!1,subjectAltNames:Array.from(A2(w)).map((J)=>({type:2,value:J}))}}async function j2(w,$){let Y=Q2({to:w,verbose:$}),A=[Y.caCertPath,Y.certPath,Y.keyPath];E("certificates","Attempting to clean up relating certificates",$),await Promise.all(A.map((X)=>eW(X,$)))}async function B2(w,$){try{if(E("ssl",`Checking if certificate is trusted: ${w}`,$?.verbose),R$.platform==="darwin"){if($?.serverName)return AQ(w,$.serverName,{verbose:$?.verbose});return G8(w,{verbose:$?.verbose})}else if(R$.platform==="win32")try{let Y=GW(w)||"";if(!Y)return E("ssl","Could not extract certificate subject",$?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(JQ(A).toString().includes(Y))return E("ssl","Certificate found in trusted root store",$?.verbose),!0;return E("ssl","Certificate not found in trusted root store",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Windows: ${Y}`,$?.verbose),!1}else if(R$.platform==="linux")try{let Y=P$(w);if(!Y)return E("ssl","Could not extract certificate fingerprint",$?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let X of A){let J;try{J=await z0.readdir(X)}catch{continue}for(let U of J){let Q=P$(X2.join(X,U));if(Q&&Q===Y)return E("ssl",`Certificate fingerprint found in ${X}`,$?.verbose),!0}}return E("ssl","Certificate not found in system trust stores",$?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Linux: ${Y}`,$?.verbose),!1}return E("ssl",`Platform ${R$.platform} not supported for certificate trust check`,$?.verbose),!1}catch(Y){return E("ssl",`Error checking if certificate is trusted: ${Y}`,$?.verbose),!1}}var M$=null,WQ,LN="rpx-root-ca.crt",SN="rpx-root-ca.key";var jQ=a(()=>{hX();k$();xA();XQ();f0();XQ();_X();_X();WQ=G0(i1(),".stacks","ssl","rpx.localhost.crt")});function hN(w){return{enabled:w?.enabled??!1,path:w?.path??"/",interval:w?.interval??1e4,timeout:w?.timeout??2000,healthyThreshold:w?.healthyThreshold??2,unhealthyThreshold:w?.unhealthyThreshold??3}}function _N(w){return(Array.isArray(w)?w:[w]).map((Y)=>{let A=typeof Y==="string"?{url:Y}:Y;return{url:A.url,weight:A.weight&&A.weight>0?A.weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0}})}function f2(w){return(Array.isArray(w)?w:[w]).map((Y)=>typeof Y==="string"?Y:Y.url)}function u$(w){if(!w)return"localhost:5173";let $=Array.isArray(w)?w[0]:w;if(!$)return"localhost:5173";return typeof $==="string"?$:$.url}function MY(w,$){return{upstreams:_N(w),strategy:$?.strategy??"round-robin",healthCheck:hN($?.healthCheck),cursor:0,wrrCurrentWeights:[],healthCheckTimer:null}}function DN(w){let $=w.upstreams.filter((Y)=>Y.healthy);if($.length===0&&w.upstreams.length===1)return w.upstreams;return $}function kN(w,$){let Y=w.cursor%$.length;return w.cursor=(w.cursor+1)%$.length,$[Y]}function ZN(w,$){if(w.wrrCurrentWeights.length!==$.length)w.wrrCurrentWeights=$.map(()=>0);let Y=$.reduce((X,J)=>X+J.weight,0),A=0;for(let X=0;X<$.length;X++)if(w.wrrCurrentWeights[X]+=$[X].weight,w.wrrCurrentWeights[X]>w.wrrCurrentWeights[A])A=X;return w.wrrCurrentWeights[A]-=Y,$[A]}function xN(w){let $=w[0];for(let Y=1;Y<w.length;Y++)if(w[Y].activeConnections<$.activeConnections)$=w[Y];return $}function z2(w){let $=DN(w);if($.length===0)return;if($.length===1)return $[0];switch(w.strategy){case"weighted-round-robin":return ZN(w,$);case"least-connections":return xN($);case"round-robin":default:return kN(w,$)}}function E8(w,$){if($.consecutiveFailures=0,$.consecutiveSuccesses+=1,!$.healthy&&$.consecutiveSuccesses>=w.healthCheck.healthyThreshold)$.healthy=!0}function yY(w,$){if($.consecutiveSuccesses=0,$.consecutiveFailures+=1,$.healthy&&$.consecutiveFailures>=w.healthCheck.unhealthyThreshold)$.healthy=!1}function PN(w){let $=w.lastIndexOf(":");if($===-1)return{hostname:w,port:80};let Y=Number(w.slice($+1));return{hostname:w.slice(0,$),port:Number.isFinite(Y)?Y:80}}async function iN(w,$){let{hostname:Y,port:A}=PN($.url),X=new AbortController,J=setTimeout(()=>X.abort(),w.healthCheck.timeout);try{(await fetch(`http://${Y}:${A}${w.healthCheck.path}`,{signal:X.signal,redirect:"manual"})).body?.cancel().catch(()=>{}),E8(w,$)}catch{yY(w,$)}finally{clearTimeout(J)}}function IY(w){if(!w.healthCheck.enabled||w.healthCheckTimer||w.upstreams.length<2)return;let $=setInterval(()=>{for(let Y of w.upstreams)iN(w,Y)},w.healthCheck.interval);$.unref?.(),w.healthCheckTimer=$}function b1(w){if(w.healthCheckTimer)clearInterval(w.healthCheckTimer),w.healthCheckTimer=null}import{createHash as E2,timingSafeEqual as G2}from"node:crypto";import{readFileSync as bN}from"node:fs";function CY(w,$){let Y=Buffer.from(w,"utf8"),A=Buffer.from($,"utf8");if(Y.length!==A.length)return G2(Y,Y),!1;return G2(Y,A)}function vN(w,$){let Y=(z)=>E2("md5").update(z).digest(),A=Buffer.from(w,"utf8"),X=Buffer.from($,"utf8"),J=Y(Buffer.concat([A,X,A])),U=[A,Buffer.from("$apr1$","utf8"),X];for(let z=A.length;z>0;z-=16)U.push(J.subarray(0,Math.min(z,16)));for(let z=A.length;z>0;z>>=1)U.push(z&1?Buffer.from([0]):A.subarray(0,1));let Q=Y(Buffer.concat(U));for(let z=0;z<1000;z++){let G=[];if(G.push(z&1?A:Q.subarray(0,16)),z%3)G.push(X);if(z%7)G.push(A);G.push(z&1?Q.subarray(0,16):A),Q=Y(Buffer.concat(G))}let W="./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",j=(z,G)=>{let T="",K=z;for(let F=0;F<G;F++)T+=W[K&63],K>>=6;return T},B=Q,f="";return f+=j(B[0]<<16|B[6]<<8|B[12],4),f+=j(B[1]<<16|B[7]<<8|B[13],4),f+=j(B[2]<<16|B[8]<<8|B[14],4),f+=j(B[3]<<16|B[9]<<8|B[15],4),f+=j(B[4]<<16|B[10]<<8|B[5],4),f+=j(B[11],2),`$apr1$${$}$${f}`}function cN(w,$){if(/^\$2[aby]?\$/.test($))try{return Bun.password.verifySync(w,$)}catch{return!1}if($.startsWith("$apr1$")){let A=$.split("$")[2]??"";return CY(vN(w,A),$)}if($.startsWith("{SHA}")){let Y=E2("sha1").update(w,"utf8").digest("base64");return CY(`{SHA}${Y}`,$)}return CY(w,$)}function mN(w){let $=new Map;for(let Y of w.split(`
220
+ `)){let A=Y.trim();if(!A||A.startsWith("#"))continue;let X=A.indexOf(":");if(X<=0)continue;$.set(A.slice(0,X),A.slice(X+1))}return $}function VY(w){if(!w)return;let $=(w.realm??"").trim()||"Restricted",Y=[];if(w.username)Y.push({username:w.username,password:w.password??""});for(let J of w.users??[])if(J?.username)Y.push({username:J.username,password:J.password??""});let A;if(w.htpasswdFile)try{A=mN(bN(w.htpasswdFile,"utf8"))}catch{A=void 0}if(Y.length===0&&(!A||A.size===0))return;return{realm:$,verify:(J,U)=>{let Q=!1;for(let W of Y)if(CY(J,W.username)&&CY(U,W.password))Q=!0;if(A){let W=A.get(J);if(W&&cN(U,W))Q=!0}return Q}}}function K2(w,$,Y){if($.startsWith(uN))return;let A=w.headers.get("authorization")??"",X=A.indexOf(" "),J=X===-1?A:A.slice(0,X),U=X===-1?"":A.slice(X+1).trim();if(J.toLowerCase()==="basic"&&U){let W="";try{W=Buffer.from(U,"base64").toString("utf8")}catch{W=""}let j=W.indexOf(":");if(j>=0&&Y.verify(W.slice(0,j),W.slice(j+1)))return}let Q=Y.realm.replace(/["\\]/g,"");return new Response("401 Unauthorized",{status:401,headers:{"www-authenticate":`Basic realm="${Q}", charset="UTF-8"`,"content-type":"text/plain; charset=utf-8"}})}var uN="/.well-known/acme-challenge/";var K8=()=>{};function nN(w){return dN.has(w.toUpperCase())}function lN(){let w=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite(w)&&w>0?w:30000}function pN(w){let $=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite($)&&$>0?$:w*8}function rN(){let w=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite(w)&&w>0?w:0}function tN(){let w=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite(w)&&w>0?w:0}function aN(){let w=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite(w)&&w>0?w:256}class H2{socket=null;buf=new Uint8Array(sN);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll(w){let $=this.socket,Y=$.write(w);while(Y<w.length){if(this.closed)throw F8;await new Promise((A)=>{this.drainWaiter=A}),Y+=$.write(w.subarray(Y))}}wakeDrain(){let w=this.drainWaiter;if(w)this.drainWaiter=null,w()}push(w){if(this.bodyQueue){let $=w.length<=this.bodyRemaining?w.length:this.bodyRemaining;if($>0)this.bodyQueue.push(w.slice(0,$)),this.queuedBytes+=$;if(this.bodyRemaining-=$,$<w.length)this.appendToBuf(w.subarray($));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf(w),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>oN)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=eN)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf(w){let $=this.len+w.length;if($>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,$));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set(w,this.len),this.len=$}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let w=this.waiter;if(w)this.waiter=null,w()}waitForData(w){if(this.len>w||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class R2{host;port;maxTotal;key;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=lN();maxWaiters;checkoutIdleMs=rN();inUse=new Set;constructor(w,$,Y,A=""){this.host=w;this.port=$;this.maxTotal=Y;this.key=A;this.maxWaiters=pN(Y)}trackCheckout(w){if(w.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add(w),this.ensureSweeper()}dial(){let w=new H2;return gN({hostname:this.host,port:this.port,socket:{data:($,Y)=>w.push(Y),drain:()=>w.wakeDrain(),close:()=>w.markClosed(),end:()=>w.markClosed(),error:()=>w.markClosed(),connectError:()=>w.markClosed(),timeout:()=>w.markTimedOut()}}).then(($)=>{let Y=$;Y.setNoDelay?.(!0);let A=tN();if(A>0)Y.timeout?.(A);return w.socket=$,w})}acquireIdleSync(){while(this.idle.length){let w=this.idle.pop();if(!w.closed)return w.socket?.ref(),w.pos=0,w.len=0,this.trackCheckout(w),w;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw v$;let w=await this.waitForSlot();if(w===v$)throw v$;if(w)return w.pos=0,w.len=0,this.trackCheckout(w),w}this.open++;try{let w=await this.dial();return this.trackCheckout(w),w}catch(w){throw this.open--,this.wakeWaiter(),w}}waitForSlot(){return new Promise((w)=>{let $=!1,Y=(J)=>{if($)return;$=!0,clearTimeout(X),w(J)},A=(J)=>Y(J),X=setTimeout(()=>{let J=this.waiters.indexOf(A);if(J!==-1)this.waiters.splice(J,1);Y(v$)},this.queueWaitMs);X.unref?.(),this.waiters.push(A)})}release(w){if(this.inUse.delete(w),w.closed){this.open--,this.wakeWaiter();return}w.clearStreaming(),w.compact(),w.fresh=!1;let $=this.waiters.shift();if($){w.socket?.ref(),this.trackCheckout(w),$(w);return}w.idleSince=Date.now(),w.socket?.unref(),this.idle.push(w),this.ensureSweeper()}destroy(w){this.inUse.delete(w),w.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let w=this.waiters.shift();if(w)w(null)}ensureSweeper(){if(this.sweeper)return;let w=this.checkoutIdleMs>0?Math.min(BQ,this.checkoutIdleMs):BQ;this.sweeper=setInterval(()=>this.sweep(),w),this.sweeper.unref?.()}sweep(){let w=Date.now(),$=w-BQ;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=$)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=w-this.checkoutIdleMs;for(let A of this.inUse)if(!A.closed&&A.lastActivityAt>0&&A.lastActivityAt<=Y)A.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper){if(clearInterval(this.sweeper),this.sweeper=null,this.key&&T8.get(this.key)===this)T8.delete(this.key)}}}function XH(w,$){let Y=T8.get(w);if(!Y){let A=w.lastIndexOf(":"),X=A===-1?w:w.slice(0,A),J=A===-1?80:Number(w.slice(A+1));Y=new R2(X,J,$,w),T8.set(w,Y)}return Y}function F2(w,$,Y){for(let A=Y+3;A<$;A++)if(w[A]===10&&w[A-1]===13&&w[A-2]===10&&w[A-3]===13)return A-3;return-1}function JH(w,$,Y){let A=N2.decode(w.subarray($,Y)),X=A.indexOf(`\r
221
+ `),J=X===-1?A:A.slice(0,X),U=J.indexOf(" "),Q=Number.parseInt(J.slice(U+1,U+5),10),W=J.startsWith("HTTP/1.0"),j=[],B=-1,f=!1,z=W,G=!1,T=!1,K=X===-1?A.length:X+2;while(K<A.length){let F=A.indexOf(`\r
222
+ `,K);if(F===-1)F=A.length;let q=A.slice(K,F);if(K=F+2,q==="")continue;let R=q.indexOf(":");if(R===-1)continue;let L=q.slice(0,R),V=q.slice(R+1).trim(),N=L.charCodeAt(0)|32;if(N===99||N===116||N===107){let M=L.toLowerCase();if(M==="content-length"){let C=/^\d+$/.test(V)?Number(V):Number.NaN;if(!Number.isSafeInteger(C)||B>=0&&B!==C)T=!0;else B=C;continue}if(M==="transfer-encoding"){if(V.toLowerCase().includes("chunked"))f=!0;continue}if(M==="connection"){let C=V.toLowerCase();if(C.includes("close"))z=!0;if(C.includes("keep-alive"))G=!0;continue}if(M==="keep-alive")continue}j.push([L,V])}if(W&&G)z=!1;if(f&&B>=0)B=-1;return{status:Q,headerEnd:Y,headers:j,contentLength:B,chunked:f,closeConn:z,malformed:T}}function UH(w,$){return $||w===204||w===304}async function M2(w){let{hostPort:$,method:Y,path:A,reqHeaders:X,forwardedHost:J,originOverride:U,body:Q}=w,W=Y==="HEAD";if(X.get("expect")||X.get("upgrade"))throw LY;let j=null;if(Q){let G=X.get("content-length"),T=G?Number.parseInt(G,10):Number.NaN;if(Number.isNaN(T)||T>T2)throw LY;if(j=await GH(Q),j===null)throw LY}let B=zH(Y,A,X,$,J,U,j),f=B;if(j&&j.length)f=new Uint8Array(B.length+j.length),f.set(B),f.set(j,B.length);let z=XH($,w.maxPerHost??aN());for(let G=0;;G++){if(G>0)await new Promise((K)=>{setTimeout(K,G)});let T;try{T=z.acquireIdleSync()??await z.acquireOrDial()}catch(K){if(K!==v$&&G<4)continue;throw K}try{let K=T.socket.write(f);if(K<f.length)await T.writeAll(f.subarray(K));return await QH(z,T,W)}catch(K){let F=K===F8&&G<4&&(T.fresh||nN(Y));if(z.destroy(T),F)continue;if(K===F8)throw Error("upstream closed connection");throw K}}}async function WH(w){let $=F2(w.buf,w.len,w.pos);while($===-1){if(w.closed){if(w.timedOut)throw fQ;if(w.len===w.pos)throw F8;throw Error("upstream closed mid-header")}if(w.len-w.pos>q2)throw Error("upstream header block too large");await w.waitForData(w.len),$=F2(w.buf,w.len,w.pos)}return $}async function QH(w,$,Y){let A;for(;;){let J=await WH($);if(A=JH($.buf,$.pos,J),$.pos=J+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw w.destroy($),Error("upstream sent malformed response framing");let X=A.headers;if(UH(A.status,Y))return y2(w,$,A.closeConn),new Response(null,{status:A.status,headers:X});if(A.chunked)return new Response(fH(w,$,A.closeConn),{status:A.status,headers:X});if(A.contentLength>=0){if($.len-$.pos>=A.contentLength){let U=$.pos+A.contentLength,Q=$.len>U,W=null;if(A.contentLength>=wH)W=$.buf.subarray($.pos,U),$.buf=new Uint8Array($H);else if(A.contentLength>0)W=$.buf.slice($.pos,U);if($.pos=0,$.len=0,A.closeConn||Q)w.destroy($);else w.release($);return new Response(W,{status:A.status,headers:X})}return new Response(jH(w,$,A.contentLength,A.closeConn),{status:A.status,headers:X})}return new Response(BH($),{status:A.status,headers:X})}function y2(w,$,Y){if(Y||$.pos!==$.len)w.destroy($);else w.release($)}function jH(w,$,Y,A){let X=$.len-$.pos,J=X>0?$.buf.slice($.pos,$.len):null;$.pos=0,$.len=0,$.bodyQueue=[],$.bodyRemaining=Y-X,$.queuedBytes=0,$.streamingBody=!0;let U=(Q)=>{if($.bodyQueue=null,A||$.len>0)w.destroy($);else w.release($);Q.close()};return new ReadableStream({start(Q){if(J)Q.enqueue(J);if($.bodyRemaining===0&&$.bodyQueue.length===0)U(Q)},async pull(Q){for(;;){let W=$.bodyQueue;if(W&&W.length>0){let j=W.shift();if($.queuedBytes-=j.length,$.resumeIfDrained(),Q.enqueue(j),$.bodyRemaining===0&&W.length===0)U(Q);return}if($.bodyRemaining===0){if($.bodyQueue)U(Q);return}if($.closed){$.bodyQueue=null,w.destroy($),Q.error(Error("upstream closed mid-body"));return}await $.waitForBody()}},cancel(){$.bodyQueue=null,w.destroy($)}})}function BH(w){return w.streamingBody=!0,new ReadableStream({async pull($){for(;;){if(w.len>w.pos){$.enqueue(w.buf.slice(w.pos,w.len)),w.pos=w.len,w.resumeIfDrained();return}if(w.closed){w.destroy(),$.close();return}await w.waitForData(w.len)}},cancel(){w.destroy()}})}function fH(w,$,Y){$.streamingBody=!0;let A=0,X=!1,J=!1;async function U(){for(;;){for(let Q=$.pos;Q+1<$.len;Q++)if($.buf[Q]===13&&$.buf[Q+1]===10){let W=N2.decode($.buf.subarray($.pos,Q));return $.pos=Q+2,W}if($.closed)throw Error("upstream closed mid-chunk-header");if($.len-$.pos>q2)throw Error("upstream chunk header too large");await $.waitForData($.len)}}return new ReadableStream({async pull(Q){try{for(;;){if(A>0){if($.len===$.pos){if($.closed){w.destroy($),Q.error(Error("upstream closed mid-chunk"));return}await $.waitForData($.len);continue}let f=Math.min(A,$.len-$.pos);if(Q.enqueue($.buf.slice($.pos,$.pos+f)),$.pos+=f,A-=f,$.resumeIfDrained(),A===0)X=!0;return}if(X)await U(),X=!1;let W=await U(),j=W.indexOf(";"),B=Number.parseInt(j===-1?W:W.slice(0,j),16);if(!Number.isInteger(B)||B<0){w.destroy($),Q.error(Error("upstream sent malformed chunk size"));return}if(B===0){for(;;)if(await U()==="")break;y2(w,$,Y),Q.close();return}A=B}}catch(W){if(w.destroy($),!J)Q.error(W)}},cancel(){J=!0,w.destroy($)}})}function zH(w,$,Y,A,X,J,U){let Q=`${w} ${$} HTTP/1.1\r
225
223
  host: ${A}\r
226
224
  x-forwarded-for: 127.0.0.1\r
227
225
  x-forwarded-proto: https\r
228
226
  x-forwarded-host: ${X}\r
229
- `;if(J!==void 0)W+=`origin: ${J}\r
230
- `;let Q=!1;for(let[B,j]of Y){let z=B.toLowerCase();if(kH.has(z))continue;if(J!==void 0&&z==="origin")continue;if(z==="content-length")Q=!0;W+=`${B}: ${j}\r
231
- `}if(W+=`connection: keep-alive\r
232
- `,U&&!Q)W+=`content-length: ${U.length}\r
233
- `;return W+=`\r
234
- `,ZH.encode(W)}async function mH(w){let $=w.getReader(),Y=[],A=0;for(;;){let{done:U,value:W}=await $.read();if(U)break;if(W){if(A+=W.length,A>DG)return $.cancel().catch(()=>{}),null;Y.push(W)}}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 fH,vY,S8,TH,ZW,p$,DG=1048576,SW=30000,yH=16384,xG=262144,OH=2097152,LH=524288,_H=8192,SH=4096,ZH,PG,kH,Z8;var iG=t(()=>{({connect:fH}=Bun),vY=Symbol("rpx.pool.fallback"),S8=Symbol("rpx.pool.stale"),TH=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);ZW=Symbol("rpx.pool.timeout"),p$=Symbol("rpx.pool.busy");ZH=new TextEncoder,PG=new TextDecoder,kH=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);Z8=new Map});function mG(w){let $=typeof w==="string"?{to:w}:w,Y=($.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:$.status??301,preservePath:$.preservePath??!0}}function gG(w,$,Y){if(!w.preservePath)return w.to||"/";let A=`${$}${Y}`;return A==="/"?`${w.to}/`:`${w.to}${A}`}import*as Gw from"node:path";function iY(w,$){if(typeof w==="string")return{dir:w,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:$};return{dir:w.dir,spa:w.spa??!1,pathRewriteStyle:w.pathRewriteStyle??"directory",maxAge:w.maxAge??0,cleanUrls:$}}function dH(w){let $=Gw.extname(w).toLowerCase();return gH[$]??"application/octet-stream"}function lH(w){let $;try{$=decodeURIComponent(w)}catch{return null}if($.includes("\x00")||$.includes("\\"))return null;let Y=Gw.posix.normalize(`/${$}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function nH(w,$){let Y=lH(w);if(Y===null)return null;let A=Gw.posix.extname(Y);if($.cleanUrls&&A===".html"){let X=w.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:Gw.join($.dir,Y),redirectTo:X||"/"}}if(Y===""||w.endsWith("/"))return{filePath:Gw.join($.dir,Y,"index.html")};if(A!=="")return{filePath:Gw.join($.dir,Y)};if($.pathRewriteStyle==="flat")return{filePath:Gw.join($.dir,`${Y}.html`)};return{filePath:Gw.join($.dir,Y,"index.html")}}async function dG(w,$){let Y=nH(w,$);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=$.maxAge>0?`public, max-age=${$.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":dH(Y.filePath),"Cache-Control":A}});if($.spa){let J=Gw.join($.dir,"index.html"),U=Bun.file(J);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var gH;var mY=t(()=>{gH={".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 pH(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function tH(w){let $=w.headers.get("host")||"",Y=$.indexOf(":");return Y===-1?$:$.slice(0,Y)}function pG(w,$){if(!$||$==="/")return w;if(w===$)return"/";if(w.startsWith(`${$}/`)){let Y=w.slice($.length);return Y===""?"/":Y}return w}function lG(w){if(w.upstreamPool)return _G(w.upstreamPool);if(w.sourceHost)return{url:w.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function nG(w,$,Y,A){let X=Y?.url??$.sourceHost??"",U=$.stripBasePathPrefix??!1?pG(w,$.basePath):w,W=fW(U,$.pathRewrites);if(W)X=W.targetHost,U=W.targetPath,F("request",`Path rewrite: ${w} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function aH(w){let $=w.indexOf("://"),Y=$===-1?w.indexOf("/"):w.indexOf("/",$+3);if(Y===-1)return{pathname:"/",search:""};let A=w.indexOf("?",Y);if(A===-1)return{pathname:w.slice(Y),search:""};return{pathname:w.slice(Y,A),search:w.slice(A)}}function a1(w,$,Y){let A=async(X,J)=>{let{pathname:U,search:W}=aH(X.url),Q=tH(X),B=w(Q,U);if(!B&&Y){let N=await Y(Q,U,X);if(N instanceof Response)return N;if(N&&N.retry)B=w(Q,U)}if(!B)return F("request",`No route found for host: ${Q}`,$),new Response(`No proxy configured for ${Q}`,{status:404});if(B.auth){let N=kG(X,U,B.auth);if(N)return F("request",`401 challenge for ${Q}${U}`,$),N}if(B.redirect){let N=gG(B.redirect,U,W);return F("request",`${B.redirect.status} redirect ${Q}${U} → ${N}`,$),new Response(null,{status:B.redirect.status,headers:{location:N}})}if(B.static){let f=B.stripBasePathPrefix??!0?pG(U,B.basePath):U;return dG(f,B.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let N=lG(B);if(!J||!N)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:f,targetPath:R}=nG(U,B,N,$),O=`ws://${f}${R}${W}`,y={};for(let[V,S]of X.headers)if(!rH.has(V.toLowerCase())&&V.toLowerCase()!=="host")y[V]=S;y.host=f,y["x-forwarded-for"]="127.0.0.1",y["x-forwarded-proto"]="https",y["x-forwarded-host"]=Q;let T={targetUrl:O,forwardHeaders:y};if(J.upgrade(X,{data:T})){F("ws",`upgraded ${Q}${R} → ${O}`,$);return}return new Response("WebSocket upgrade failed",{status:400})}let j=lG(B);if(!j)return new Response(`No upstream configured for ${Q}`,{status:502});if(B.cleanUrls&&U.endsWith(".html")){let N=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:N}})}let{targetHost:z,targetPath:G}=nG(U,B,j,$),K=B.changeOrigin?`http://${z}`:void 0,E=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",q=B.upstreamPool;if(q)j.activeConnections++;try{let N=await cG({hostPort:z,method:X.method,path:`${G}${W}`,reqHeaders:X.headers,forwardedHost:Q,originOverride:K,body:X.body});if(q)_8(q,j);return N}catch(N){if(N===ZW){if(F("request",`Upstream timeout for ${Q}`,$),q)bY(q,j);return new Response("Gateway Timeout",{status:504})}if(N===p$)return F("request",`Upstream pool saturated for ${Q}`,$),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(N===vY||!E)try{let f=new Headers(X.headers);if(f.set("host",z),f.set("x-forwarded-for","127.0.0.1"),f.set("x-forwarded-proto","https"),f.set("x-forwarded-host",Q),K!==void 0)f.set("origin",K);let R=await fetch(`http://${z}${G}${W}`,{method:X.method,headers:f,body:X.body,redirect:"manual"});if(q)_8(q,j);return R}catch(f){if(F("request",`Proxy error for ${Q}: ${f}`,$),q)bY(q,j);return new Response(`Proxy Error: ${f}`,{status:502})}if(F("request",`Proxy error for ${Q}: ${N}`,$),q)bY(q,j);return new Response(`Proxy Error: ${N}`,{status:502})}finally{if(q)j.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return F("request",`Unhandled proxy handler error: ${U}`,$),new Response("Bad Gateway",{status:502})}}}function s1(w){let $=new WeakMap,Y=pH();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(Q){F("ws",`failed to open upstream ${X}: ${Q}`,w),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let W={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};$.set(A,W),U.addEventListener("open",()=>{W.upstreamOpen=!0;for(let Q of W.pending)U.send(Q);W.pending=[],W.pendingBytes=0}),U.addEventListener("message",(Q)=>{A.send(Q.data)}),U.addEventListener("close",(Q)=>{try{A.close(Q.code||1000,Q.reason||"")}catch{}}),U.addEventListener("error",()=>{F("ws",`upstream error for ${X}`,w);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=$.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let W=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+W>Y){F("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,w);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}$.delete(A);return}J.pending.push(U),J.pendingBytes+=W},close(A,X,J){let U=$.get(A);if(!U)return;$.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var rH;var k8=t(()=>{cY();iG();mY();X0();rH=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 tG from"node:fs";import*as aG from"node:path";function gY(w,$){if(!w||!$.startsWith(rG))return null;let Y=$.slice(rG.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return tG.readFileSync(aG.join(w,Y),"utf8")}catch{return null}}var rG="/.well-known/acme-challenge/";var h8=()=>{};function Sw(w){if(!w||w==="/")return"/";let $=w.trim();if(!$.startsWith("/"))$=`/${$}`;return $=$.replace(/\/+$/,""),$===""?"/":$}function sH(w,$){if($==="/")return!0;if(w===$)return!0;return w.startsWith(`${$}/`)}function o1(w){let $=new Map;for(let A of w){let X=Sw(A.path),J=$.get(A.host);if(!J)J=new Map,$.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of $){let J=[];for(let[U,W]of X)J.push({path:U,route:W});J.sort((U,W)=>W.path.length-U.path.length),Y.set(A,J)}return Y}function D8(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!q1(J))continue;if(TY($,J)){let W=J.length-1;if(W>X)X=W,A=U}}return A}function e1(w,$,Y){let A=D8(w,$);if(!A)return;for(let X of A)if(sH(Y,X.path))return X.route;return}var dY=()=>{};import*as lY from"node:fs/promises";import*as kW from"node:path";function S$(w){if(Array.isArray(w))return w.map(($)=>({...$,lowMemoryMode:!0}));return{...w,lowMemoryMode:!0}}function oH(w){if(!w.endsWith(".crt"))return null;let $=w.slice(0,-4);if($.length===0)return null;if($.startsWith("_wildcard."))return`*.${$.slice(10)}`;return $}async function eH(w,$,Y,A){try{let[X,J]=await Promise.all([lY.readFile($,"utf8"),lY.readFile(Y,"utf8")]);return{serverName:w,cert:X,key:J}}catch(X){return F("sni",`skipping ${w}: ${X.message}`,A),null}}async function wY(w,$){let Y=new Map;if(w.certsDir){let X=[];try{X=await lY.readdir(w.certsDir)}catch(J){F("sni",`certsDir read failed (${w.certsDir}): ${J.message}`,$)}for(let J of X){let U=oH(J);if(!U)continue;let W=J.slice(0,-4);Y.set(U,{certPath:kW.join(w.certsDir,J),keyPath:kW.join(w.certsDir,`${W}.key`)})}}if(w.domains)for(let[X,J]of Object.entries(w.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await eH(X,J.certPath,J.keyPath,$);if(U)A.push(U)}return A}var x8=t(()=>{X0()});import*as Vw from"node:fs/promises";import*as P8 from"node:path";function YR(w,$){if(!$||$.length===0)return!1;return $.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return w===A||w.endsWith(`.${A}`)})}function oG(w){if(!w||w.length>253)return!1;if(w.includes("/")||w.includes(":")||w.includes(" "))return!1;if(w.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(w)}class r${config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(w){this.config=w.config,this.certsDir=w.certsDir,this.onCertAdded=w.onCertAdded,this.http01Store=w.http01Store??DX,this.issuer=w.issuer??jQ,this.verbose=w.verbose??!1,this.negativeCacheMs=w.negativeCacheMs??$R;for(let $ of w.initial??[])this.certs.set($.serverName,$)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(w){return this.certs.has(w)}async isApproved(w){if(!oG(w))return!1;if(YR(w,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(w)}catch($){return F("on-demand",`ask(${w}) threw: ${$.message}`,this.verbose),!1}return!1}async ensureCert(w){if(!this.config.enabled)return!1;if(this.certs.has(w))return!0;if(!oG(w))return!1;let $=this.inFlight.get(w);if($)return $;let Y=this.negativeCache.get(w);if(Y!==void 0&&Date.now()<Y){if(await this.loadFromDisk(w))return this.negativeCache.delete(w),!0;return F("on-demand",`${w} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1}let A=this.issue(w).finally(()=>{this.inFlight.delete(w)});return this.inFlight.set(w,A),A}async issue(w){if(this.certs.has(w))return!0;if(await this.loadFromDisk(w))return!0;if(!await this.isApproved(w))return F("on-demand",`refused issuance for ${w} (not approved)`,this.verbose),this.cacheNegative(w),!1;try{F("on-demand",`issuing cert for ${w} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let $=await this.issuer({domains:[w],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey($.accountKeyPem),await this.persist(w,$.fullChainPem,$.keyPem);let Y={serverName:w,cert:$.fullChainPem,key:$.keyPem};return this.certs.set(w,Y),this.negativeCache.delete(w),F("on-demand",`issued + installed cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch($){return this.cacheNegative(w),F("on-demand",`issuance for ${w} failed: ${$.message}`,this.verbose),!1}}cacheNegative(w){if(this.negativeCache.size>=sG){let $=Date.now();for(let[Y,A]of this.negativeCache)if(A<=$)this.negativeCache.delete(Y);if(this.negativeCache.size>=sG){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set(w,Date.now()+this.negativeCacheMs)}async loadFromDisk(w){let{certPath:$,keyPath:Y}=this.pathsFor(w);try{let[A,X]=await Promise.all([Vw.readFile($,"utf8"),Vw.readFile(Y,"utf8")]),J={serverName:w,cert:A,key:X};return this.certs.set(w,J),F("on-demand",`adopted existing on-disk cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(w){return{certPath:P8.join(this.certsDir,`${w}.crt`),keyPath:P8.join(this.certsDir,`${w}.key`)}}async persist(w,$,Y){await Vw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor(w);await Promise.all([Vw.writeFile(A,$,"utf8"),Vw.writeFile(X,Y,{encoding:"utf8",mode:384})])}get accountKeyPath(){return P8.join(this.certsDir,wR)}async loadAccountKey(){try{return await Vw.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(w){if(!w||this.accountKeyPem===w)return;this.accountKeyPem=w,await Vw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await Vw.writeFile(this.accountKeyPath,w,{encoding:"utf8",mode:384}).catch(()=>{})}}var wR="acme-account.key",$R=60000,sG=4096;var b8=t(()=>{mX();X0()});import{existsSync as AR,readdirSync as _L,readFileSync as XR,statSync as JR}from"node:fs";import{homedir as UR}from"node:os";import{isAbsolute as QR,join as $Y}from"node:path";function eG(w,$){if(w==="~")return $;if(w.startsWith("~/"))return $Y($,w.slice(2));return w}function zR(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function w5(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function GR(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function KR(w,$){let Y=$.readText($Y(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText($Y(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function FR(w){let $=w.selfRegisters??!1;return{command:w.command,env:w.env,urlEnv:w.urlEnv,selfRegisters:$,routes:w.routes??($?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function qR(w,$){let Y=KR(w,$);if(Y?.command)return FR(Y);let A=$.fileExists($Y(w,"buddy")),X=$.readText($Y(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((Q)=>Q==="stacks"||Q.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 DW(w,$={}){let Y={dirExists:$.dirExists??hW.dirExists,fileExists:$.fileExists??hW.fileExists,readText:$.readText??hW.readText},A=$.detect??qR,X=$.homeDir??UR(),J=w.tlds??BR,U=(w.roots??WR).map((G)=>eG(G,X)),W=w.idleTimeoutMs??jR,Q=new Map;for(let G of w.sites??[])Q.set(G.to,G);let B=(G)=>G.idleTimeoutMs??W;function j(G){let K=pA(Q,G);if(!K)return null;let E=QR(K.dir)?K.dir:eG(K.dir,X),q=K.selfRegisters??!1,N=K.routes??[];if(!q&&N.length===0)N=A(E,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let f=$5({...K.env??{}},void 0,G);return{host:G,id:w5(G),dir:E,command:K.command,env:f,routes:N,selfRegisters:q,idleTimeoutMs:B(K),source:"config"}}function z(G){let K=GR(G,J);if(!K)return null;for(let E of U){let q=$Y(E,K);if(!Y.dirExists(q))continue;let N=A(q,Y);if(!N)continue;let f=N.selfRegisters??!1;return{host:G,id:w5(G),dir:q,command:N.command,env:$5({...N.env??{}},N.urlEnv,G),routes:f?[]:N.routes??[],selfRegisters:f,idleTimeoutMs:W,source:"discovered"}}return null}return{resolve(G){let K=zR(G);if(!K)return null;return j(K)??z(K)}}}function $5(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}var WR,BR,jR=1800000,hW;var xW=t(()=>{WR=["~/Code"],BR=["localhost","test"],hW={dirExists:(w)=>{try{return JR(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return AR(w)}catch{return!1}},readText:(w)=>{try{return XR(w,"utf8")}catch{return null}}}});import*as u8 from"node:net";function Z$(w,$,Y){return F("port",`Checking if port ${w} is in use on ${$}`,Y),new Promise((A)=>{let X=u8.createServer(),J=setTimeout(()=>{F("port",`Checking port ${w} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")F("port",`Port ${w} is in use`,Y),A(!0);else F("port",`Error checking port ${w}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),F("port",`Port ${w} is available`,Y),X.close(),A(!1)});try{X.listen(w,$)}catch(U){clearTimeout(J),F("port",`Exception checking port ${w}: ${U}`,Y),A(!0)}})}async function PW(w,$,Y,A=50){F("port",`Finding available port starting from ${w} (max attempts: ${A})`,Y);let X=w,J=0;while(J<A){if(J++,!await Z$(X,$,Y))return F("port",`Found available port: ${X} after ${J} attempts`,Y),X;F("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${A})`,Y),X++}throw Error(`Unable to find available port after ${A} attempts starting from ${w}`)}function Y5(w,$,Y=5000,A){return F("port",`Testing connection to ${$}:${w}`,A),new Promise((X)=>{let J=u8.connect({host:$,port:w,timeout:Y});J.once("connect",()=>{F("port",`Successfully connected to ${$}:${w}`,A),J.end(),X(!0)}),J.once("timeout",()=>{F("port",`Connection to ${$}:${w} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{F("port",`Failed to connect to ${$}:${w}: ${U.message}`,A),J.destroy(),X(!1)})})}class c8{usedPorts=new Set;hostname;verbose;maxRetries;constructor(w="0.0.0.0",$,Y=50){this.hostname=w,this.verbose=$,this.maxRetries=Y}async getNextAvailablePort(w,$=!1){if(this.usedPorts.has(w))return this.findNextAvailablePort(w+1,$);if(await Z$(w,this.hostname,this.verbose))return this.findNextAvailablePort(w+1,$);if($){if(!await Y5(w,this.hostname,3000,this.verbose))return F("port",`Port ${w} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(w+1,$)}return this.usedPorts.add(w),w}async findNextAvailablePort(w,$=!1){let Y=await PW(w,this.hostname,this.verbose,this.maxRetries);if($){if(!await Y5(Y,this.hostname,3000,this.verbose))if(Y<w+this.maxRetries)return this.findNextAvailablePort(Y+1,$);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort(w){F("port",`Releasing port ${w}`,this.verbose),this.usedPorts.delete(w)}}var xL;var bW=t(()=>{X0();xL=new c8});import*as v8 from"node:fs";import*as r0 from"node:fs/promises";import{homedir as NR}from"node:os";import*as uW from"node:path";import*as i8 from"node:process";function kw(){return uW.join(NR(),".stacks","rpx","registry.d")}function nY(w){return typeof w==="string"&&w.length>0&&w.length<=128&&ER.test(w)}function cW(w,$){if(!nY($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return uW.join(w,`${$}.json`)}function b0(w){if(!Number.isInteger(w)||w<=0)return!1;try{return i8.kill(w,0),!0}catch($){return $.code==="EPERM"}}function A5(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&nY($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function fR(w){await r0.mkdir(w,{recursive:!0})}async function m8(w,$=kw(),Y){if(!A5(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await fR($);let A=cW($,w.id),X=`${A}.tmp.${i8.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await r0.writeFile(X,J,{encoding:"utf8",mode:420}),await r0.rename(X,A),F("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await r0.unlink(X).catch(()=>{}),U}}async function pY(w,$=kw(),Y){let A=cW($,w);try{await r0.unlink(A),F("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function TR(w,$=kw(),Y){let A=cW($,w);try{let X=await r0.readFile(A,"utf8"),J=JSON.parse(X);if(!A5(J))return F("registry",`entry ${w} failed validation, removing`,Y),await r0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return F("registry",`entry ${w} has invalid JSON, removing`,Y),await r0.unlink(A).catch(()=>{}),null;throw X}}async function Zw(w=kw(),$){let Y;try{Y=await r0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!nY(J))continue;let U=await TR(J,w,$);if(U)A.push(U)}return A}async function YY(w=kw(),$){let Y=await Zw(w,$),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!b0(X.pid))F("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,$),await pY(X.id,w,$).catch(()=>{}),A++}return A}function rY(w,$={}){let Y=$.dir??kw(),A=$.debounceMs??100,X=$.pollMs??Math.max(A*2,250),J=$.verbose;v8.mkdirSync(Y,{recursive:!0});let U=null,W=!1,Q=null,B=!1,j=(N)=>{return JSON.stringify(N.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,R)=>f.id.localeCompare(R.id)))},z=()=>{if(U=null,W)return;Zw(Y,J).then((N)=>{return Q=j(N),w(N)}).catch((N)=>{F("registry",`watcher onChange failed: ${N}`,J)})},G=()=>{if(W)return;if(U)clearTimeout(U);U=setTimeout(z,A)},E=setInterval(()=>{if(W||B)return;B=!0,Zw(Y,J).then((N)=>{if(j(N)!==Q)G()}).catch((N)=>{F("registry",`watcher poll failed: ${N}`,J)}).finally(()=>{B=!1})},X),q=v8.watch(Y,{persistent:!0},(N,f)=>{if(f&&/\.tmp\.\d+\.\d+$/.test(f))return;G()});return q.on("error",(N)=>{F("registry",`watcher error: ${N}`,J)}),G(),{close:()=>{if(W=!0,U)clearTimeout(U);clearInterval(E),q.close()}}}var ER;var t$=t(()=>{X0();ER=/^[a-zA-Z0-9._-]+$/});import{closeSync as X5,openSync as HR,readFileSync as RR}from"node:fs";import*as J5 from"node:fs/promises";import{spawn as MR}from"node:child_process";import{homedir as IR}from"node:os";import*as tY from"node:path";import*as Cw from"node:process";class g8{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(w){this.resolver=w.resolver,this.registryDir=w.registryDir??kw(),this.rpxDir=w.rpxDir??tY.join(IR(),".stacks","rpx"),this.verbose=w.verbose??!1,this.startupTimeoutMs=w.startupTimeoutMs??VR,this.pollIntervalMs=w.pollIntervalMs??CR,this.restartDelayMs=w.restartDelayMs??OR,this.killGraceMs=w.killGraceMs??LR,this.launch=w.launcher??SR(this.verbose),this.probePort=w.probePort??_R,this.pickPort=w.pickPort??((Y)=>PW(Y,"127.0.0.1")),this.isHostRoutable=w.isHostRoutable??(()=>!1),this.onSiteActivating=w.onSiteActivating,this.now=w.now??Date.now,this.writeEntry=w.writeEntry??m8,this.removeEntry=w.removeEntry??pY;let $=w.reapIntervalMs??yR;if(this.reaper=setInterval(()=>{this.reapIdle()},$),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(w){if(this.stopped)return{kind:"unknown"};let $=this.sites.get(w);if($&&$.status==="failed"&&this.now()-$.failedAt>=this.restartDelayMs)this.sites.delete(w),$=void 0;if(!$){let Y=this.resolver.resolve(w);if(!Y)return{kind:"unknown"};$=await this.start(Y)}if($.lastAccess=this.now(),$.status==="ready")return{kind:"ready",host:w};if($.status==="failed")return{kind:"failed",host:w,error:$.error??"failed to start",logTail:this.readLogTail($)};return{kind:"starting",host:w,sinceMs:this.now()-$.startedAt,source:$.site.source,logTail:this.readLogTail($,16)}}async start(w){try{this.onSiteActivating?.(w.host)}catch{}let $=new Map;if(!w.selfRegisters)for(let W of w.routes){if($.has(W.portEnv))continue;let Q=await this.pickPort(W.defaultPort??3000);$.set(W.portEnv,Q)}let Y=tY.join(this.rpxDir,"sites",`${w.id}.log`);await J5.mkdir(tY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv(w,$),X=null,J;try{X=this.launch({command:w.command,cwd:w.dir,env:A,logPath:Y})}catch(W){J=`failed to spawn: ${W.message}`}let U={site:w,status:J?"failed":"starting",handle:X,ports:$,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:J?this.now():0,error:J,logPath:Y,exited:!1,ready:Promise.resolve()};if(this.sites.set(w.host,U),J)return H.warn(`rpx: site ${w.host} ${J}`),U;return H.info(`rpx: booting ${w.host} → ${w.command} (${w.dir})`),X.exited.then((W)=>this.onProcessExit(U,W)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((W)=>{F("sites",`readiness loop for ${w.host} threw: ${W}`,this.verbose)}),U}async onProcessExit(w,$){if(w.exited=!0,this.stopped||this.sites.get(w.site.host)!==w)return;if(w.status==="ready"){H.warn(`rpx: ${w.site.host} exited${$!==null?` (code ${$})`:""} — will reboot on next request`),this.sites.delete(w.site.host);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if(w.status==="starting")this.fail(w,`process exited${$!==null?` with code ${$}`:""} before becoming ready`)}async driveReadiness(w){let{site:$}=w,Y=this.now()+this.startupTimeoutMs,A=$.selfRegisters?()=>this.isHostRoutable($.host):await this.makeGateProbe($,w.ports);while(this.now()<Y&&!this.stopped){if(w.status!=="starting"||w.exited)return;if(await A()){if(await this.publishRoutes(w),w.status==="starting")w.status="ready",H.success(`rpx: ${$.host} ready`);return}await vW(this.pollIntervalMs)}if(w.status==="starting")this.fail(w,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(w,$){let Y=w.routes.filter((X)=>X.readyGate??Sw(X.path)==="/").map((X)=>$.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...$.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes(w){let{site:$,ports:Y}=w;if($.selfRegisters||$.routes.length===0)return;let A=$.routes.find((Q)=>Sw(Q.path)==="/")??$.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let Q of $.routes){if(Q===A)continue;let B=Y.get(Q.portEnv);if(B===void 0)continue;J.push({from:Sw(Q.path),to:`localhost:${B}`,stripPrefix:Q.stripPrefix??!1})}let U={id:$.id,from:`localhost:${X}`,to:$.host,cwd:$.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:w.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),w.routeIds=[$.id];let W=this.now()+2000;while(this.now()<W&&!this.isHostRoutable($.host))await vW(50)}fail(w,$){w.status="failed",w.error=$,w.failedAt=this.now(),H.warn(`rpx: site ${w.site.host} failed — ${$}`),this.killProcess(w)}buildEnv(w,$){let Y={};for(let[A,X]of Object.entries(Cw.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,w.env);for(let[A,X]of $)Y[A]=String(X);return Y.RPX_SITE_HOST=w.host,Y.RPX_SITE_URL=`https://${w.host}`,Y}readLogTail(w,$=40){try{return RR(w.logPath,"utf8").split(`
227
+ `;if(J!==void 0)Q+=`origin: ${J}\r
228
+ `;let W=!1;for(let[j,B]of Y){let f=j.toLowerCase();if(AH.has(f))continue;if(J!==void 0&&f==="origin")continue;if(f==="content-length")W=!0;Q+=`${j}: ${B}\r
229
+ `}if(Q+=`connection: keep-alive\r
230
+ `,U&&!W)Q+=`content-length: ${U.length}\r
231
+ `;return Q+=`\r
232
+ `,YH.encode(Q)}async function GH(w){let $=w.getReader(),Y=[],A=0;for(;;){let{done:U,value:Q}=await $.read();if(U)break;if(Q){if(A+=Q.length,A>T2)return $.cancel().catch(()=>{}),null;Y.push(Q)}}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 gN,LY,F8,dN,fQ,v$,T2=1048576,BQ=30000,sN=16384,q2=262144,oN=2097152,eN=524288,wH=8192,$H=4096,YH,N2,AH,T8;var I2=a(()=>{({connect:gN}=Bun),LY=Symbol("rpx.pool.fallback"),F8=Symbol("rpx.pool.stale"),dN=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);fQ=Symbol("rpx.pool.timeout"),v$=Symbol("rpx.pool.busy");YH=new TextEncoder,N2=new TextDecoder,AH=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);T8=new Map});function C2(w){let $=typeof w==="string"?{to:w}:w,Y=($.to??"").trim();if(Y&&!/^[a-z][\w+.-]*:\/\//i.test(Y))Y=`https://${Y}`;return Y=Y.replace(/\/+$/,""),{to:Y,status:$.status??301,preservePath:$.preservePath??!0}}function V2(w,$,Y){if(!w.preservePath)return w.to||"/";let A=`${$}${Y}`;return A==="/"?`${w.to}/`:`${w.to}${A}`}import*as fw from"node:path";function q8(w,$){if(typeof w==="string")return{dir:w,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:$};return{dir:w.dir,spa:w.spa??!1,pathRewriteStyle:w.pathRewriteStyle??"directory",maxAge:w.maxAge??0,cleanUrls:$}}function KH(w){let $=fw.extname(w).toLowerCase();return EH[$]??"application/octet-stream"}function FH(w){let $;try{$=decodeURIComponent(w)}catch{return null}if($.includes("\x00")||$.includes("\\"))return null;let Y=fw.posix.normalize(`/${$}`);if(Y.split("/").includes(".."))return null;return Y.replace(/^\/+/,"")}function TH(w,$){let Y=FH(w);if(Y===null)return null;let A=fw.posix.extname(Y);if($.cleanUrls&&A===".html"){let X=w.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:fw.join($.dir,Y),redirectTo:X||"/"}}if(Y===""||w.endsWith("/"))return{filePath:fw.join($.dir,Y,"index.html")};if(A!=="")return{filePath:fw.join($.dir,Y)};if($.pathRewriteStyle==="flat")return{filePath:fw.join($.dir,`${Y}.html`)};return{filePath:fw.join($.dir,Y,"index.html")}}async function L2(w,$){let Y=TH(w,$);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=$.maxAge>0?`public, max-age=${$.maxAge}`:"no-cache",X=Bun.file(Y.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":KH(Y.filePath),"Cache-Control":A}});if($.spa){let J=fw.join($.dir,"index.html"),U=Bun.file(J);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var EH;var N8=a(()=>{EH={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"}});function qH(){return Math.max(0,Number(process.env.RPX_MAX_WS_PENDING_BYTES))||8388608}function HH(w){let $=w.headers.get("host")||"",Y=$.indexOf(":");return Y===-1?$:$.slice(0,Y)}function h2(w,$){if(!$||$==="/")return w;if(w===$)return"/";if(w.startsWith(`${$}/`)){let Y=w.slice($.length);return Y===""?"/":Y}return w}function S2(w){if(w.upstreamPool)return z2(w.upstreamPool);if(w.sourceHost)return{url:w.sourceHost,weight:1,healthy:!0,activeConnections:0,consecutiveFailures:0,consecutiveSuccesses:0};return}function O2(w,$,Y,A){let X=Y?.url??$.sourceHost??"",U=$.stripBasePathPrefix??!1?h2(w,$.basePath):w,Q=oW(U,$.pathRewrites);if(Q)X=Q.targetHost,U=Q.targetPath,E("request",`Path rewrite: ${w} → ${X}${U}`,A);return{targetHost:X,targetPath:U}}function RH(w){let $=w.indexOf("://"),Y=$===-1?w.indexOf("/"):w.indexOf("/",$+3);if(Y===-1)return{pathname:"/",search:""};let A=w.indexOf("?",Y);if(A===-1)return{pathname:w.slice(Y),search:""};return{pathname:w.slice(Y,A),search:w.slice(A)}}function SY(w,$,Y){let A=async(X,J)=>{let{pathname:U,search:Q}=RH(X.url),W=HH(X),j=w(W,U);if(!j&&Y){let F=await Y(W,U,X);if(F instanceof Response)return F;if(F&&F.retry)j=w(W,U)}if(!j)return E("request",`No route found for host: ${W}`,$),new Response(`No proxy configured for ${W}`,{status:404});if(j.auth){let F=K2(X,U,j.auth);if(F)return E("request",`401 challenge for ${W}${U}`,$),F}if(j.redirect){let F=V2(j.redirect,U,Q);return E("request",`${j.redirect.status} redirect ${W}${U} → ${F}`,$),new Response(null,{status:j.redirect.status,headers:{location:F}})}if(j.static){let q=j.stripBasePathPrefix??!0?h2(U,j.basePath):U;return L2(q,j.static)}if(X.headers.get("upgrade")?.toLowerCase()==="websocket"){let F=S2(j);if(!J||!F)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:q,targetPath:R}=O2(U,j,F,$),L=`ws://${q}${R}${Q}`,V={};for(let[C,h]of X.headers)if(!NH.has(C.toLowerCase())&&C.toLowerCase()!=="host")V[C]=h;V.host=q,V["x-forwarded-for"]="127.0.0.1",V["x-forwarded-proto"]="https",V["x-forwarded-host"]=W;let N={targetUrl:L,forwardHeaders:V};if(J.upgrade(X,{data:N})){E("ws",`upgraded ${W}${R} → ${L}`,$);return}return new Response("WebSocket upgrade failed",{status:400})}let B=S2(j);if(!B)return new Response(`No upstream configured for ${W}`,{status:502});if(j.cleanUrls&&U.endsWith(".html")){let F=U.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:F}})}let{targetHost:f,targetPath:z}=O2(U,j,B,$),G=j.changeOrigin?`http://${f}`:void 0,T=X.body!=null&&X.method!=="GET"&&X.method!=="HEAD",K=j.upstreamPool;if(K)B.activeConnections++;try{let F=await M2({hostPort:f,method:X.method,path:`${z}${Q}`,reqHeaders:X.headers,forwardedHost:W,originOverride:G,body:X.body});if(K)E8(K,B);return F}catch(F){if(F===fQ){if(E("request",`Upstream timeout for ${W}`,$),K)yY(K,B);return new Response("Gateway Timeout",{status:504})}if(F===v$)return E("request",`Upstream pool saturated for ${W}`,$),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(F===LY||!T)try{let q=new Headers(X.headers);if(q.set("host",f),q.set("x-forwarded-for","127.0.0.1"),q.set("x-forwarded-proto","https"),q.set("x-forwarded-host",W),G!==void 0)q.set("origin",G);let R=await fetch(`http://${f}${z}${Q}`,{method:X.method,headers:q,body:X.body,redirect:"manual"});if(K)E8(K,B);return R}catch(q){if(E("request",`Proxy error for ${W}: ${q}`,$),K)yY(K,B);return new Response(`Proxy Error: ${q}`,{status:502})}if(E("request",`Proxy error for ${W}: ${F}`,$),K)yY(K,B);return new Response(`Proxy Error: ${F}`,{status:502})}finally{if(K)B.activeConnections--}};return async(X,J)=>{try{return await A(X,J)}catch(U){return E("request",`Unhandled proxy handler error: ${U}`,$),new Response("Bad Gateway",{status:502})}}}function OY(w){let $=new WeakMap,Y=qH();return{open(A){let{targetUrl:X,forwardHeaders:J}=A.data,U;try{U=new WebSocket(X,{headers:J})}catch(W){E("ws",`failed to open upstream ${X}: ${W}`,w),A.close(1011,"upstream connect failed");return}U.binaryType="arraybuffer";let Q={upstream:U,upstreamOpen:!1,pending:[],pendingBytes:0};$.set(A,Q),U.addEventListener("open",()=>{Q.upstreamOpen=!0;for(let W of Q.pending)U.send(W);Q.pending=[],Q.pendingBytes=0}),U.addEventListener("message",(W)=>{A.send(W.data)}),U.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),U.addEventListener("error",()=>{E("ws",`upstream error for ${X}`,w);try{A.close(1011,"upstream error")}catch{}})},message(A,X){let J=$.get(A);if(!J)return;let U=typeof X==="string"?X:new Uint8Array(X);if(J.upstreamOpen){J.upstream.send(U);return}let Q=typeof U==="string"?Buffer.byteLength(U):U.byteLength;if(J.pendingBytes+Q>Y){E("ws",`pending buffer would exceed ${Y}B before upstream open; closing socket`,w);try{A.close(1009,"buffer limit")}catch{}try{J.upstream.close(1011,"client buffer overflow")}catch{}$.delete(A);return}J.pending.push(U),J.pendingBytes+=Q},close(A,X,J){let U=$.get(A);if(!U)return;$.delete(A);try{U.upstream.close(X||1000,J||"")}catch{}}}}var NH;var zQ=a(()=>{K8();I2();N8();f0();NH=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 D2 from"node:fs";import*as k2 from"node:path";function H8(w,$){if(!w||!$.startsWith(_2))return null;let Y=$.slice(_2.length);if(!Y||!/^[A-Za-z0-9_-]+$/.test(Y))return null;try{return D2.readFileSync(k2.join(w,Y),"utf8")}catch{return null}}var _2="/.well-known/acme-challenge/";var GQ=()=>{};function X$(w){if(!w||w==="/")return"/";let $=w.trim();if(!$.startsWith("/"))$=`/${$}`;return $=$.replace(/\/+$/,""),$===""?"/":$}function MH(w,$){if($==="/")return!0;if(w===$)return!0;return w.startsWith(`${$}/`)}function hY(w){let $=new Map;for(let A of w){let X=X$(A.path),J=$.get(A.host);if(!J)J=new Map,$.set(A.host,J);J.set(X,A.route)}let Y=new Map;for(let[A,X]of $){let J=[];for(let[U,Q]of X)J.push({path:U,route:Q});J.sort((U,Q)=>Q.path.length-U.path.length),Y.set(A,J)}return Y}function EQ(w,$){let Y=w.get($);if(Y!==void 0)return Y;let A,X=-1;for(let[J,U]of w){if(!Q1(J))continue;if($Y($,J)){let Q=J.length-1;if(Q>X)X=Q,A=U}}return A}function _Y(w,$,Y){let A=EQ(w,$);if(!A)return;for(let X of A)if(MH(Y,X.path))return X.route;return}var R8=()=>{};import*as DY from"node:fs/promises";import*as KQ from"node:path";function c$(w){if(Array.isArray(w))return w.map(($)=>({...$,lowMemoryMode:!0}));return{...w,lowMemoryMode:!0}}function yH(w){if(!w.endsWith(".crt"))return null;let $=w.slice(0,-4);if($.length===0)return null;if($.startsWith("_wildcard."))return`*.${$.slice(10)}`;return $}async function IH(w,$,Y,A){try{let[X,J]=await Promise.all([DY.readFile($,"utf8"),DY.readFile(Y,"utf8")]);return{serverName:w,cert:X,key:J}}catch(X){return E("sni",`skipping ${w}: ${X.message}`,A),null}}async function kY(w,$){let Y=new Map;if(w.certsDir){let X=[];try{X=await DY.readdir(w.certsDir)}catch(J){E("sni",`certsDir read failed (${w.certsDir}): ${J.message}`,$)}for(let J of X){let U=yH(J);if(!U)continue;let Q=J.slice(0,-4);Y.set(U,{certPath:KQ.join(w.certsDir,J),keyPath:KQ.join(w.certsDir,`${Q}.key`)})}}if(w.domains)for(let[X,J]of Object.entries(w.domains))Y.set(X,J);let A=[];for(let[X,J]of Y){let U=await IH(X,J.certPath,J.keyPath,$);if(U)A.push(U)}return A}var FQ=a(()=>{f0()});import*as yw from"node:fs/promises";import*as M8 from"node:path";function ZY(w=process.env){let $=w.RPX_TLS_RELOAD_STRATEGY?.trim().toLowerCase();if($==="restart"||$==="rebind")return $;return w.INVOCATION_ID?"restart":"rebind"}function LH(w,$){if(!$||$.length===0)return!1;return $.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return w===A||w.endsWith(`.${A}`)})}function x2(w){if(!w||w.length>253)return!1;if(w.includes("/")||w.includes(":")||w.includes(" "))return!1;if(w.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(w)}class u1{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;accountKeyPem;constructor(w){this.config=w.config,this.certsDir=w.certsDir,this.onCertAdded=w.onCertAdded,this.http01Store=w.http01Store??MX,this.issuer=w.issuer??rU,this.verbose=w.verbose??!1,this.negativeCacheMs=w.negativeCacheMs??VH;for(let $ of w.initial??[])this.certs.set($.serverName,$)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert(w){return this.certs.has(w)}async isApproved(w){if(!x2(w))return!1;if(LH(w,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask(w)}catch($){return E("on-demand",`ask(${w}) threw: ${$.message}`,this.verbose),!1}return!1}async ensureCert(w){if(!this.config.enabled)return!1;if(this.certs.has(w))return!0;if(!x2(w))return!1;let $=this.inFlight.get(w);if($)return $;let Y=this.negativeCache.get(w);if(Y!==void 0&&Date.now()<Y){if(await this.loadFromDisk(w))return this.negativeCache.delete(w),!0;return E("on-demand",`${w} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1}let A=this.issue(w).finally(()=>{this.inFlight.delete(w)});return this.inFlight.set(w,A),A}async issue(w){if(this.certs.has(w))return!0;if(await this.loadFromDisk(w))return!0;if(!await this.isApproved(w))return E("on-demand",`refused issuance for ${w} (not approved)`,this.verbose),this.cacheNegative(w),!1;try{E("on-demand",`issuing cert for ${w} (staging=${this.config.staging??!1})`,this.verbose),this.accountKeyPem??=await this.loadAccountKey();let $=await this.issuer({domains:[w],method:"http-01",http01Store:this.http01Store,email:this.config.email,accountKeyPem:this.accountKeyPem,staging:this.config.staging??!1});await this.saveAccountKey($.accountKeyPem),await this.persist(w,$.fullChainPem,$.keyPem);let Y={serverName:w,cert:$.fullChainPem,key:$.keyPem};return this.certs.set(w,Y),this.negativeCache.delete(w),E("on-demand",`issued + installed cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch($){return this.cacheNegative(w),E("on-demand",`issuance for ${w} failed: ${$.message}`,this.verbose),!1}}cacheNegative(w){if(this.negativeCache.size>=Z2){let $=Date.now();for(let[Y,A]of this.negativeCache)if(A<=$)this.negativeCache.delete(Y);if(this.negativeCache.size>=Z2){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set(w,Date.now()+this.negativeCacheMs)}async loadFromDisk(w){let{certPath:$,keyPath:Y}=this.pathsFor(w);try{let[A,X]=await Promise.all([yw.readFile($,"utf8"),yw.readFile(Y,"utf8")]),J={serverName:w,cert:A,key:X};return this.certs.set(w,J),E("on-demand",`adopted existing on-disk cert for ${w}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor(w){return{certPath:M8.join(this.certsDir,`${w}.crt`),keyPath:M8.join(this.certsDir,`${w}.key`)}}async persist(w,$,Y){await yw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:X}=this.pathsFor(w);await Promise.all([yw.writeFile(A,$,"utf8"),yw.writeFile(X,Y,{encoding:"utf8",mode:384})])}get accountKeyPath(){return M8.join(this.certsDir,CH)}async loadAccountKey(){try{return await yw.readFile(this.accountKeyPath,"utf8")}catch{return}}async saveAccountKey(w){if(!w||this.accountKeyPem===w)return;this.accountKeyPem=w,await yw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{}),await yw.writeFile(this.accountKeyPath,w,{encoding:"utf8",mode:384}).catch(()=>{})}}var CH="acme-account.key",VH=60000,Z2=4096;var TQ=a(()=>{hX();f0()});import*as y8 from"node:net";function I$(w,$,Y){return E("port",`Checking if port ${w} is in use on ${$}`,Y),new Promise((A)=>{let X=y8.createServer(),J=setTimeout(()=>{E("port",`Checking port ${w} timed out, assuming it's in use`,Y),X.close(),A(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")E("port",`Port ${w} is in use`,Y),A(!0);else E("port",`Error checking port ${w}: ${U.message}`,Y),A(!0)}),X.once("listening",()=>{clearTimeout(J),E("port",`Port ${w} is available`,Y),X.close(),A(!1)});try{X.listen(w,$)}catch(U){clearTimeout(J),E("port",`Exception checking port ${w}: ${U}`,Y),A(!0)}})}async function qQ(w,$,Y,A=50){E("port",`Finding available port starting from ${w} (max attempts: ${A})`,Y);let X=w,J=0;while(J<A){if(J++,!await I$(X,$,Y))return E("port",`Found available port: ${X} after ${J} attempts`,Y),X;E("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${A})`,Y),X++}throw Error(`Unable to find available port after ${A} attempts starting from ${w}`)}function P2(w,$,Y=5000,A){return E("port",`Testing connection to ${$}:${w}`,A),new Promise((X)=>{let J=y8.connect({host:$,port:w,timeout:Y});J.once("connect",()=>{E("port",`Successfully connected to ${$}:${w}`,A),J.end(),X(!0)}),J.once("timeout",()=>{E("port",`Connection to ${$}:${w} timed out`,A),J.destroy(),X(!1)}),J.once("error",(U)=>{E("port",`Failed to connect to ${$}:${w}: ${U.message}`,A),J.destroy(),X(!1)})})}class I8{usedPorts=new Set;hostname;verbose;maxRetries;constructor(w="0.0.0.0",$,Y=50){this.hostname=w,this.verbose=$,this.maxRetries=Y}async getNextAvailablePort(w,$=!1){if(this.usedPorts.has(w))return this.findNextAvailablePort(w+1,$);if(await I$(w,this.hostname,this.verbose))return this.findNextAvailablePort(w+1,$);if($){if(!await P2(w,this.hostname,3000,this.verbose))return E("port",`Port ${w} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort(w+1,$)}return this.usedPorts.add(w),w}async findNextAvailablePort(w,$=!1){let Y=await qQ(w,this.hostname,this.verbose,this.maxRetries);if($){if(!await P2(Y,this.hostname,3000,this.verbose))if(Y<w+this.maxRetries)return this.findNextAvailablePort(Y+1,$);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort(w){E("port",`Releasing port ${w}`,this.verbose),this.usedPorts.delete(w)}}var LL;var NQ=a(()=>{f0();LL=new I8});import*as C8 from"node:fs";import*as p0 from"node:fs/promises";import{homedir as SH}from"node:os";import*as HQ from"node:path";import*as V8 from"node:process";function $w(){return HQ.join(SH(),".stacks","rpx","registry.d")}function C$(w){return typeof w==="string"&&w.length>0&&w.length<=128&&OH.test(w)}function RQ(w,$){if(!C$($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return HQ.join(w,`${$}.json`)}function Yw(w){if(!Number.isInteger(w)||w<=0)return!1;try{return V8.kill(w,0),!0}catch($){return $.code==="EPERM"}}function i2(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&C$($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function hH(w){await p0.mkdir(w,{recursive:!0})}async function v1(w,$=$w(),Y){if(!i2(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await hH($);let A=RQ($,w.id),X=`${A}.tmp.${V8.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await p0.writeFile(X,J,{encoding:"utf8",mode:420}),await p0.rename(X,A),E("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await p0.unlink(X).catch(()=>{}),U}}async function m$(w,$=$w(),Y){let A=RQ($,w);try{await p0.unlink(A),E("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function MQ(w,$=$w(),Y){let A=RQ($,w);try{let X=await p0.readFile(A,"utf8"),J=JSON.parse(X);if(!i2(J))return E("registry",`entry ${w} failed validation, removing`,Y),await p0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return E("registry",`entry ${w} has invalid JSON, removing`,Y),await p0.unlink(A).catch(()=>{}),null;throw X}}async function zw(w=$w(),$){let Y;try{Y=await p0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!C$(J))continue;let U=await MQ(J,w,$);if(U)A.push(U)}return A}async function xY(w=$w(),$){let Y=await zw(w,$),A=0;for(let X of Y){if(X.pid===void 0)continue;if(!Yw(X.pid))E("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,$),await m$(X.id,w,$).catch(()=>{}),A++}return A}function L8(w,$={}){let Y=$.dir??$w(),A=$.debounceMs??100,X=$.pollMs??Math.max(A*2,250),J=$.verbose;C8.mkdirSync(Y,{recursive:!0});let U=null,Q=!1,W=null,j=!1,B=(F)=>{return JSON.stringify(F.map((q)=>({id:q.id,from:q.from,to:q.to,path:q.path,pid:q.pid,pathRewrites:q.pathRewrites,cleanUrls:q.cleanUrls,changeOrigin:q.changeOrigin,static:q.static,loadBalancer:q.loadBalancer})).sort((q,R)=>q.id.localeCompare(R.id)))},f=()=>{if(U=null,Q)return;zw(Y,J).then((F)=>{return W=B(F),w(F)}).catch((F)=>{E("registry",`watcher onChange failed: ${F}`,J)})},z=()=>{if(Q)return;if(U)clearTimeout(U);U=setTimeout(f,A)},T=setInterval(()=>{if(Q||j)return;j=!0,zw(Y,J).then((F)=>{if(B(F)!==W)z()}).catch((F)=>{E("registry",`watcher poll failed: ${F}`,J)}).finally(()=>{j=!1})},X),K=C8.watch(Y,{persistent:!0},(F,q)=>{if(q&&/\.tmp\.\d+\.\d+$/.test(q))return;z()});return K.on("error",(F)=>{E("registry",`watcher error: ${F}`,J)}),z(),{close:()=>{if(Q=!0,U)clearTimeout(U);clearInterval(T),K.close()}}}var OH;var g$=a(()=>{f0();OH=/^[a-zA-Z0-9._-]+$/});import{closeSync as b2,openSync as _H,readFileSync as DH}from"node:fs";import*as u2 from"node:fs/promises";import{spawn as kH}from"node:child_process";import{homedir as ZH}from"node:os";import*as PY from"node:path";import*as Iw from"node:process";class IQ{resolver;registryDir;rpxDir;verbose;startupTimeoutMs;pollIntervalMs;restartDelayMs;killGraceMs;launch;probePort;pickPort;isHostRoutable;onSiteActivating;now;writeEntry;removeEntry;sites=new Map;reaper;stopped=!1;constructor(w){this.resolver=w.resolver,this.registryDir=w.registryDir??$w(),this.rpxDir=w.rpxDir??PY.join(ZH(),".stacks","rpx"),this.verbose=w.verbose??!1,this.startupTimeoutMs=w.startupTimeoutMs??xH,this.pollIntervalMs=w.pollIntervalMs??PH,this.restartDelayMs=w.restartDelayMs??bH,this.killGraceMs=w.killGraceMs??uH,this.launch=w.launcher??cH(this.verbose),this.probePort=w.probePort??vH,this.pickPort=w.pickPort??((Y)=>qQ(Y,"127.0.0.1")),this.isHostRoutable=w.isHostRoutable??(()=>!1),this.onSiteActivating=w.onSiteActivating,this.now=w.now??Date.now,this.writeEntry=w.writeEntry??v1,this.removeEntry=w.removeEntry??m$;let $=w.reapIntervalMs??iH;if(this.reaper=setInterval(()=>{this.reapIdle()},$),typeof this.reaper.unref==="function")this.reaper.unref()}async onRequest(w){if(this.stopped)return{kind:"unknown"};let $=this.sites.get(w);if($&&$.status==="failed"&&this.now()-$.failedAt>=this.restartDelayMs)this.sites.delete(w),$=void 0;if(!$){let Y=this.resolver.resolve(w);if(!Y)return{kind:"unknown"};$=await this.start(Y)}if($.lastAccess=this.now(),$.status==="ready")return{kind:"ready",host:w};if($.status==="failed")return{kind:"failed",host:w,error:$.error??"failed to start",logTail:this.readLogTail($)};return{kind:"starting",host:w,sinceMs:this.now()-$.startedAt,source:$.site.source,logTail:this.readLogTail($,16)}}async start(w){try{this.onSiteActivating?.(w.host)}catch{}let $=new Map;if(!w.selfRegisters)for(let Q of w.routes){if($.has(Q.portEnv))continue;let W=await this.pickPort(Q.defaultPort??3000);$.set(Q.portEnv,W)}let Y=PY.join(this.rpxDir,"sites",`${w.id}.log`);await u2.mkdir(PY.dirname(Y),{recursive:!0}).catch(()=>{});let A=this.buildEnv(w,$),X=null,J;try{X=this.launch({command:w.command,cwd:w.dir,env:A,logPath:Y})}catch(Q){J=`failed to spawn: ${Q.message}`}let U={site:w,status:J?"failed":"starting",handle:X,ports:$,routeIds:[],startedAt:this.now(),lastAccess:this.now(),failedAt:J?this.now():0,error:J,logPath:Y,exited:!1,ready:Promise.resolve()};if(this.sites.set(w.host,U),J)return H.warn(`rpx: site ${w.host} ${J}`),U;return H.info(`rpx: booting ${w.host} → ${w.command} (${w.dir})`),X.exited.then((Q)=>this.onProcessExit(U,Q)).catch(()=>{}),U.ready=this.driveReadiness(U).catch((Q)=>{E("sites",`readiness loop for ${w.host} threw: ${Q}`,this.verbose)}),U}async onProcessExit(w,$){if(w.exited=!0,this.stopped||this.sites.get(w.site.host)!==w)return;if(w.status==="ready"){H.warn(`rpx: ${w.site.host} exited${$!==null?` (code ${$})`:""} — will reboot on next request`),this.sites.delete(w.site.host);for(let Y of w.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{})}else if(w.status==="starting")this.fail(w,`process exited${$!==null?` with code ${$}`:""} before becoming ready`)}async driveReadiness(w){let{site:$}=w,Y=this.now()+this.startupTimeoutMs,A=$.selfRegisters?()=>this.isHostRoutable($.host):await this.makeGateProbe($,w.ports);while(this.now()<Y&&!this.stopped){if(w.status!=="starting"||w.exited)return;if(await A()){if(await this.publishRoutes(w),w.status==="starting")w.status="ready",H.success(`rpx: ${$.host} ready`);return}await yQ(this.pollIntervalMs)}if(w.status==="starting")this.fail(w,`did not become ready within ${Math.round(this.startupTimeoutMs/1000)}s`)}async makeGateProbe(w,$){let Y=w.routes.filter((X)=>X.readyGate??X$(X.path)==="/").map((X)=>$.get(X.portEnv)).filter((X)=>typeof X==="number"),A=Y.length>0?Y:[...$.values()];return async()=>{for(let X of A)if(!await this.probePort(X))return!1;return A.length>0}}async publishRoutes(w){let{site:$,ports:Y}=w;if($.selfRegisters||$.routes.length===0)return;let A=$.routes.find((W)=>X$(W.path)==="/")??$.routes[0],X=Y.get(A.portEnv);if(X===void 0)return;let J=[];for(let W of $.routes){if(W===A)continue;let j=Y.get(W.portEnv);if(j===void 0)continue;J.push({from:X$(W.path),to:`localhost:${j}`,stripPrefix:W.stripPrefix??!1})}let U={id:$.id,from:`localhost:${X}`,to:$.host,cwd:$.dir,createdAt:new Date(this.now()).toISOString(),pathRewrites:J.length>0?J:void 0,pid:w.handle?.pid};await this.writeEntry(U,this.registryDir,this.verbose),w.routeIds=[$.id];let Q=this.now()+2000;while(this.now()<Q&&!this.isHostRoutable($.host))await yQ(50)}fail(w,$){w.status="failed",w.error=$,w.failedAt=this.now(),H.warn(`rpx: site ${w.site.host} failed — ${$}`),this.killProcess(w)}buildEnv(w,$){let Y={};for(let[A,X]of Object.entries(Iw.env))if(typeof X==="string")Y[A]=X;Object.assign(Y,w.env);for(let[A,X]of $)Y[A]=String(X);return Y.RPX_SITE_HOST=w.host,Y.RPX_SITE_URL=`https://${w.host}`,Y}readLogTail(w,$=40){try{return DH(w.logPath,"utf8").split(`
235
233
  `).slice(-$).join(`
236
- `).trim()}catch{return""}}async stop(w){let $=this.sites.get(w);if(!$)return;this.sites.delete(w);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess($),H.info(`rpx: stopped ${w}`)}async killProcess(w){let $=w.handle;if(!$)return;w.handle=null;try{$.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{$.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([$.exited.catch(()=>{}),vW(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let w=this.now();for(let[$,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=w-Y.lastAccess;if((Y.status==="ready"||w-Y.startedAt>this.startupTimeoutMs)&&X>A)F("sites",`reaping ${$} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop($)}}list(){let w=this.now();return[...this.sites.values()].map(($)=>({host:$.site.host,dir:$.site.dir,status:$.status,pid:$.handle?.pid??null,ports:Object.fromEntries($.ports),uptimeMs:w-$.startedAt,idleMs:w-$.lastAccess,error:$.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((w)=>this.stop(w)))}}function vW(w){return new Promise(($)=>setTimeout($,w))}async function _R(w){let $=new AbortController,Y=setTimeout(()=>$.abort(),2000);try{return await fetch(`http://127.0.0.1:${w}/`,{signal:$.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(Y)}}function SR(w){let $=ZR();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=HR(J,"a");try{let W=MR("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...$?{uid:$.uid,gid:$.gid}:{}}),Q=W.pid;if(Q===void 0)throw Error("spawn returned no pid");let B=new Promise((j)=>{W.once("exit",(z)=>{j(z)}),W.once("error",()=>{j(null)})}).finally(()=>{try{X5(U)}catch{}});return F("sites",`spawned pid ${Q}: sh -c ${Y} (cwd ${A})`,w),{pid:Q,exited:B,stop:(j="SIGTERM")=>{try{Cw.kill(-Q,j)}catch{try{W.kill(j)}catch{}}}}}catch(W){try{X5(U)}catch{}throw W}}}function ZR(){if(Cw.platform==="win32")return null;if(!(typeof Cw.getuid==="function"&&Cw.getuid()===0))return null;let $=Number.parseInt(Cw.env.SUDO_UID??"",10),Y=Number.parseInt(Cw.env.SUDO_GID??"",10);if(!Number.isInteger($)||$<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:$,gid:Y}}var VR=120000,CR=200,yR=30000,OR=3000,LR=4000;var iW=t(()=>{dY();bW();t$();X0();nw()});function AY(w){return w.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function U5(w,$,Y){return`<!doctype html>
234
+ `).trim()}catch{return""}}async stop(w){let $=this.sites.get(w);if(!$)return;this.sites.delete(w);for(let Y of $.routeIds)await this.removeEntry(Y,this.registryDir,this.verbose).catch(()=>{});await this.killProcess($),H.info(`rpx: stopped ${w}`)}async killProcess(w){let $=w.handle;if(!$)return;w.handle=null;try{$.stop("SIGTERM")}catch{}let Y=setTimeout(()=>{try{$.stop("SIGKILL")}catch{}},this.killGraceMs);if(typeof Y.unref==="function")Y.unref();await Promise.race([$.exited.catch(()=>{}),yQ(this.killGraceMs+500)]),clearTimeout(Y)}async reapIdle(){if(this.stopped)return;let w=this.now();for(let[$,Y]of this.sites){let A=Y.site.idleTimeoutMs;if(A<=0)continue;let X=w-Y.lastAccess;if((Y.status==="ready"||w-Y.startedAt>this.startupTimeoutMs)&&X>A)E("sites",`reaping ${$} (idle ${Math.round(X/1000)}s)`,this.verbose),await this.stop($)}}list(){let w=this.now();return[...this.sites.values()].map(($)=>({host:$.site.host,dir:$.site.dir,status:$.status,pid:$.handle?.pid??null,ports:Object.fromEntries($.ports),uptimeMs:w-$.startedAt,idleMs:w-$.lastAccess,error:$.error}))}async stopAll(){this.stopped=!0,clearInterval(this.reaper),await Promise.allSettled([...this.sites.keys()].map((w)=>this.stop(w)))}}function yQ(w){return new Promise(($)=>setTimeout($,w))}async function vH(w){let $=new AbortController,Y=setTimeout(()=>$.abort(),2000);try{return await fetch(`http://127.0.0.1:${w}/`,{signal:$.signal,redirect:"manual"}),!0}catch{return!1}finally{clearTimeout(Y)}}function cH(w){let $=mH();return({command:Y,cwd:A,env:X,logPath:J})=>{let U=_H(J,"a");try{let Q=kH("sh",["-c",Y],{cwd:A,env:X,detached:!0,stdio:["ignore",U,U],...$?{uid:$.uid,gid:$.gid}:{}}),W=Q.pid;if(W===void 0)throw Error("spawn returned no pid");let j=new Promise((B)=>{Q.once("exit",(f)=>{B(f)}),Q.once("error",()=>{B(null)})}).finally(()=>{try{b2(U)}catch{}});return E("sites",`spawned pid ${W}: sh -c ${Y} (cwd ${A})`,w),{pid:W,exited:j,stop:(B="SIGTERM")=>{try{Iw.kill(-W,B)}catch{try{Q.kill(B)}catch{}}}}}catch(Q){try{b2(U)}catch{}throw Q}}}function mH(){if(Iw.platform==="win32")return null;if(!(typeof Iw.getuid==="function"&&Iw.getuid()===0))return null;let $=Number.parseInt(Iw.env.SUDO_UID??"",10),Y=Number.parseInt(Iw.env.SUDO_GID??"",10);if(!Number.isInteger($)||$<=0||!Number.isInteger(Y)||Y<=0)return null;return{uid:$,gid:Y}}var xH=120000,PH=200,iH=30000,bH=3000,uH=4000;var v2=a(()=>{R8();NQ();g$();f0();k$()});function c1(w){return w.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function c2(w,$,Y){return`<!doctype html>
237
235
  <html lang="en">
238
236
  <head>
239
237
  <meta charset="utf-8">
240
238
  <meta name="viewport" content="width=device-width, initial-scale=1">
241
239
  ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
242
- <title>${AY(w)}</title>
243
- <style>${kR}</style>
240
+ <title>${c1(w)}</title>
241
+ <style>${gH}</style>
244
242
  </head>
245
243
  <body><main class="card">${$}</main></body>
246
- </html>`}function mW(w){let $=Math.max(1,Math.round(w.sinceMs/1000)),Y=w.logTail?`<pre>${AY(w.logTail)}</pre>`:"",A=`
247
- <div class="row"><div class="spinner"></div><h1>Starting ${AY(w.host)}…</h1></div>
244
+ </html>`}function m2(w){let $=Math.max(1,Math.round(w.sinceMs/1000)),Y=w.logTail?`<pre>${c1(w.logTail)}</pre>`:"",A=`
245
+ <div class="row"><div class="spinner"></div><h1>Starting ${c1(w.host)}…</h1></div>
248
246
  <p>rpx is booting this site's dev server on demand. This page reloads itself —
249
247
  it'll switch to the app as soon as it's ready (usually a few seconds).</p>
250
248
  <p>Booting for ${$}s.</p>
251
- ${Y}`;return new Response(U5(`Starting ${w.host}`,A,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function gW(w){let $=w.logTail?`<pre>${AY(w.logTail)}</pre>`:"<p>No output was captured.</p>",Y=`
252
- <div class="row"><div class="dot"></div><h1>${AY(w.host)} failed to start</h1></div>
253
- <p>${AY(w.error)}</p>
249
+ ${Y}`;return new Response(c2(`Starting ${w.host}`,A,2),{status:503,headers:{"content-type":"text/html; charset=utf-8","retry-after":"2","cache-control":"no-store"}})}function g2(w){let $=w.logTail?`<pre>${c1(w.logTail)}</pre>`:"<p>No output was captured.</p>",Y=`
250
+ <div class="row"><div class="dot"></div><h1>${c1(w.host)} failed to start</h1></div>
251
+ <p>${c1(w.error)}</p>
254
252
  ${$}
255
- <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(U5(`${w.host} failed`,Y,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var kR=`
253
+ <p>Fix the cause and reload — rpx retries the boot on the next request.</p>`;return new Response(c2(`${w.host} failed`,Y,5),{status:502,headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}})}var gH=`
256
254
  :root { color-scheme: light dark }
257
255
  * { box-sizing: border-box }
258
256
  body {
@@ -278,63 +276,63 @@ ${Y>0?`<meta http-equiv="refresh" content="${Y}">`:""}
278
276
  }
279
277
  .dot { width: 10px; height: 10px; border-radius: 50%; background: #f87171 }
280
278
  @keyframes spin { to { transform: rotate(360deg) } }
281
- `;import{exec as hR}from"node:child_process";import d8 from"node:fs";import DR from"node:os";import B5 from"node:path";import*as a$ from"node:process";import{promisify as xR}from"node:util";function Q5(w){let $=w.trim().toLowerCase();return $==="localhost"||$.endsWith(".localhost")||$.endsWith(".localhost.")}async function j5(w){if(a$.platform==="win32")throw Error("Administrator privileges required on Windows");if(DY()){let{stdout:A}=await aY(w);return A}let $=V$(),Y=w.replace(/'/g,"'\\''");try{if($){let{stdout:A}=await aY(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`);return dW=!0,A}if(dW)try{let{stdout:A}=await aY(`sudo -n sh -c '${Y}'`);return A}catch(A){F("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await aY(`sudo -n sh -c '${Y}'`);return dW=!0,A}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(A){throw Error(`Failed to execute sudo command: ${A.message}`)}}function n8(w){let $=w.indexOf("#"),Y=($===-1?w:w.slice(0,$)).trim();if(!Y)return null;let A=$===-1?"":w.slice($+1).trim(),[X,...J]=Y.split(/\s+/);if(!X||J.length===0)return null;let U=/^rpx(?::pid=(\d+))?$/.exec(A);return{address:X,names:J,comment:A,rpxPid:U?.[1]?Number.parseInt(U[1],10):null,rpxManaged:U!==null}}function z5(w,$){let Y=n8(w);return Y!==null&&l8.has(Y.address)&&Y.names.includes($)}function bR(w,$){let Y=new Set($),A=new Set,X=w.split(`
282
- `),J=[],U=0;while(U<X.length){let W=X[U];if(W.trim()===PR){let B=[],j=U+1;while(j<X.length){let G=X[j];if(G.trim()===""||G.trim().startsWith("#"))break;B.push(G),j++}let z=B.filter((G)=>{let K=n8(G),E=K!==null&&l8.has(K.address)&&K.names.some((q)=>Y.has(q));if(E){for(let q of K.names)if(Y.has(q))A.add(q)}return!E});if(z.length>0||B.length===0)J.push(W,...z);U=j;continue}let Q=n8(W);if(Q?.rpxManaged&&l8.has(Q.address)&&Q.names.some((B)=>Y.has(B))){for(let B of Q.names)if(Y.has(B))A.add(B);U++;continue}J.push(W),U++}while(J.length>0&&J[J.length-1].trim()==="")J.pop();return{content:`${J.join(`
279
+ `;import{exec as dH}from"node:child_process";import S8 from"node:fs";import nH from"node:os";import l2 from"node:path";import*as d$ from"node:process";import{promisify as lH}from"node:util";function d2(w){let $=w.trim().toLowerCase();return $==="localhost"||$.endsWith(".localhost")||$.endsWith(".localhost.")}async function p2(w){if(d$.platform==="win32")throw Error("Administrator privileges required on Windows");if(TY()){let{stdout:A}=await iY(w);return A}let $=T$(),Y=w.replace(/'/g,"'\\''");try{if($){let{stdout:A}=await iY(`echo '${$}' | sudo -S sh -c '${Y}' 2>/dev/null`);return CQ=!0,A}if(CQ)try{let{stdout:A}=await iY(`sudo -n sh -c '${Y}'`);return A}catch(A){E("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await iY(`sudo -n sh -c '${Y}'`);return CQ=!0,A}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(A){throw Error(`Failed to execute sudo command: ${A.message}`)}}function h8(w){let $=w.indexOf("#"),Y=($===-1?w:w.slice(0,$)).trim();if(!Y)return null;let A=$===-1?"":w.slice($+1).trim(),[X,...J]=Y.split(/\s+/);if(!X||J.length===0)return null;let U=/^rpx(?::pid=(\d+))?$/.exec(A);return{address:X,names:J,comment:A,rpxPid:U?.[1]?Number.parseInt(U[1],10):null,rpxManaged:U!==null}}function r2(w,$){let Y=h8(w);return Y!==null&&O8.has(Y.address)&&Y.names.includes($)}function rH(w,$){let Y=new Set($),A=new Set,X=w.split(`
280
+ `),J=[],U=0;while(U<X.length){let Q=X[U];if(Q.trim()===pH){let j=[],B=U+1;while(B<X.length){let z=X[B];if(z.trim()===""||z.trim().startsWith("#"))break;j.push(z),B++}let f=j.filter((z)=>{let G=h8(z),T=G!==null&&O8.has(G.address)&&G.names.some((K)=>Y.has(K));if(T){for(let K of G.names)if(Y.has(K))A.add(K)}return!T});if(f.length>0||j.length===0)J.push(Q,...f);U=B;continue}let W=h8(Q);if(W?.rpxManaged&&O8.has(W.address)&&W.names.some((j)=>Y.has(j))){for(let j of W.names)if(Y.has(j))A.add(j);U++;continue}J.push(Q),U++}while(J.length>0&&J[J.length-1].trim()==="")J.pop();return{content:`${J.join(`
283
281
  `)}
284
- `,removed:[...A]}}function uR(w,$){let Y=[],A=new Set,X=[];for(let J of w.split(`
285
- `)){let U=n8(J);if(U?.rpxManaged&&U.rpxPid!==null&&l8.has(U.address)&&!$(U.rpxPid)){Y.push(...U.names),A.add(U.rpxPid);continue}X.push(J)}while(X.length>0&&X[X.length-1].trim()==="")X.pop();return{content:`${X.join(`
282
+ `,removed:[...A]}}function tH(w,$){let Y=[],A=new Set,X=[];for(let J of w.split(`
283
+ `)){let U=h8(J);if(U?.rpxManaged&&U.rpxPid!==null&&O8.has(U.address)&&!$(U.rpxPid)){Y.push(...U.names),A.add(U.rpxPid);continue}X.push(J)}while(X.length>0&&X[X.length-1].trim()==="")X.pop();return{content:`${X.join(`
286
284
  `)}
287
- `,removed:Y,stalePids:[...A]}}async function lW(w){try{return await d8.promises.readFile(B$,"utf-8")}catch{return F("hosts","Reading hosts file requires elevated permissions, using sudo",w),j5(`cat "${B$}"`)}}async function nW(w,$){let Y=B5.join(DR.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await d8.promises.writeFile(Y,w,"utf8"),await j5(`cat "${Y}" | tee "${B$}" > /dev/null`)}finally{await d8.promises.unlink(Y).catch((A)=>{F("hosts",`Failed to remove temporary file: ${A}`,$)})}}async function sY(w,$){let Y=w.filter((X)=>!Q5(X)),A=w.filter((X)=>Q5(X));if(A.length>0)F("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,$);if(Y.length===0)return;F("hosts",`Adding hosts: ${Y.join(", ")}`,$),F("hosts",`Using hosts file at: ${B$}`,$);try{let X;try{X=await lW($)}catch(B){throw console.log(" Could not read hosts file — skipping hosts setup"),F("hosts",`sudo read also failed: ${B}`,$),Error(`Cannot read hosts file: ${B}`)}let J=X.split(`
288
- `),U=Y.filter((B)=>!J.some((j)=>z5(j,B)));if(U.length===0){F("hosts","All hosts already exist in hosts file",$);return}let W=a$.pid,Q=U.map((B)=>`
289
- 127.0.0.1 ${B} ${W5}:pid=${W}
290
- ::1 ${B} ${W5}:pid=${W}`).join(`
291
- `);try{await nW(X+Q,$),console.log(` Hosts updated: ${U.join(", ")}`)}catch(B){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),U.forEach((j)=>{console.log(` 127.0.0.1 ${j}`),console.log(` ::1 ${j}`)}),console.log(` Or run: sudo nano ${B$}`)}}catch(X){F("hosts",`Failed to manage hosts file: ${X.message}`,$)}}async function G5(w,$){F("hosts",`Removing hosts: ${w.join(", ")}`,$);try{let Y;try{Y=await lW($)}catch(J){throw F("hosts",`sudo read also failed: ${J}`,$),Error(`Cannot read hosts file: ${J}`)}let{content:A,removed:X}=bR(Y,w);if(X.length===0){F("hosts","No matching rpx-managed hosts found to remove",$);return}try{await nW(A,$),F("hosts",`Hosts removed successfully: ${X.join(", ")}`,$)}catch(J){F("hosts","Could not clean up hosts file automatically",$)}}catch(Y){F("hosts",`Failed to clean up hosts file: ${Y.message}`,$)}}async function oY(w,$){F("hosts",`Checking hosts: ${w}`,$);let Y;try{Y=await d8.promises.readFile(B$,"utf-8")}catch(X){F("hosts",`Error reading hosts file: ${X}`,$);try{let J=V$(),U;if(J)U=`echo '${J}' | sudo -S cat "${B$}" 2>/dev/null`;else U=`sudo -n cat "${B$}" 2>/dev/null || cat "${B$}" 2>/dev/null || echo ""`;let{stdout:W}=await aY(U);Y=W}catch(J){return F("hosts",`Cannot read hosts file, assuming entries don't exist: ${J}`,$),w.map(()=>!1)}}let A=Y.split(`
292
- `);return w.map((X)=>A.some((J)=>z5(J,X)))}async function XY(w={}){let $=w.isAlive??b0,Y;try{Y=await lW(w.verbose)}catch(U){return F("hosts",`stale hosts GC: cannot read hosts file: ${U}`,w.verbose),[]}let{content:A,removed:X,stalePids:J}=uR(Y,$);if(X.length===0)return[];try{return await nW(A,w.verbose),F("hosts",`stale hosts GC: removed ${X.join(", ")} (dead pid(s): ${J.join(", ")})`,w.verbose),[...new Set(X)]}catch(U){return F("hosts",`stale hosts GC: write failed: ${U}`,w.verbose),[]}}var aY,B$,W5="# rpx",PR="# Added by rpx",l8,dW=!1;var p8=t(()=>{t$();X0();aY=xR(hR);B$=a$.platform==="win32"?B5.join(a$.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",l8=new Set(["127.0.0.1","::1"])});import{spawn as cR}from"node:child_process";import*as j$ from"node:fs/promises";import{homedir as vR}from"node:os";import*as eY from"node:path";import*as I0 from"node:process";function z$(){return eY.join(vR(),".stacks","rpx")}function F5(w=z$()){return eY.join(w,"daemon.pid")}async function K5(w=z$()){try{let $=await j$.readFile(F5(w),"utf8"),Y=Number.parseInt($.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch($){if($.code==="ENOENT")return null;throw $}}async function iR(w=z$()){await j$.unlink(F5(w)).catch(()=>{})}function mR(){let w=I0.execPath,$=eY.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&I0.argv[1])return[w,I0.argv[1],"daemon:start"];return[w,"daemon:start"]}async function q5(w={}){let $=w.rpxDir??z$(),Y=w.verbose??!1;await G$({rpxDir:$,verbose:Y}).catch((j)=>{F("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,Y)});let A=await K5($);if(A!==null&&b0(A))return F("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)F("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await iR($);await j$.mkdir($,{recursive:!0});let X=w.spawnCommand??mR();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");F("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=cR(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??I0.cwd(),env:w.spawnEnv?{...I0.env,...w.spawnEnv}:I0.env});J.unref();let U=null;J.once("error",(j)=>{U=j});let W=w.startupTimeoutMs??5000,Q=w.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let j=await K5($);if(j!==null&&b0(j))return F("daemon",`daemon registered with pid=${j}`,Y),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,Q))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${$})`)}var pW=t(()=>{nw();L8();k8();h8();dY();x8();b8();xW();iW();mY();cY();t$();p8();JY();X0()});import*as h$ from"node:fs/promises";import{homedir as gR}from"node:os";import*as rW from"node:path";function E5(){return rW.join(gR(),".stacks","rpx")}function tW(w=E5()){return rW.join(w,dR)}async function t8(w=E5()){try{let $=await h$.readFile(tW(w),"utf8"),Y=JSON.parse($);if(Y.version!==r8||!Array.isArray(Y.resolvers))return null;return{version:r8,resolvers:Y.resolvers.filter((A)=>typeof A==="string"),domains:Array.isArray(Y.domains)?Y.domains.filter((A)=>typeof A==="string"):[],ownerPid:typeof Y.ownerPid==="number"?Y.ownerPid:null,updatedAt:typeof Y.updatedAt==="string"?Y.updatedAt:""}}catch($){if($.code==="ENOENT")return null;throw $}}async function f5(w,$){await h$.mkdir(w,{recursive:!0}),await h$.writeFile(tW(w),`${JSON.stringify($,null,2)}
293
- `,"utf8")}async function aW(w){await h$.rm(tW(w),{force:!0})}function T5(w){let $=w.trim().toLowerCase().replace(/\.$/,"");if(!$||$.includes("127.0.0.1"))return null;if($==="localhost"||$.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test($))return null;if(!/^[a-z0-9.-]+$/.test($))return null;return $}function lR(w){let $=T5(w);if(!$)return null;let Y=$.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function sW(w){let $=new Set;for(let Y of w){let A=lR(Y);if(A)$.add(A)}return Array.from($).sort()}function oW(w){let $=new Set;for(let Y of w){let A=T5(Y);if(A)$.add(A)}return Array.from($).sort()}var r8=1,dR="dns-state.json",N5;var H5=t(()=>{N5=["com","test","dev","app","page","local","localhost","example","invalid"]});var s8={};fB(s8,{tearDownDevelopmentDns:()=>k$,syncDevelopmentDnsFromRegistry:()=>s$,stopDnsServer:()=>eW,startDnsServer:()=>L5,setupResolver:()=>$M,setupDevelopmentDns:()=>AB,resolverFilePath:()=>UY,removeResolver:()=>AM,removeLegacyTldResolvers:()=>YB,reconcileStaleDevelopmentDns:()=>G$,isRpxDevelopmentDnsAnswering:()=>_5,isDnsServerRunning:()=>tR,contentLooksLikeRpxResolver:()=>S5,RPX_RESOLVER_MARKER:()=>V5,DNS_PORT:()=>$A});import R5 from"node:dgram";import*as M5 from"node:fs/promises";import*as I5 from"node:path";import*as K$ from"node:process";function y5(w){return{id:w.readUInt16BE(0),flags:w.readUInt16BE(2),qdcount:w.readUInt16BE(4),ancount:w.readUInt16BE(6),nscount:w.readUInt16BE(8),arcount:w.readUInt16BE(10)}}function O5(w,$,Y=0){let A=[],X=$,J=0;while(!0){if(X>=w.length||++J>128)break;let U=w[X];if(U===0){X++;break}if((U&192)===192){if(X+1>=w.length||Y>=10)break;let W=w.readUInt16BE(X)&16383,{name:Q}=O5(w,W,Y+1);if(Q)A.push(Q);X+=2;break}if(X++,X+U>w.length)break;A.push(w.subarray(X,X+U).toString("ascii")),X+=U}return{name:A.join("."),newOffset:X}}function nR(w,$){let{name:Y,newOffset:A}=O5(w,$),X=w.readUInt16BE(A),J=w.readUInt16BE(A+2);return{question:{name:Y,type:X,class:J},newOffset:A+4}}function wA(w){let $=w.split("."),Y=[];for(let A of $)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function pR(w,$,Y){let A=[],X=Buffer.alloc(12);X.writeUInt16BE(w,0),X.writeUInt16BE(33152,2),X.writeUInt16BE(1,4),X.writeUInt16BE(1,6),X.writeUInt16BE(0,8),X.writeUInt16BE(0,10),A.push(X),A.push(wA($.name));let J=Buffer.alloc(4);J.writeUInt16BE($.type,0),J.writeUInt16BE($.class,2),A.push(J),A.push(wA($.name));let U=Buffer.alloc(10);if(U.writeUInt16BE($.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),$.type===1){U.writeUInt16BE(4,8),A.push(U);let W=Y.split(".").map((Q)=>Number.parseInt(Q,10));A.push(Buffer.from(W))}else if($.type===28)U.writeUInt16BE(16,8),A.push(U),A.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return X.writeUInt16BE(33155,2),X.writeUInt16BE(0,6),Buffer.concat([X,wA($.name),J]);return Buffer.concat(A)}function rR(w,$){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE(w,0),A.writeUInt16BE(33155,2),A.writeUInt16BE(1,4),A.writeUInt16BE(0,6),A.writeUInt16BE(0,8),A.writeUInt16BE(0,10),Y.push(A),Y.push(wA($.name));let X=Buffer.alloc(4);return X.writeUInt16BE($.type,0),X.writeUInt16BE($.class,2),Y.push(X),Buffer.concat(Y)}async function L5(w,$){if(K$.platform!=="darwin")return!1;let Y=oW(w);if(Y.length===0)return!1;if(a0){for(let A of Y)a8.add(A);return F("dns","DNS server already running — merged domains",$),!0}return a8=new Set(Y),new Promise((A)=>{a0=R5.createSocket("udp4"),a0.on("error",(X)=>{F("dns",`DNS server error: ${X.message}`,$),a0?.close(),a0=null,A(!1)}),a0.on("message",(X,J)=>{try{let U=y5(X),{question:W}=nR(X,12);F("dns",`Query for ${W.name} type ${W.type} from ${J.address}`,$);let Q=W.name.toLowerCase(),B=!1;for(let z of a8)if(Q===z||Q.endsWith(`.${z}`)){B=!0;break}let j;if(B&&(W.type===1||W.type===28))j=pR(U.id,W,"127.0.0.1"),F("dns",`Responding with localhost for ${W.name}`,$);else j=rR(U.id,W),F("dns",`NXDOMAIN for ${W.name}`,$);a0?.send(j,J.port,J.address)}catch(U){F("dns",`Error processing DNS query: ${U}`,$)}}),a0.on("listening",()=>{let X=a0?.address();F("dns",`DNS server listening on ${X?.address}:${X?.port}`,$),A(!0)});try{a0.bind($A,"127.0.0.1")}catch(X){F("dns",`Failed to bind DNS server: ${X}`,$),A(!1)}})}function eW(w){if(a0)F("dns","Stopping DNS server",w),a0.close(),a0=null,a8=new Set}function tR(){return a0!==null}async function _5(w,$=500){let Y=w.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let X=R5.createSocket("udp4"),J=setTimeout(()=>{X.close(),A(!1)},$);X.on("message",(W)=>{clearTimeout(J),X.close();try{let Q=y5(W);A(Q.ancount>0)}catch{A(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),A(!1)});let U=aR(Y,1);X.send(U,$A,"127.0.0.1",(W)=>{if(W)clearTimeout(J),X.close(),A(!1)})})}function aR(w,$){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([wA(w),Buffer.from([0,$,0,1])]);return Buffer.concat([Y,A])}function sR(){return`${V5}
285
+ `,removed:Y,stalePids:[...A]}}async function VQ(w){try{return await S8.promises.readFile(J$,"utf-8")}catch{return E("hosts","Reading hosts file requires elevated permissions, using sudo",w),p2(`cat "${J$}"`)}}async function LQ(w,$){let Y=l2.join(nH.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await S8.promises.writeFile(Y,w,"utf8"),await p2(`cat "${Y}" | tee "${J$}" > /dev/null`)}finally{await S8.promises.unlink(Y).catch((A)=>{E("hosts",`Failed to remove temporary file: ${A}`,$)})}}async function bY(w,$){let Y=w.filter((X)=>!d2(X)),A=w.filter((X)=>d2(X));if(A.length>0)E("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,$);if(Y.length===0)return;E("hosts",`Adding hosts: ${Y.join(", ")}`,$),E("hosts",`Using hosts file at: ${J$}`,$);try{let X;try{X=await VQ($)}catch(j){throw console.log(" Could not read hosts file — skipping hosts setup"),E("hosts",`sudo read also failed: ${j}`,$),Error(`Cannot read hosts file: ${j}`)}let J=X.split(`
286
+ `),U=Y.filter((j)=>!J.some((B)=>r2(B,j)));if(U.length===0){E("hosts","All hosts already exist in hosts file",$);return}let Q=d$.pid,W=U.map((j)=>`
287
+ 127.0.0.1 ${j} ${n2}:pid=${Q}
288
+ ::1 ${j} ${n2}:pid=${Q}`).join(`
289
+ `);try{await LQ(X+W,$),console.log(` Hosts updated: ${U.join(", ")}`)}catch(j){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),U.forEach((B)=>{console.log(` 127.0.0.1 ${B}`),console.log(` ::1 ${B}`)}),console.log(` Or run: sudo nano ${J$}`)}}catch(X){E("hosts",`Failed to manage hosts file: ${X.message}`,$)}}async function t2(w,$){E("hosts",`Removing hosts: ${w.join(", ")}`,$);try{let Y;try{Y=await VQ($)}catch(J){throw E("hosts",`sudo read also failed: ${J}`,$),Error(`Cannot read hosts file: ${J}`)}let{content:A,removed:X}=rH(Y,w);if(X.length===0){E("hosts","No matching rpx-managed hosts found to remove",$);return}try{await LQ(A,$),E("hosts",`Hosts removed successfully: ${X.join(", ")}`,$)}catch(J){E("hosts","Could not clean up hosts file automatically",$)}}catch(Y){E("hosts",`Failed to clean up hosts file: ${Y.message}`,$)}}async function uY(w,$){E("hosts",`Checking hosts: ${w}`,$);let Y;try{Y=await S8.promises.readFile(J$,"utf-8")}catch(X){E("hosts",`Error reading hosts file: ${X}`,$);try{let J=T$(),U;if(J)U=`echo '${J}' | sudo -S cat "${J$}" 2>/dev/null`;else U=`sudo -n cat "${J$}" 2>/dev/null || cat "${J$}" 2>/dev/null || echo ""`;let{stdout:Q}=await iY(U);Y=Q}catch(J){return E("hosts",`Cannot read hosts file, assuming entries don't exist: ${J}`,$),w.map(()=>!1)}}let A=Y.split(`
290
+ `);return w.map((X)=>A.some((J)=>r2(J,X)))}async function vY(w={}){let $=w.isAlive??Yw,Y;try{Y=await VQ(w.verbose)}catch(U){return E("hosts",`stale hosts GC: cannot read hosts file: ${U}`,w.verbose),[]}let{content:A,removed:X,stalePids:J}=tH(Y,$);if(X.length===0)return[];try{return await LQ(A,w.verbose),E("hosts",`stale hosts GC: removed ${X.join(", ")} (dead pid(s): ${J.join(", ")})`,w.verbose),[...new Set(X)]}catch(U){return E("hosts",`stale hosts GC: write failed: ${U}`,w.verbose),[]}}var iY,J$,n2="# rpx",pH="# Added by rpx",O8,CQ=!1;var SQ=a(()=>{g$();f0();iY=lH(dH);J$=d$.platform==="win32"?l2.join(d$.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",O8=new Set(["127.0.0.1","::1"])});import*as V$ from"node:fs/promises";import{homedir as aH}from"node:os";import*as OQ from"node:path";function s2(){return OQ.join(aH(),".stacks","rpx")}function hQ(w=s2()){return OQ.join(w,sH)}async function D8(w=s2()){try{let $=await V$.readFile(hQ(w),"utf8"),Y=JSON.parse($);if(Y.version!==_8||!Array.isArray(Y.resolvers))return null;return{version:_8,resolvers:Y.resolvers.filter((A)=>typeof A==="string"),domains:Array.isArray(Y.domains)?Y.domains.filter((A)=>typeof A==="string"):[],ownerPid:typeof Y.ownerPid==="number"?Y.ownerPid:null,updatedAt:typeof Y.updatedAt==="string"?Y.updatedAt:""}}catch($){if($.code==="ENOENT")return null;throw $}}async function o2(w,$){await V$.mkdir(w,{recursive:!0}),await V$.writeFile(hQ(w),`${JSON.stringify($,null,2)}
291
+ `,"utf8")}async function _Q(w){await V$.rm(hQ(w),{force:!0})}function e2(w){let $=w.trim().toLowerCase().replace(/\.$/,"");if(!$||$.includes("127.0.0.1"))return null;if($==="localhost"||$.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test($))return null;if(!/^[a-z0-9.-]+$/.test($))return null;return $}function oH(w){let $=e2(w);if(!$)return null;let Y=$.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function DQ(w){let $=new Set;for(let Y of w){let A=oH(Y);if(A)$.add(A)}return Array.from($).sort()}function kQ(w){let $=new Set;for(let Y of w){let A=e2(Y);if(A)$.add(A)}return Array.from($).sort()}var _8=1,sH="dns-state.json",a2;var wG=a(()=>{a2=["com","test","dev","app","page","local","localhost","example","invalid"]});var Z8={};rQ(Z8,{tearDownDevelopmentDns:()=>n$,syncDevelopmentDnsFromRegistry:()=>g1,stopDnsServer:()=>ZQ,startDnsServer:()=>QG,setupResolver:()=>QR,setupDevelopmentDns:()=>bQ,resolverFilePath:()=>m1,removeResolver:()=>BR,removeLegacyTldResolvers:()=>iQ,reconcileStaleDevelopmentDns:()=>l$,isRpxDevelopmentDnsAnswering:()=>jG,isDnsServerRunning:()=>YR,contentLooksLikeRpxResolver:()=>BG,RPX_RESOLVER_MARKER:()=>XG,DNS_PORT:()=>mY});import $G from"node:dgram";import*as YG from"node:fs/promises";import*as AG from"node:path";import*as U$ from"node:process";function UG(w){return{id:w.readUInt16BE(0),flags:w.readUInt16BE(2),qdcount:w.readUInt16BE(4),ancount:w.readUInt16BE(6),nscount:w.readUInt16BE(8),arcount:w.readUInt16BE(10)}}function WG(w,$,Y=0){let A=[],X=$,J=0;while(!0){if(X>=w.length||++J>128)break;let U=w[X];if(U===0){X++;break}if((U&192)===192){if(X+1>=w.length||Y>=10)break;let Q=w.readUInt16BE(X)&16383,{name:W}=WG(w,Q,Y+1);if(W)A.push(W);X+=2;break}if(X++,X+U>w.length)break;A.push(w.subarray(X,X+U).toString("ascii")),X+=U}return{name:A.join("."),newOffset:X}}function eH(w,$){let{name:Y,newOffset:A}=WG(w,$),X=w.readUInt16BE(A),J=w.readUInt16BE(A+2);return{question:{name:Y,type:X,class:J},newOffset:A+4}}function cY(w){let $=w.split("."),Y=[];for(let A of $)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function wR(w,$,Y){let A=[],X=Buffer.alloc(12);X.writeUInt16BE(w,0),X.writeUInt16BE(33152,2),X.writeUInt16BE(1,4),X.writeUInt16BE(1,6),X.writeUInt16BE(0,8),X.writeUInt16BE(0,10),A.push(X),A.push(cY($.name));let J=Buffer.alloc(4);J.writeUInt16BE($.type,0),J.writeUInt16BE($.class,2),A.push(J),A.push(cY($.name));let U=Buffer.alloc(10);if(U.writeUInt16BE($.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),$.type===1){U.writeUInt16BE(4,8),A.push(U);let Q=Y.split(".").map((W)=>Number.parseInt(W,10));A.push(Buffer.from(Q))}else if($.type===28)U.writeUInt16BE(16,8),A.push(U),A.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return X.writeUInt16BE(33155,2),X.writeUInt16BE(0,6),Buffer.concat([X,cY($.name),J]);return Buffer.concat(A)}function $R(w,$){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE(w,0),A.writeUInt16BE(33155,2),A.writeUInt16BE(1,4),A.writeUInt16BE(0,6),A.writeUInt16BE(0,8),A.writeUInt16BE(0,10),Y.push(A),Y.push(cY($.name));let X=Buffer.alloc(4);return X.writeUInt16BE($.type,0),X.writeUInt16BE($.class,2),Y.push(X),Buffer.concat(Y)}async function QG(w,$){if(U$.platform!=="darwin")return!1;let Y=kQ(w);if(Y.length===0)return!1;if(r0){for(let A of Y)k8.add(A);return E("dns","DNS server already running — merged domains",$),!0}return k8=new Set(Y),new Promise((A)=>{r0=$G.createSocket("udp4"),r0.on("error",(X)=>{E("dns",`DNS server error: ${X.message}`,$),r0?.close(),r0=null,A(!1)}),r0.on("message",(X,J)=>{try{let U=UG(X),{question:Q}=eH(X,12);E("dns",`Query for ${Q.name} type ${Q.type} from ${J.address}`,$);let W=Q.name.toLowerCase(),j=!1;for(let f of k8)if(W===f||W.endsWith(`.${f}`)){j=!0;break}let B;if(j&&(Q.type===1||Q.type===28))B=wR(U.id,Q,"127.0.0.1"),E("dns",`Responding with localhost for ${Q.name}`,$);else B=$R(U.id,Q),E("dns",`NXDOMAIN for ${Q.name}`,$);r0?.send(B,J.port,J.address)}catch(U){E("dns",`Error processing DNS query: ${U}`,$)}}),r0.on("listening",()=>{let X=r0?.address();E("dns",`DNS server listening on ${X?.address}:${X?.port}`,$),A(!0)});try{r0.bind(mY,"127.0.0.1")}catch(X){E("dns",`Failed to bind DNS server: ${X}`,$),A(!1)}})}function ZQ(w){if(r0)E("dns","Stopping DNS server",w),r0.close(),r0=null,k8=new Set}function YR(){return r0!==null}async function jG(w,$=500){let Y=w.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let X=$G.createSocket("udp4"),J=setTimeout(()=>{X.close(),A(!1)},$);X.on("message",(Q)=>{clearTimeout(J),X.close();try{let W=UG(Q);A(W.ancount>0)}catch{A(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),A(!1)});let U=AR(Y,1);X.send(U,mY,"127.0.0.1",(Q)=>{if(Q)clearTimeout(J),X.close(),A(!1)})})}function AR(w,$){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([cY(w),Buffer.from([0,$,0,1])]);return Buffer.concat([Y,A])}function XR(){return`${XG}
294
292
  nameserver 127.0.0.1
295
- port ${$A}
296
- `}function UY(w){return I5.join(C5,w)}function S5(w){return w.includes("127.0.0.1")&&w.includes(String($A))}async function oR(w){try{return await M5.readFile(UY(w),"utf8")}catch($){if($.code==="ENOENT")return null;throw $}}async function wB(w){if(K$.platform!=="darwin")return;let{execSudoSync:$,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),d1));if(!A()&&!Y()){F("dns","Cannot flush DNS cache without SUDO_PASSWORD",w);return}try{$("dscacheutil -flushcache"),$("killall -HUP mDNSResponder 2>/dev/null || true"),F("dns","DNS cache flushed",w)}catch(X){F("dns",`Could not flush DNS cache: ${X}`,w)}}function Z5(w){if(!/^[a-z0-9.-]+$/.test(w))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(w)}`)}async function eR(w,$){Z5(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),d1)),A=sR().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${C5} && printf "%b" "${A}" > ${UY(w)}'`;Y(X),F("dns",`Created ${UY(w)}`,$)}async function wM(w,$){Z5(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (X0(),d1));Y(`rm -f ${UY(w)}`),F("dns",`Removed ${UY(w)}`,$)}async function $M(w,$){return AB({domains:$??[],verbose:w})}async function YM(w,$){if(K$.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),d1));if(!A()&&!Y())return F("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;try{for(let X of w)await eR(X,$);return await wB($),!0}catch(X){return F("dns",`Failed to create resolver file: ${X}`,$),!1}}async function $B(w,$){if(K$.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (X0(),d1));if(!A()&&!Y())return;try{for(let X of w)await wM(X,$);await wB($)}catch(X){F("dns",`Failed to remove resolver files: ${X}`,$)}}async function YB(w){if(K$.platform!=="darwin")return[];let $=[];for(let Y of N5){let A=await oR(Y);if(A&&S5(A))await $B([Y],w),$.push(Y)}return $}async function AB(w){let $=w.rpxDir??z$(),Y=oW(w.domains);if(Y.length===0)return!1;let A=sW(Y),X=await L5(Y,w.verbose);if(!X){let W=Y[0];if(W&&await _5(W))X=!0;else F("dns","Dev DNS server not available on 127.0.0.1:15353",w.verbose)}if(!X)return!1;if(!await YM(A,w.verbose))return!1;let U={version:r8,resolvers:A,domains:Y,ownerPid:w.ownerPid??K$.pid,updatedAt:new Date().toISOString()};return await f5($,U),!0}async function s$(w,$={}){let Y=w.map((Q)=>Q.to).filter(Boolean),A=$.rpxDir??z$(),X=sW(Y),W=((await t8(A))?.resolvers??[]).filter((Q)=>!X.includes(Q));if(W.length>0)await $B(W,$.verbose);if(X.length===0){eW($.verbose),await aW(A);return}await AB({domains:Y,rpxDir:A,verbose:$.verbose,ownerPid:$.ownerPid??K$.pid})}async function k$(w={}){let $=w.rpxDir??z$();eW(w.verbose);let A=(await t8($))?.resolvers??[];await $B(A,w.verbose),await YB(w.verbose),await aW($)}async function AM(w){await k$({verbose:w})}async function G$(w={}){let $=w.rpxDir??z$(),Y=await t8($),A=Y?.ownerPid!=null&&b0(Y.ownerPid);if(Y&&!A){F("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,w.verbose),await k$(w);return}let X=await YB(w.verbose);if(X.length>0)F("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,w.verbose);await wB(w.verbose)}var $A=15353,V5="# managed-by: rpx",C5="/etc/resolver",a0=null,a8;var JY=t(()=>{pW();H5();t$();X0();a8=new Set});import{dirname as SM,join as ZM}from"path";import*as P0 from"process";import{fileURLToPath as kM}from"url";import{existsSync as N6}from"node:fs";import EJ from"node:fs/promises";import TB from"node:os";import fJ from"node:path";import b$ from"node:process";import{EventEmitter as E6}from"node:events";import F$ from"node:process";import HB from"node:process";import MJ from"node:process";import UA from"node:process";import KY from"node:process";import IB from"node:tty";import XK,{stdin as oM,stdout as eM}from"node:process";import CB,{stdin as QK,stdout as WK}from"node:process";import BK from"node:readline";class OB{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let w=TB.homedir(),$=fJ.join(w,".config","clapp");this.configPath=fJ.join($,"telemetry.json")}async isEnabled(){if(b$.env.DO_NOT_TRACK==="1"||b$.env.DO_NOT_TRACK==="true")return!1;if(b$.env.NO_TELEMETRY==="1"||b$.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let w=await this.loadConfig();if(w.enabled=!0,!w.userId)w.userId=this.generateUserId();await this.saveConfig(w)}async disable(){let w=await this.loadConfig();w.enabled=!1,await this.saveConfig(w)}async track(w,$){if(!await this.isEnabled())return;let A={event:w,...$,timestamp:Date.now(),platform:TB.platform(),nodeVersion:b$.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand(w,$){await this.track("command",{command:w,duration:$})}async trackError(w,$){await this.track("error",{error:w,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(w){return new Promise(($)=>setTimeout($,w))}async status(){let w=await this.loadConfig();return{enabled:w.enabled,doNotTrack:b$.env.DO_NOT_TRACK==="1"||b$.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:w.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(N6(this.configPath)){let w=await EJ.readFile(this.configPath,"utf-8");return this.config=JSON.parse(w),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(w){this.config=w;try{let $=fJ.dirname(this.configPath);await EJ.mkdir($,{recursive:!0}),await EJ.writeFile(this.configPath,JSON.stringify(w,null,2),"utf-8")}catch{}}generateUserId(){let w=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${w}-${$}`}}var vM=new OB;function f6(w,$={}){let Y={_:[]},A=$.alias||{},X=new Set($.boolean||[]),J={};for(let W of Object.keys(A))for(let Q of A[W])J[Q]=W;for(let W of X)if(A[W])for(let Q of A[W])X.add(Q);function U(W,Q){let B=J[W]||W;if(Y[B]=Q,A[B])for(let j of A[B])Y[j]=Q;if(J[W]&&A[J[W]])for(let j of A[J[W]])Y[j]=Q;Y[W]=Q}for(let W=0;W<w.length;W++){let Q=w[W];if(Q==="--"){Y._.push(...w.slice(W+1));break}if(Q.startsWith("--")){let B=Q.indexOf("=");if(B!==-1){let j=Q.slice(2,B),z=Q.slice(B+1);U(j,z)}else{let j=Q.slice(2);if(j.startsWith("no-")){let G=j.slice(3);U(G,!1);continue}let z=J[j]||j;if(X.has(z)||X.has(j))U(j,!0);else{let G=w[W+1];if(G!==void 0&&!G.startsWith("-"))U(j,G),W++;else U(j,!0)}}}else if(Q.startsWith("-")&&Q.length>1){let B=Q.slice(1);for(let j=0;j<B.length;j++){let z=B[j],G=J[z]||z;if(j===B.length-1&&!X.has(G)&&!X.has(z)){let K=w[W+1];if(K!==void 0&&!K.startsWith("-"))U(z,K),W++;else U(z,!0)}else U(z,!0)}}else Y._.push(Q)}return Y}function RJ(w){return w.replace(/[<[].+/,"").trim()}function T6(w){let $=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(W)=>{let Q=!1,B=W[1];if(B.startsWith("..."))B=B.slice(3),Q=!0;return{required:W[0].startsWith("<"),value:B,variadic:Q}},J;while(J=$.exec(w))A.push(X(J));let U;while(U=Y.exec(w))A.push(X(U));return A}function H6(w){let $={alias:{},boolean:[]};for(let[Y,A]of w.entries()){if(A.names.length>1)$.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!w.some((J,U)=>{return U!==Y&&J.names.some((W)=>A.names.includes(W))&&typeof J.required==="boolean"}))$.boolean.push(A.names[0])}else $.boolean.push(A.names[0])}return $}function RB(w){return w.reduce(($,Y)=>$.length>=Y.length?$:Y,"")}function TJ(w,$){return w.length>=$?w:`${w}${" ".repeat($-w.length)}`}function R6(w){return w.replace(/([a-z])-([a-z])/g,($,Y,A)=>{return Y+A.toUpperCase()})}function M6(w,$,Y){let A=0,X=$.length,J=w,U;for(;A<X;++A)U=J[$[A]],J=J[$[A]]=A===X-1?Y:U!=null?U:!!~$[A+1].indexOf(".")||!(+$[A+1]>-1)?{}:[]}function I6(w,$){for(let Y of Object.keys($)){let A=$[Y];if(A.shouldTransform){if(w[Y]=Array.prototype.concat.call([],w[Y]),typeof A.transformFunction==="function")w[Y]=w[Y].map(A.transformFunction)}}}function V6(w){let $=/([^\\/]+)$/.exec(w);return $?$[1]:""}function LB(w){return w.split(".").map(($,Y)=>{return Y===0?R6($):$}).join(".")}class JA extends Error{exitCode=2;isUsageError=!0;constructor(w){super(w);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(w).stack}format(w=!1){if(w&&this.stack)return`${this.message}
293
+ port ${mY}
294
+ `}function m1(w){return AG.join(JG,w)}function BG(w){return w.includes("127.0.0.1")&&w.includes(String(mY))}async function JR(w){try{return await YG.readFile(m1(w),"utf8")}catch($){if($.code==="ENOENT")return null;throw $}}async function xQ(w){if(U$.platform!=="darwin")return;let{execSudoSync:$,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),P1));if(!A()&&!Y()){E("dns","Cannot flush DNS cache without SUDO_PASSWORD",w);return}try{$("dscacheutil -flushcache"),$("killall -HUP mDNSResponder 2>/dev/null || true"),E("dns","DNS cache flushed",w)}catch(X){E("dns",`Could not flush DNS cache: ${X}`,w)}}function fG(w){if(!/^[a-z0-9.-]+$/.test(w))throw Error(`refusing unsafe resolver basename: ${JSON.stringify(w)}`)}async function UR(w,$){fG(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (f0(),P1)),A=XR().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${JG} && printf "%b" "${A}" > ${m1(w)}'`;Y(X),E("dns",`Created ${m1(w)}`,$)}async function WR(w,$){fG(w);let{execSudoSync:Y}=await Promise.resolve().then(() => (f0(),P1));Y(`rm -f ${m1(w)}`),E("dns",`Removed ${m1(w)}`,$)}async function QR(w,$){return bQ({domains:$??[],verbose:w})}async function jR(w,$){if(U$.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),P1));if(!A()&&!Y())return E("dns","SUDO_PASSWORD not set, cannot create resolver files",$),!1;try{for(let X of w)await UR(X,$);return await xQ($),!0}catch(X){return E("dns",`Failed to create resolver file: ${X}`,$),!1}}async function PQ(w,$){if(U$.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),P1));if(!A()&&!Y())return;try{for(let X of w)await WR(X,$);await xQ($)}catch(X){E("dns",`Failed to remove resolver files: ${X}`,$)}}async function iQ(w){if(U$.platform!=="darwin")return[];let $=[];for(let Y of a2){let A=await JR(Y);if(A&&BG(A))await PQ([Y],w),$.push(Y)}return $}async function bQ(w){let $=w.rpxDir??V0(),Y=kQ(w.domains);if(Y.length===0)return!1;let A=DQ(Y),X=await QG(Y,w.verbose);if(!X){let Q=Y[0];if(Q&&await jG(Q))X=!0;else E("dns","Dev DNS server not available on 127.0.0.1:15353",w.verbose)}if(!X)return!1;if(!await jR(A,w.verbose))return!1;let U={version:_8,resolvers:A,domains:Y,ownerPid:w.ownerPid??U$.pid,updatedAt:new Date().toISOString()};return await o2($,U),!0}async function g1(w,$={}){let Y=w.map((W)=>W.to).filter(Boolean),A=$.rpxDir??V0(),X=DQ(Y),Q=((await D8(A))?.resolvers??[]).filter((W)=>!X.includes(W));if(Q.length>0)await PQ(Q,$.verbose);if(X.length===0){ZQ($.verbose),await _Q(A);return}await bQ({domains:Y,rpxDir:A,verbose:$.verbose,ownerPid:$.ownerPid??U$.pid})}async function n$(w={}){let $=w.rpxDir??V0();ZQ(w.verbose);let A=(await D8($))?.resolvers??[];await PQ(A,w.verbose),await iQ(w.verbose),await _Q($)}async function BR(w){await n$({verbose:w})}async function l$(w={}){let $=w.rpxDir??V0(),Y=await D8($),A=Y?.ownerPid!=null&&Yw(Y.ownerPid);if(Y&&!A){E("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,w.verbose),await n$(w);return}let X=await iQ(w.verbose);if(X.length>0)E("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,w.verbose);await xQ(w.verbose)}var mY=15353,XG="# managed-by: rpx",JG="/etc/resolver",r0=null,k8;var gY=a(()=>{x8();wG();g$();f0();k8=new Set});import{spawn as KG}from"node:child_process";import*as i0 from"node:fs/promises";import{homedir as FG}from"node:os";import*as Ow from"node:path";import*as y from"node:process";function V0(){return Ow.join(FG(),".stacks","rpx")}function S$(w=V0()){return Ow.join(w,"daemon.pid")}async function L$(w=V0()){try{let $=await i0.readFile(S$(w),"utf8"),Y=Number.parseInt($.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch($){if($.code==="ENOENT")return null;throw $}}async function u8(w=V0()){let $=await L$(w);return $!==null&&Yw($)}async function TG(w=V0()){await i0.mkdir(w,{recursive:!0});let $=S$(w);while(!0){try{let A=await i0.open($,"wx");try{await A.write(`${y.pid}
295
+ `)}finally{await A.close()}return $}catch(A){if(A.code!=="EEXIST")throw A}let Y=await L$(w);if(Y!==null&&Yw(Y))throw Error(`rpx daemon already running (pid=${Y})`);await i0.unlink($).catch(()=>{})}}async function d1(w=V0()){await i0.unlink(S$(w)).catch(()=>{})}function b8(w){for(let[$,Y]of i8)if(!w.has($))b1(Y),i8.delete($)}function zR(w,$){let Y=f2($??"localhost:1");if(w.upstreams.length!==Y.length)return!1;return w.upstreams.every((A,X)=>A.url===Y[X])}function qG(w){let $=w.cleanUrls??!1,Y=X$(w.path),A=VY(w.auth);if(w.static)return{static:q8(w.static,$),cleanUrls:$,basePath:Y,auth:A};let X=w.from??"localhost:1",J=u$(X),U=new URL(J.startsWith("http")?J:`http://${J}`),Q=i8.get(w.id);if(Q&&!zR(Q,X))b1(Q),Q=void 0;if(!Q)Q=MY(X,w.loadBalancer),IY(Q),i8.set(w.id,Q);return{sourceHost:U.host,upstreamPool:Q,cleanUrls:$,changeOrigin:w.changeOrigin??!1,pathRewrites:w.pathRewrites,basePath:Y,auth:A}}function GR(w){return w.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??w[0]??"rpx.localhost"}async function P8(w,$,Y=[],A=!1){let X=await zw($,w.verbose),J=[...new Set([...X.map((B)=>B.to).filter(Boolean),...Y])],U=GR(J),Q=[...new Set([U,...J,"rpx.localhost"])],W=U2(J,U,w.verbose);if(typeof w.https==="object"&&typeof W.https==="object")W.https={...W.https,...w.https};let j=await y$(W);if(j&&(A||!EW(WQ,Q)))E("daemon",`regenerating shared cert for host(s): ${Q.join(", ")}`,w.verbose),QQ(),j=null;if(!j)E("daemon","no usable cert on disk, generating one via tlsx",w.verbose),await HY({...W,forceRegenerate:!0}),j=await y$(W);if(!j)throw Error("failed to bootstrap TLS for rpx daemon");return j}async function ER(w,$,Y,A){let X=y.env.SUDO_PASSWORD,J=y.env.HOME??FG(),U=[y.execPath,...y.argv.slice(1)],Q=[`HOME=${J}`,`PATH=${y.env.PATH??""}`];if(A)Q.push("RPX_VERBOSE=1");for(let[T,K]of Object.entries(y.env))if(K!==void 0&&T!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(T))Q.push(`${T}=${K}`);let W=X?["-S","-p","","env",...Q,...U]:["-n","env",...Q,...U];E("daemon",`elevating daemon via sudo for privileged ports ${$}/${Y}`,A);let j=KG("sudo",W,{detached:!0,stdio:["pipe","ignore","ignore"]}),B=null,f=null;if(j.once("error",(T)=>{B=T}),j.once("exit",(T)=>{f=T??0}),X&&j.stdin)j.stdin.write(`${X}
296
+ `),j.stdin.end();j.unref();let z=S$(w),G=Date.now()+15000;while(Date.now()<G){if(B)throw B;let T=await L$(w);if(T!==null&&Yw(T)){if(A)H.success(`rpx daemon elevated to root (pid=${T}, https on :${$})`);return{httpsPort:$,httpPort:Y,pidPath:z,done:Promise.resolve(),stop:async()=>{try{y.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(f!==null&&f!==0)throw Error(`rpx daemon could not elevate to bind :${$} (sudo exited ${f}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((K)=>setTimeout(K,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${w})`)}function uQ(){if(zG)return;zG=!0,y.on("uncaughtException",(w)=>{H.error(`rpx daemon: uncaught exception (continuing): ${w?.stack??w}`)}),y.on("unhandledRejection",(w)=>{H.error(`rpx daemon: unhandled rejection (continuing): ${w}`)})}function NG(w,$,Y){let A;try{A=new URL(w.url)}catch{return new Response("Bad Request",{status:400})}let X=(w.headers.get("host")??A.hostname).split(":")[0];if(A.pathname.startsWith("/.well-known/acme-challenge/")){if($){let J=$.challengeStore.handlePath(A.pathname);if(J!==void 0)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(Y){let J=H8(Y,A.pathname);if(J!=null)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if($)return new Response("challenge not found",{status:404})}if($&&!$.hasCert(X))$.ensureCert(X).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${X}${A.pathname}${A.search}`}})}async function HG(w={}){uQ();let $=w.verbose??!1,Y=w.rpxDir??V0(),A=w.registryDir??Ow.join(Y,"registry.d"),X=w.httpsPort??443,J=w.httpPort??80,U=w.hostname??"0.0.0.0",Q=w.gcIntervalMs??fR;if(y.env.RPX_DAEMON_WORKER==="1")return TR({rpxDir:y.env.RPX_WORKER_RPXDIR??Y,registryDir:y.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(y.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:y.env.RPX_WORKER_HOSTNAME??U,verbose:y.env.RPX_WORKER_VERBOSE==="1"||$});let W=X>0&&X<1024||J>0&&J<1024,j=typeof y.getuid==="function"&&y.getuid()===0;if(y.platform!=="win32"&&W&&!j)return ER(Y,X,J,$);let B=Math.max(1,w.workers??(Number.parseInt(y.env.RPX_WORKERS??"",10)||1));if(B>1){if(w.onDemandSites?.enabled)H.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return qR(w,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:$,gcIntervalMs:Q,workers:B})}let f=await TG(Y),z=new Map,G=(I,D)=>_Y(z,I,D);function T(I){z=hY(I.map((Lw)=>({host:Lw.to,path:Lw.path,route:qG(Lw)}))),b8(new Set(I.map((Lw)=>Lw.id)));let D=Array.from(z.keys());E("daemon",`routing table now covers ${D.length} host(s): ${D.join(", ")||"<empty>"}`,$)}await xY(A,$).catch((I)=>{E("daemon",`initial gc failed: ${I}`,$)}),await vY({verbose:$}).catch((I)=>{E("daemon",`stale hosts GC on start failed: ${I}`,$)});let K=await zw(A,$);T(K),await l$({rpxDir:Y,verbose:$}).catch((I)=>{E("daemon",`DNS reconcile on start failed: ${I}`,$)}),await g1(K,{rpxDir:Y,verbose:$,ownerPid:y.pid}).catch((I)=>{E("daemon",`DNS setup on start failed: ${I}`,$)});let F=[];if(w.productionCerts){if(F=await kY(w.productionCerts,$),$&&F.length>0)H.info(`SNI: serving ${F.length} real cert(s): ${F.map((I)=>I.serverName).join(", ")}`)}let q=new Set,R=null,L;if(w.onDemandSites?.enabled){if(R=new IQ({resolver:XU(w.onDemandSites),registryDir:A,rpxDir:Y,verbose:$,startupTimeoutMs:w.onDemandSites.startupTimeoutMs,isHostRoutable:(I)=>EQ(z,I)!==void 0,onSiteActivating:(I)=>{Cw(I)}}),L=async(I)=>{let D=await R.onRequest(I);switch(D.kind){case"ready":return{retry:!0};case"starting":return m2({host:D.host,sinceMs:D.sinceMs,logTail:D.logTail});case"failed":return g2({host:D.host,error:D.error,logTail:D.logTail});case"unknown":default:return}},$)H.info("rpx: on-demand sites enabled")}let V=SY(G,$,L),N=OY($),M=null;if(F.length===0)M=await P8(w,A);let C=w.onDemandTls,h=C?.enabled?new u1({config:C,certsDir:C.certsDir??w.productionCerts?.certsDir??Ow.join(Y,"on-demand-certs"),initial:F,verbose:$,onCertAdded:(I)=>{if(ZY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",$),setTimeout(()=>y.kill(y.pid,"SIGTERM"),10).unref();else Zw(I)}}):null;function J0(I){if(I.length>0)return c$(I.map((D)=>({serverName:D.serverName,cert:D.cert,key:D.key})));return c$({key:M.key,cert:M.cert,ca:M.ca,requestCert:!1,rejectUnauthorized:!1})}function u0(I){return Bun.serve({port:X,hostname:U,reusePort:qY(),tls:J0(I),fetch(D,Lw){return V(D,Lw)},websocket:N,error(D){return E("daemon",`https server error: ${D}`,$),new Response(`Server Error: ${D.message}`,{status:500})}})}let Gw=(I)=>[...new Set(I.map((D)=>D.to).filter(Boolean))],O$=(I)=>{if(!M)return F;return J2([...Gw(I),...q,"rpx.localhost"],M)},Dw=u0(h?h.sniEntries():F.length>0?F:O$(K)),kw=null,Ew=!1;async function Zw(I){if(Vw)return;if(kw=I,Ew)return;Ew=!0;try{while(!Vw&&kw){let D=kw;kw=null,E("daemon",`rebuilding :443 with ${D.length} SNI cert(s)`,$),Dw.stop(!1);let Lw,e8=!1,pQ=60,iG=500;for(let wJ=0;!Vw&&!e8;wJ++)try{Dw=u0(D),e8=!0;break}catch(bG){if(Lw=bG,wJ>=pQ)break;await new Promise((uG)=>setTimeout(uG,Math.min(25*2**Math.min(wJ,4),iG)))}if(!e8)H.error(`rpx: CRITICAL — could not rebind :443 after ${pQ} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Lw?.message}`)}}finally{Ew=!1}}let t0=null;if(J>0)t0=Bun.serve({port:J,hostname:U,fetch(I){return NG(I,h,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if($)H.success(`rpx daemon listening on https://${U}:${X}${t0?` (http→https on :${J})`:""}`),H.info(`pid file: ${f}`),H.info(`registry: ${A}`);async function _(I){if(Vw||F.length>0||h||!M)return;try{M=await P8(w,A,[...q]),await Zw(O$(I))}catch(D){E("daemon",`TLS sync on registry change failed: ${D}`,$)}}async function Cw(I){if(Vw||F.length>0||h||!M||!I)return;if(q.has(I))return;q.add(I);try{M=await P8(w,A,[...q],!0);let D=await zw(A,$);await Zw(O$(D))}catch(D){E("daemon",`dev cert refresh for ${I} failed: ${D}`,$)}}let n1=L8((I)=>{T(I),_(I),g1(I,{rpxDir:Y,verbose:$,ownerPid:y.pid}).catch((D)=>{E("daemon",`DNS sync on registry change failed: ${D}`,$)})},{dir:A,verbose:$}),p$=setInterval(()=>{xY(A,$).then((I)=>{if(I>0)E("daemon",`gc reaped ${I} stale entries`,$)}).catch((I)=>{E("daemon",`periodic gc failed: ${I}`,$)}),vY({verbose:$}).then((I)=>{if(I.length>0)E("daemon",`gc reaped stale hosts entries: ${I.join(", ")}`,$)}).catch((I)=>{E("daemon",`periodic hosts gc failed: ${I}`,$)})},Q);if(typeof p$.unref==="function")p$.unref();let Vw=!1,l1,r$=new Promise((I)=>{l1=I});async function o8(){if(Vw)return r$;if(Vw=!0,clearInterval(p$),n1.close(),await R?.stopAll().catch((I)=>{E("daemon",`site supervisor stopAll failed: ${I}`,$)}),Dw.stop(!1),t0?.stop(!1),await n$({rpxDir:Y,verbose:$}).catch((I)=>{E("daemon",`DNS teardown failed: ${I}`,$)}),b8(new Set),await d1(Y),$)H.info("rpx daemon stopped");return l1(),r$}let lQ=(I)=>{E("daemon",`received ${I}, shutting down`,$),o8().catch(()=>{})};return y.once("SIGINT",lQ),y.once("SIGTERM",lQ),{stop:o8,done:r$,httpsPort:typeof Dw.port==="number"?Dw.port:X,httpPort:t0&&typeof t0.port==="number"?t0.port:J,pidPath:f,ensureCert:(I)=>h?h.ensureCert(I):Promise.resolve(!1),listSites:()=>R?.list()??[]}}function vQ(w){return Ow.join(w,"cluster-sni.json")}async function GG(w,$,Y){let A=vQ(w),X=`${A}.${y.pid}.tmp`;await i0.writeFile(X,JSON.stringify({sni:$,dev:Y}),"utf8"),await i0.rename(X,A)}async function EG(w){try{return JSON.parse(await i0.readFile(vQ(w),"utf8"))}catch{return{sni:[],dev:null}}}function KR(w){if(w.sni.length>0)return c$(w.sni.map(($)=>({serverName:$.serverName,cert:$.cert,key:$.key})));if(w.dev)return c$({key:w.dev.key,cert:w.dev.cert,ca:w.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function FR(){let w=y.execPath,$=y.env.RPX_WORKER_BIN;if($)return[w,$,"daemon:start"];let Y=Ow.basename(w).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&y.argv[1])return[w,y.argv[1],"daemon:start"];return[w,"daemon:start"]}async function TR(w){uQ();let{rpxDir:$,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=w,U=new Map,Q=(M,C)=>_Y(U,M,C),W=(M)=>{U=hY(M.map((C)=>({host:C.to,path:C.path,route:qG(C)}))),b8(new Set(M.map((C)=>C.id)))};W(await zw(Y,J));let j=SY(Q,J),B=OY(J),f=!1,z=(M)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:KR(M),fetch(C,h){return j(C,h)},websocket:B,error(C){return E("daemon",`worker https error: ${C}`,J),new Response(`Server Error: ${C.message}`,{status:500})}}),G=z(await EG($));async function T(){if(f)return;let M=await EG($),C=null;for(let J0=0;J0<20&&!f;J0++)try{C=z(M);break}catch{await new Promise((u0)=>setTimeout(u0,25))}if(!C){E("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let h=G;G=C,h.stop(!1)}let K=L8((M)=>W(M),{dir:Y,verbose:J}),F=()=>{T().catch(()=>{})};y.on("SIGHUP",F);let q=()=>{let M=y.removeListener??y.off;if(typeof M==="function")M.call(y,"SIGHUP",F)},R,L=new Promise((M)=>{R=M});async function V(){if(f)return L;return f=!0,q(),K.close(),G.stop(!1),b8(new Set),R(),L}let N=()=>{V().then(()=>y.exit(0)).catch(()=>y.exit(0))};if(y.once("SIGTERM",N),y.once("SIGINT",N),J)H.success(`rpx worker (pid ${y.pid}) serving :${A}`);return{stop:V,done:L,httpsPort:typeof G.port==="number"?G.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function qR(w,$){uQ();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:Q,gcIntervalMs:W,workers:j}=$,B=await TG(Y),f=[];if(w.productionCerts)f=await kY(w.productionCerts,Q);let z=null;if(f.length===0)z=await P8(w,A);let G=z?{key:z.key,cert:z.cert,ca:Array.isArray(z.ca)?z.ca.join(`
297
+ `):z.ca}:null,T=!1,K=[];function F(_){for(let Cw of K)try{Cw.kill(_)}catch{}}async function q(_){await GG(Y,_,G),F("SIGHUP")}let R=w.onDemandTls,L=R?.enabled?new u1({config:R,certsDir:R.certsDir??w.productionCerts?.certsDir??Ow.join(Y,"on-demand-certs"),initial:f,verbose:Q,onCertAdded:(_)=>{if(ZY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",Q),setTimeout(()=>y.kill(y.pid,"SIGTERM"),10).unref();else q(_)}}):null;await GG(Y,L?L.sniEntries():f,G);let V=await zw(A,Q);await l$({rpxDir:Y,verbose:Q}).catch((_)=>{E("daemon",`DNS reconcile on start failed: ${_}`,Q)}),await g1(V,{rpxDir:Y,verbose:Q,ownerPid:y.pid}).catch((_)=>{E("daemon",`DNS setup on start failed: ${_}`,Q)}),await xY(A,Q).catch(()=>{}),await vY({verbose:Q}).catch(()=>{});let N=L8((_)=>{g1(_,{rpxDir:Y,verbose:Q,ownerPid:y.pid}).catch((Cw)=>{E("daemon",`DNS sync on registry change failed: ${Cw}`,Q)})},{dir:A,verbose:Q}),M=setInterval(()=>{xY(A,Q).catch(()=>{}),vY({verbose:Q}).catch(()=>{})},W);M.unref?.();let C=null;if(J>0)C=Bun.serve({port:J,hostname:U,fetch(_){return NG(_,L,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let h=10,J0=60000,u0=30000,Gw=0,O$=Date.now();function Dw(){if(T)return;let _={...y.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:Q?"1":"0"},Cw=Bun.spawn(FR(),{env:_,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(n1,p$){if(T)return;let Vw=K.indexOf(n1);if(Vw!==-1)K.splice(Vw,1);let l1=Date.now();if(l1-O$>J0)O$=l1,Gw=0;if(Gw++,Gw>h){H.error(`rpx: worker keeps exiting (code ${p$}); giving up after ${h} restarts in ${Math.round(J0/1000)}s`);return}let r$=Math.min(u0,100*2**Math.min(Gw,8));E("daemon",`worker exited (code ${p$}); respawning in ${r$}ms (restart ${Gw}/${h})`,Q),setTimeout(Dw,r$).unref?.()}});K.push(Cw)}for(let _=0;_<j;_++)Dw();if(Q)H.success(`rpx coordinator listening on https://${U}:${X} via ${j} worker(s)${C?` (http→https on :${J})`:""}`),H.info(`pid file: ${B}`);let kw,Ew=new Promise((_)=>{kw=_});async function Zw(){if(T)return Ew;if(T=!0,clearInterval(M),N.close(),C?.stop(!1),F("SIGTERM"),await Promise.race([Promise.all(K.map((_)=>_.exited)),new Promise((_)=>setTimeout(_,3000))]),F("SIGKILL"),await n$({rpxDir:Y,verbose:Q}).catch((_)=>{E("daemon",`DNS teardown failed: ${_}`,Q)}),await d1(Y),await i0.unlink(vQ(Y)).catch(()=>{}),Q)H.info("rpx coordinator stopped");return kw(),Ew}let t0=(_)=>{E("daemon",`coordinator received ${_}, shutting down`,Q),Zw().catch(()=>{})};return y.once("SIGINT",t0),y.once("SIGTERM",t0),{stop:Zw,done:Ew,httpsPort:X,httpPort:J,pidPath:B,ensureCert:(_)=>L?L.ensureCert(_):Promise.resolve(!1),listSites:()=>[]}}function NR(){let w=y.execPath,$=Ow.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&y.argv[1])return[w,y.argv[1],"daemon:start"];return[w,"daemon:start"]}async function v8(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1;await l$({rpxDir:$,verbose:Y}).catch((B)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${B}`,Y)});let A=await L$($);if(A!==null&&Yw(A))return E("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)E("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await d1($);await i0.mkdir($,{recursive:!0});let X=w.spawnCommand??NR();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=KG(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??y.cwd(),env:w.spawnEnv?{...y.env,...w.spawnEnv}:y.env});J.unref();let U=null;J.once("error",(B)=>{U=B});let Q=w.startupTimeoutMs??5000,W=w.pollIntervalMs??50,j=Date.now()+Q;while(Date.now()<j){if(U)throw U;let B=await L$($);if(B!==null&&Yw(B))return E("daemon",`daemon registered with pid=${B}`,Y),{pid:B,spawned:!0};await new Promise((f)=>setTimeout(f,W))}if(U)throw U;throw Error(`rpx daemon failed to start within ${Q}ms (rpxDir=${$})`)}async function RG(w={}){let $=w.rpxDir??V0(),Y=w.verbose??!1,A=w.timeoutMs??5000,X=w.pollIntervalMs??50,J=w.forceAfterTimeout??!0,U=await L$($);if(U===null||!Yw(U)){if(U!==null)await d1($);return await l$({rpxDir:$,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{y.kill(U,"SIGTERM")}catch(W){let j=W.code;if(j==="ESRCH")return await d1($),{stopped:!1,pid:U,forced:!1};if(j==="EPERM")q$(`kill -TERM ${U}`);else throw W}let Q=Date.now()+A;while(Date.now()<Q){if(!Yw(U))return E("daemon",`daemon pid=${U} stopped cleanly`,Y),{stopped:!0,pid:U,forced:!1};await new Promise((W)=>setTimeout(W,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${A}ms`);E("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{y.kill(U,"SIGKILL")}catch(W){let j=W.code;if(j==="EPERM")q$(`kill -KILL ${U}`);else if(j!=="ESRCH")throw W}return await d1($),await n$({rpxDir:$,verbose:Y}).catch((W)=>{E("daemon",`DNS teardown after SIGKILL: ${W}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function MG(w={}){let $=w.rpxDir??V0();if(await u8($))return;await l$({rpxDir:$,verbose:w.verbose})}var fR=5000,i8,zG=!1;var x8=a(()=>{k$();jQ();zQ();GQ();R8();FQ();TQ();JU();v2();N8();K8();g$();SQ();gY();f0();i8=new Map});import{dirname as kR,join as ZR}from"node:path";import*as P0 from"node:process";import{fileURLToPath as xR}from"node:url";import{existsSync as dG}from"node:fs";import $J from"node:fs/promises";import tQ from"node:os";import YJ from"node:path";import h$ from"node:process";import{EventEmitter as nG}from"node:events";import W$ from"node:process";import aQ from"node:process";import UJ from"node:process";import rY from"node:process";import t1 from"node:process";import eQ from"node:tty";import D5,{stdin as $M,stdout as YM}from"node:process";import $j,{stdin as x5,stdout as P5}from"node:process";import i5 from"node:readline";class Aj{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let w=tQ.homedir(),$=YJ.join(w,".config","clapp");this.configPath=YJ.join($,"telemetry.json")}async isEnabled(){if(h$.env.DO_NOT_TRACK==="1"||h$.env.DO_NOT_TRACK==="true")return!1;if(h$.env.NO_TELEMETRY==="1"||h$.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let w=await this.loadConfig();if(w.enabled=!0,!w.userId)w.userId=this.generateUserId();await this.saveConfig(w)}async disable(){let w=await this.loadConfig();w.enabled=!1,await this.saveConfig(w)}async track(w,$){if(!await this.isEnabled())return;let A={event:w,...$,timestamp:Date.now(),platform:tQ.platform(),nodeVersion:h$.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand(w,$){await this.track("command",{command:w,duration:$})}async trackError(w,$){await this.track("error",{error:w,command:$})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let $=await this.loadConfig();return $.lastSent=Date.now(),await this.saveConfig($),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let $=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep($),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(w){return new Promise(($)=>setTimeout($,w))}async status(){let w=await this.loadConfig();return{enabled:w.enabled,doNotTrack:h$.env.DO_NOT_TRACK==="1"||h$.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:w.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(dG(this.configPath)){let w=await $J.readFile(this.configPath,"utf-8");return this.config=JSON.parse(w),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(w){this.config=w;try{let $=YJ.dirname(this.configPath);await $J.mkdir($,{recursive:!0}),await $J.writeFile(this.configPath,JSON.stringify(w,null,2),"utf-8")}catch{}}generateUserId(){let w=Math.random().toString(36).substring(2,15),$=Date.now().toString(36);return`${w}-${$}`}}var gR=new Aj;function lG(w,$={}){let Y={_:[]},A=$.alias||{},X=new Set($.boolean||[]),J={};for(let Q of Object.keys(A))for(let W of A[Q])J[W]=Q;for(let Q of X)if(A[Q])for(let W of A[Q])X.add(W);function U(Q,W){let j=J[Q]||Q;if(Y[j]=W,A[j])for(let B of A[j])Y[B]=W;if(J[Q]&&A[J[Q]])for(let B of A[J[Q]])Y[B]=W;Y[Q]=W}for(let Q=0;Q<w.length;Q++){let W=w[Q];if(W==="--"){Y._.push(...w.slice(Q+1));break}if(W.startsWith("--")){let j=W.indexOf("=");if(j!==-1){let B=W.slice(2,j),f=W.slice(j+1);U(B,f)}else{let B=W.slice(2);if(B.startsWith("no-")){let z=B.slice(3);U(z,!1);continue}let f=J[B]||B;if(X.has(f)||X.has(B))U(B,!0);else{let z=w[Q+1];if(z!==void 0&&!z.startsWith("-"))U(B,z),Q++;else U(B,!0)}}}else if(W.startsWith("-")&&W.length>1){let j=W.slice(1);for(let B=0;B<j.length;B++){let f=j[B],z=J[f]||f;if(B===j.length-1&&!X.has(z)&&!X.has(f)){let G=w[Q+1];if(G!==void 0&&!G.startsWith("-"))U(f,G),Q++;else U(f,!0)}else U(f,!0)}}else Y._.push(W)}return Y}function JJ(w){return w.replace(/[<[].+/,"").trim()}function pG(w){let $=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],X=(Q)=>{let W=!1,j=Q[1];if(j.startsWith("..."))j=j.slice(3),W=!0;return{required:Q[0].startsWith("<"),value:j,variadic:W}},J;while(J=$.exec(w))A.push(X(J));let U;while(U=Y.exec(w))A.push(X(U));return A}function rG(w){let $={alias:{},boolean:[]};for(let[Y,A]of w.entries()){if(A.names.length>1)$.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!w.some((J,U)=>{return U!==Y&&J.names.some((Q)=>A.names.includes(Q))&&typeof J.required==="boolean"}))$.boolean.push(A.names[0])}else $.boolean.push(A.names[0])}return $}function sQ(w){return w.reduce(($,Y)=>$.length>=Y.length?$:Y,"")}function AJ(w,$){return w.length>=$?w:`${w}${" ".repeat($-w.length)}`}function tG(w){return w.replace(/([a-z])-([a-z])/g,($,Y,A)=>{return Y+A.toUpperCase()})}function aG(w,$,Y){let A=0,X=$.length,J=w,U;for(;A<X;++A)U=J[$[A]],J=J[$[A]]=A===X-1?Y:U!=null?U:!!~$[A+1].indexOf(".")||!(+$[A+1]>-1)?{}:[]}function sG(w,$){for(let Y of Object.keys($)){let A=$[Y];if(A.shouldTransform){if(w[Y]=Array.prototype.concat.call([],w[Y]),typeof A.transformFunction==="function")w[Y]=w[Y].map(A.transformFunction)}}}function oG(w){let $=/([^\\/]+)$/.exec(w);return $?$[1]:""}function Xj(w){return w.split(".").map(($,Y)=>{return Y===0?tG($):$}).join(".")}class pY extends Error{exitCode=2;isUsageError=!0;constructor(w){super(w);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(w).stack}format(w=!1){if(w&&this.stack)return`${this.message}
297
298
 
298
299
  Stack trace:
299
- ${this.stack}`;return this.message}}function C6(){let{env:w}=HB,{TERM:$,TERM_PROGRAM:Y}=w;if(HB.platform!=="win32")return $!=="linux";return Boolean(w.WT_SESSION)||Boolean(w.TERMINUS_SUBLIME)||w.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||w.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var BA="\x1B",j0=`${BA}[`;var cw={to(w,$){if(!$)return`${j0}${w+1}G`;return`${j0}${$+1};${w+1}H`},move(w,$){let Y="";if(w<0)Y+=`${j0}${-w}D`;else if(w>0)Y+=`${j0}${w}C`;if($<0)Y+=`${j0}${-$}A`;else if($>0)Y+=`${j0}${$}B`;return Y},up:(w=1)=>`${j0}${w}A`,down:(w=1)=>`${j0}${w}B`,forward:(w=1)=>`${j0}${w}C`,backward:(w=1)=>`${j0}${w}D`,nextLine:(w=1)=>`${j0}E`.repeat(w),prevLine:(w=1)=>`${j0}F`.repeat(w),left:`${j0}G`,hide:`${j0}?25l`,show:`${j0}?25h`,save:`${BA}7`,restore:`${BA}8`};var HJ={screen:`${j0}2J`,up:(w=1)=>`${j0}1J`.repeat(w),down:(w=1)=>`${j0}J`.repeat(w),line:`${j0}2K`,lineEnd:`${j0}K`,lineStart:`${j0}1K`,lines(w){let $="";for(let Y=0;Y<w;Y++)$+=this.line+(Y<w-1?cw.up():"");if(w)$+=cw.left;return $}},dM={screen:`${BA}c`};function y6(w,$){let Y=[];for(let A=0;A<=$.length;A++)Y[A]=[A];for(let A=0;A<=w.length;A++)Y[0][A]=A;for(let A=1;A<=$.length;A++)for(let X=1;X<=w.length;X++)if($.charAt(A-1)===w.charAt(X-1))Y[A][X]=Y[A-1][X-1];else Y[A][X]=Math.min(Y[A-1][X-1]+1,Y[A][X-1]+1,Y[A-1][X]+1);return Y[$.length][w.length]}function _B(w,$,Y=2,A=3){return $.map((X)=>({cmd:X,distance:y6(w,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class SB{rawName;description;name;names;isBoolean;required;config;negated;constructor(w,$,Y){if(this.rawName=w,this.description=$,this.config=Object.assign({},Y),w=w.replace(/\.\*/g,""),this.negated=!1,this.names=RJ(w).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return LB(X)}).sort((A,X)=>A.length>X.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(w.includes("<"))this.required=!0;else if(w.includes("["))this.required=!1;else this.isBoolean=!0}}var nM=MJ.argv,O6=`${MJ.platform}-${MJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,MB=UA.argv,L6=`${UA.platform}-${UA.arch} node-${UA.version}`;class IJ{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(w,$,Y,A){this.rawName=w,this.description=$,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=RJ(w);let X=RJ(w),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=T6(w),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage(w){return this.usageText=w,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(w,$="-v, --version"){return this.versionNumber=w,this.option($,"Display version number"),this}example(w){return this.examples.push(w),this}option(w,$,Y){let A=new SB(w,$,Y);return this.options.push(A),this}alias(w){return this.aliasNames.push(w),this}action(w){return this.commandAction=w,this}before(w){return this.beforeHooks.push(w),this}after(w){return this.afterHooks.push(w),this}use(w){return this.middleware.push(w),this}isMatched(w){if(this.aliasNames.includes(w))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===w;return this.name===w}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof VJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(w){return w=w.split(".")[0],!!this.options.find(($)=>{return $.names.includes(w)})}outputHelp(){let{name:w,commands:$}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${w}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${w} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let Q=RB($.map((K)=>K.rawName)),B=new Map,j=[];for(let K of $)if(K.namespace){if(!B.has(K.namespace))B.set(K.namespace,[]);B.get(K.namespace).push(K)}else j.push(K);let z="";if(j.length>0)z+=j.map((K)=>{return` ${TJ(K.rawName,Q.length)} ${K.description}`}).join(`
300
- `);let G=Array.from(B.keys()).sort();for(let K of G){let E=B.get(K);if(z.length>0)z+=`
300
+ ${this.stack}`;return this.message}}function eG(){let{env:w}=aQ,{TERM:$,TERM_PROGRAM:Y}=w;if(aQ.platform!=="win32")return $!=="linux";return Boolean(w.WT_SESSION)||Boolean(w.TERMINUS_SUBLIME)||w.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||$==="xterm-256color"||$==="alacritty"||$==="rxvt-unicode"||$==="rxvt-unicode-256color"||w.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var sY="\x1B",j0=`${sY}[`;var xw={to(w,$){if(!$)return`${j0}${w+1}G`;return`${j0}${$+1};${w+1}H`},move(w,$){let Y="";if(w<0)Y+=`${j0}${-w}D`;else if(w>0)Y+=`${j0}${w}C`;if($<0)Y+=`${j0}${-$}A`;else if($>0)Y+=`${j0}${$}B`;return Y},up:(w=1)=>`${j0}${w}A`,down:(w=1)=>`${j0}${w}B`,forward:(w=1)=>`${j0}${w}C`,backward:(w=1)=>`${j0}${w}D`,nextLine:(w=1)=>`${j0}E`.repeat(w),prevLine:(w=1)=>`${j0}F`.repeat(w),left:`${j0}G`,hide:`${j0}?25l`,show:`${j0}?25h`,save:`${sY}7`,restore:`${sY}8`};var XJ={screen:`${j0}2J`,up:(w=1)=>`${j0}1J`.repeat(w),down:(w=1)=>`${j0}J`.repeat(w),line:`${j0}2K`,lineEnd:`${j0}K`,lineStart:`${j0}1K`,lines(w){let $="";for(let Y=0;Y<w;Y++)$+=this.line+(Y<w-1?xw.up():"");if(w)$+=xw.left;return $}},pR={screen:`${sY}c`};function w5(w,$){let Y=[];for(let A=0;A<=$.length;A++)Y[A]=[A];for(let A=0;A<=w.length;A++)Y[0][A]=A;for(let A=1;A<=$.length;A++)for(let X=1;X<=w.length;X++)if($.charAt(A-1)===w.charAt(X-1))Y[A][X]=Y[A-1][X-1];else Y[A][X]=Math.min(Y[A-1][X-1]+1,Y[A][X-1]+1,Y[A-1][X]+1);return Y[$.length][w.length]}function Jj(w,$,Y=2,A=3){return $.map((X)=>({cmd:X,distance:w5(w,X)})).filter(({distance:X})=>X<=Y).sort((X,J)=>X.distance-J.distance).slice(0,A).map(({cmd:X})=>X)}class Uj{rawName;description;name;names;isBoolean;required;config;negated;constructor(w,$,Y){if(this.rawName=w,this.description=$,this.config=Object.assign({},Y),w=w.replace(/\.\*/g,""),this.negated=!1,this.names=JJ(w).split(",").map((A)=>{let X=A.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return Xj(X)}).sort((A,X)=>A.length>X.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(w.includes("<"))this.required=!0;else if(w.includes("["))this.required=!1;else this.isBoolean=!0}}var tR=UJ.argv,$5=`${UJ.platform}-${UJ.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,oQ=rY.argv,Y5=`${rY.platform}-${rY.arch} node-${rY.version}`;class WJ{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(w,$,Y,A){this.rawName=w,this.description=$,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=JJ(w);let X=JJ(w),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=pG(w),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage(w){return this.usageText=w,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(w,$="-v, --version"){return this.versionNumber=w,this.option($,"Display version number"),this}example(w){return this.examples.push(w),this}option(w,$,Y){let A=new Uj(w,$,Y);return this.options.push(A),this}alias(w){return this.aliasNames.push(w),this}action(w){return this.commandAction=w,this}before(w){return this.beforeHooks.push(w),this}after(w){return this.afterHooks.push(w),this}use(w){return this.middleware.push(w),this}isMatched(w){if(this.aliasNames.includes(w))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===w;return this.name===w}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof QJ}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(w){return w=w.split(".")[0],!!this.options.find(($)=>{return $.names.includes(w)})}outputHelp(){let{name:w,commands:$}=this.cli,{versionNumber:Y,options:A,helpCallback:X}=this.cli.globalCommand,J=[{body:`${w}${Y?`/${Y}`:""}`}];if(J.push({title:"Usage",body:` $ ${w} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&$.length>0){let W=sQ($.map((G)=>G.rawName)),j=new Map,B=[];for(let G of $)if(G.namespace){if(!j.has(G.namespace))j.set(G.namespace,[]);j.get(G.namespace).push(G)}else B.push(G);let f="";if(B.length>0)f+=B.map((G)=>{return` ${AJ(G.rawName,W.length)} ${G.description}`}).join(`
301
+ `);let z=Array.from(j.keys()).sort();for(let G of z){let T=j.get(G);if(f.length>0)f+=`
301
302
 
302
- `;z+=` ${K}:
303
- `,z+=E.map((q)=>{return` ${TJ(q.rawName,Q.length-2)} ${q.description}`}).join(`
304
- `)}J.push({title:"Commands",body:z}),J.push({title:"For more info, run any command with the `--help` flag",body:$.map((K)=>` $ ${w}${K.displayName===""?"":` ${K.displayName}`} --help`).join(`
305
- `)})}let W=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)W=W.filter((Q)=>Q.name!=="version");if(W.length>0){let Q=RB(W.map((B)=>B.rawName));J.push({title:"Options",body:W.map((B)=>{return` ${TJ(B.rawName,Q.length)} ${B.description} ${B.config.default===void 0?"":`(default: ${B.config.default})`}`}).join(`
306
- `)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((Q)=>{if(typeof Q==="function")return Q(w);return Q}).join(`
307
- `)});if(X)J=X(J)||J;console.log(J.map((Q)=>{return Q.title?`${Q.title}:
308
- ${Q.body}`:Q.body}).join(`
303
+ `;f+=` ${G}:
304
+ `,f+=T.map((K)=>{return` ${AJ(K.rawName,W.length-2)} ${K.description}`}).join(`
305
+ `)}J.push({title:"Commands",body:f}),J.push({title:"For more info, run any command with the `--help` flag",body:$.map((G)=>` $ ${w}${G.displayName===""?"":` ${G.displayName}`} --help`).join(`
306
+ `)})}let Q=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)Q=Q.filter((W)=>W.name!=="version");if(Q.length>0){let W=sQ(Q.map((j)=>j.rawName));J.push({title:"Options",body:Q.map((j)=>{return` ${AJ(j.rawName,W.length)} ${j.description} ${j.config.default===void 0?"":`(default: ${j.config.default})`}`}).join(`
307
+ `)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((W)=>{if(typeof W==="function")return W(w);return W}).join(`
308
+ `)});if(X)J=X(J)||J;console.log(J.map((W)=>{return W.title?`${W.title}:
309
+ ${W.body}`:W.body}).join(`
309
310
 
310
- `))}outputVersion(){let{name:w}=this.cli,{versionNumber:$}=this.cli.globalCommand;if($)console.log(`${w}/${$} ${typeof Bun<"u"?O6:L6}`)}checkRequiredArgs(){let w=this.args.filter(($)=>$.required).length;if(this.cli.args.length<w){let Y=this.args.filter((X)=>X.required).slice(this.cli.args.length),A=Y.map((X)=>`<${X.value}>`).join(" ");throw new JA(`Missing required argument${Y.length>1?"s":""}: ${A}
311
+ `))}outputVersion(){let{name:w}=this.cli,{versionNumber:$}=this.cli.globalCommand;if($)console.log(`${w}/${$} ${typeof Bun<"u"?$5:Y5}`)}checkRequiredArgs(){let w=this.args.filter(($)=>$.required).length;if(this.cli.args.length<w){let Y=this.args.filter((X)=>X.required).slice(this.cli.args.length),A=Y.map((X)=>`<${X.value}>`).join(" ");throw new pY(`Missing required argument${Y.length>1?"s":""}: ${A}
311
312
 
312
- Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:w,globalCommand:$}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys(w))if(Y!=="--"&&!this.hasOption(Y)&&!$.hasOption(Y)){let X=[...$.options,...this.options].flatMap((Q)=>Q.names),J=Y.length>1?`--${Y}`:`-${Y}`,U=_B(Y,X),W=`Unknown option \`${J}\``;if(U.length>0)W+=`
313
+ Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:w,globalCommand:$}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys(w))if(Y!=="--"&&!this.hasOption(Y)&&!$.hasOption(Y)){let X=[...$.options,...this.options].flatMap((W)=>W.names),J=Y.length>1?`--${Y}`:`-${Y}`,U=Jj(Y,X),Q=`Unknown option \`${J}\``;if(U.length>0)Q+=`
313
314
 
314
- Did you mean one of these?`,U.forEach((Q)=>{let B=Q.length>1?`--${Q}`:`-${Q}`;W+=`
315
- • ${B}`});throw W+=`
315
+ Did you mean one of these?`,U.forEach((W)=>{let j=W.length>1?`--${W}`:`-${W}`;Q+=`
316
+ • ${j}`});throw Q+=`
316
317
 
317
- Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new JA(W)}}}checkOptionValue(){let{options:w,globalCommand:$}=this.cli,Y=[...$.options,...this.options];for(let A of Y){let X=w[A.name.split(".")[0]];if(A.required){let J=Y.some((U)=>U.negated&&U.names.includes(A.name));if(X===!0||X===!1&&!J)throw new JA(`Option \`${A.rawName}\` requires a value.
318
+ Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new pY(Q)}}}checkOptionValue(){let{options:w,globalCommand:$}=this.cli,Y=[...$.options,...this.options];for(let A of Y){let X=w[A.name.split(".")[0]];if(A.required){let J=Y.some((U)=>U.negated&&U.names.includes(A.name));if(X===!0||X===!1&&!J)throw new pY(`Option \`${A.rawName}\` requires a value.
318
319
 
319
- Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class VJ extends IJ{constructor(w){super("@@global@@","",{},w)}}var _6=IJ,q$={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 zY={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function S6(){return!0}function Z6(){let w={};w.supportsColor=S6();function $(A,X=[]){let J=A===""?[]:[...X,A],U=function(Q){if(!w.supportsColor)return Q;let B="",j="";for(let z of J)if(z in zY&&zY[z]in q$){let G=zY[z];B+=q$[G][0],j=q$[G][1]+j}else if(z in q$)B+=q$[z][0],j=q$[z][1]+j;return B+Q+j},W=[...Object.keys(q$),...Object.keys(zY)];for(let Q of W)if(!(Q in U))Object.defineProperty(U,Q,{get(){return $(Q,J)}});return U}let Y=[...Object.keys(q$),...Object.keys(zY)];for(let A of Y)if(!(A in w))Object.defineProperty(w,A,{get(){return $(A)}});return w}var GY=Z6();class CJ extends E6{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(w=""){super();this.name=w,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new VJ(this),this.globalCommand.usage("<command> [options]")}handleSignals(w){if(this.signalHandlersSet)return this;let $=async(Y)=>{if(console.log(`
320
+ Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class QJ extends WJ{constructor(w){super("@@global@@","",{},w)}}var A5=WJ,Q$={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var p1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function X5(){return!0}function J5(){let w={};w.supportsColor=X5();function $(A,X=[]){let J=A===""?[]:[...X,A],U=function(W){if(!w.supportsColor)return W;let j="",B="";for(let f of J)if(f in p1&&p1[f]in Q$){let z=p1[f];j+=Q$[z][0],B=Q$[z][1]+B}else if(f in Q$)j+=Q$[f][0],B=Q$[f][1]+B;return j+W+B},Q=[...Object.keys(Q$),...Object.keys(p1)];for(let W of Q)if(!(W in U))Object.defineProperty(U,W,{get(){return $(W,J)}});return U}let Y=[...Object.keys(Q$),...Object.keys(p1)];for(let A of Y)if(!(A in w))Object.defineProperty(w,A,{get(){return $(A)}});return w}var r1=J5();class jJ extends nG{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor(w=""){super();this.name=w,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new QJ(this),this.globalCommand.usage("<command> [options]")}handleSignals(w){if(this.signalHandlersSet)return this;let $=async(Y)=>{if(console.log(`
320
321
 
321
- Received ${Y}, cleaning up...`),w)try{await w()}catch(A){console.error("Error during cleanup:",A)}F$.exit(0)};return F$.on("SIGINT",()=>$("SIGINT")),F$.on("SIGTERM",()=>$("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(w=!0){return this.enableDidYouMean=w,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(w){return this.globalCommand.usage(w),this}command(w,$,Y){if(!Y)Y={};let A=new _6(w,$||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option(w,$,Y){return this.globalCommand.option(w,$,Y),this}help(w){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=w,this.showHelpOnExit=!0,this}version(w,$="-v, --version"){return this.globalCommand.version(w,$),this.showVersionOnExit=!0,this}example(w){return this.globalCommand.example(w),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:w,options:$},Y,A){if(this.args=w,this.options=$,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(w){if(console.log(GY.red(`
322
+ Received ${Y}, cleaning up...`),w)try{await w()}catch(A){console.error("Error during cleanup:",A)}W$.exit(0)};return W$.on("SIGINT",()=>$("SIGINT")),W$.on("SIGTERM",()=>$("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean(w=!0){return this.enableDidYouMean=w,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage(w){return this.globalCommand.usage(w),this}command(w,$,Y){if(!Y)Y={};let A=new A5(w,$||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option(w,$,Y){return this.globalCommand.option(w,$,Y),this}help(w){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=w,this.showHelpOnExit=!0,this}version(w,$="-v, --version"){return this.globalCommand.version(w,$),this.showVersionOnExit=!0,this}example(w){return this.globalCommand.example(w),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:w,options:$},Y,A){if(this.args=w,this.options=$,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound(w){if(console.log(r1.red(`
322
323
  ✗ Command "${w}" not found.
323
- `)),this.enableDidYouMean){let $=[];for(let A of this.commands){if(A.displayName)$.push(A.displayName);if(A.aliasNames)$.push(...A.aliasNames)}let Y=_B(w,$);if(Y.length>0)console.log(GY.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${GY.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(GY.dim("Run"),`${this.name} --help`,GY.dim("to see all available commands")),F$.exit(1)}async parse(w=MB,$={}){let{run:Y=!0,exitOnError:A=!1}=$;if(A)try{return await this.parse(w,{run:Y})}catch(Q){throw this.handleUsageError(Q),Q}if(this.rawArgs=w,!this.name)this.name=w[1]?V6(w[1]):"cli";let X=!0,J=w.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let Q of this.commands)if(Q.isMatched(U)){let B=this.mri(J,Q);X=!1;let j={...B,args:B.args.slice(1)};this.setParsedInfo(j,Q,U),this.emit(`command:${U}`,Q);break}}if(X){for(let Q of this.commands)if(Q.name===""){X=!1;let B=this.mri(J,Q);this.setParsedInfo(B,Q),this.emit("command:!",Q);break}}if(X){let Q=this.mri(w.slice(2));this.setParsedInfo(Q)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),Y=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Y=!1,this.unsetMatchedCommand();let W={args:this.args,options:this.options};if(Y)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return W}mri(w,$){let Y=[...this.globalCommand.options,...$?$.options:[]],A=H6(Y),X=[],J=w.indexOf("--");if(J>-1)X=w.slice(J+1),w=w.slice(0,J);let U=f6(w,A),W={_:U._};for(let G of Object.keys(U))if(G!=="_")W[LB(G)]=U[G];let Q=W._,B={"--":X},j=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,z=Object.create(null);for(let G of Y){if(!j&&G.config.default!==void 0)for(let K of G.names)B[K]=G.config.default;if(Array.isArray(G.config.type)){if(z[G.name]===void 0)z[G.name]={shouldTransform:!0,transformFunction:G.config.type[0]}}}for(let G of Object.keys(W))if(G!=="_"){let K=G.split(".");M6(B,K,W[G]),I6(B,z)}return{args:Q,options:B}}async run(w=MB){return this.parse(w,{run:!0,exitOnError:!0})}handleUsageError(w){if(!(!!w&&typeof w==="object"&&w.name==="ClappError"&&w.isUsageError!==!1))return;let A=w,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
324
- Run \`${this.name??"cli"} --help\` for usage.`;F$.stderr.write(`${J}${X}${U}
325
- `),F$.exit(A.exitCode??2)}async runMatchedCommand(){let{args:w,options:$,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((W,Q)=>{if(W.variadic)A.push(w.slice(Q));else A.push(w[Q])}),A.push($);let X={command:Y,args:A,options:$};for(let W of Y.beforeHooks)await W(X);let J,U=async()=>{let W=Y.commandAction.apply(this,A);if(W instanceof Promise)J=await W;else J=W;return J};if(Y.middleware.length>0){let W=0,Q=async()=>{if(W<Y.middleware.length){let B=Y.middleware[W++];await B({...X,next:Q})}else await U()};await Q()}else await U();for(let W of Y.afterHooks)await W(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return F$.removeAllListeners("SIGINT"),F$.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 ZB{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(w){if(!this.enabled){this.misses++;return}let $=this.cache.get(w);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(w),this.misses++;return}return this.hits++,$.value}set(w,$,Y=5000){if(!this.enabled)return;this.cache.set(w,{value:$,timestamp:Date.now(),ttl:Y})}has(w){if(!this.enabled)return!1;let $=this.cache.get(w);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(w),!1;return!0}delete(w){this.cache.delete(w)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let w=Date.now();for(let[$,Y]of this.cache.entries())if(w-Y.timestamp>Y.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var rM=new ZB;function k6(){if("FORCE_COLOR"in KY.env)return KY.env.FORCE_COLOR!=="0";if("NO_COLOR"in KY.env||KY.env.TERM==="dumb")return!1;if(KY.platform==="win32")return!0;return IB.isatty(1)&&IB.isatty(2)}var kB=k6();function A0(w,$){if(!kB)return(Y)=>Y;return(Y)=>w+Y+$}var h6=A0("\x1B[0m","\x1B[0m"),D6=A0("\x1B[31m","\x1B[39m"),x6=A0("\x1B[32m","\x1B[39m"),P6=A0("\x1B[33m","\x1B[39m"),b6=A0("\x1B[34m","\x1B[39m"),u6=A0("\x1B[35m","\x1B[39m"),c6=A0("\x1B[36m","\x1B[39m"),v6=A0("\x1B[37m","\x1B[39m"),i6=A0("\x1B[90m","\x1B[39m"),m6=A0("\x1B[1m","\x1B[22m"),g6=A0("\x1B[3m","\x1B[23m"),d6=A0("\x1B[4m","\x1B[24m"),l6=A0("\x1B[2m","\x1B[22m"),n6=A0("\x1B[7m","\x1B[27m"),p6=A0("\x1B[8m","\x1B[28m"),r6=A0("\x1B[9m","\x1B[29m"),t6=A0("\x1B[41m","\x1B[49m"),a6=A0("\x1B[42m","\x1B[49m"),s6=A0("\x1B[43m","\x1B[49m"),o6=A0("\x1B[44m","\x1B[49m"),e6=A0("\x1B[45m","\x1B[49m"),wK=A0("\x1B[46m","\x1B[49m"),$K=A0("\x1B[47m","\x1B[49m"),YK=kB,AK={reset:h6,red:D6,green:x6,yellow:P6,blue:b6,magenta:u6,cyan:c6,white:v6,gray:i6,bold:m6,italic:g6,underline:d6,dim:l6,inverse:n6,hidden:p6,strikethrough:r6,bgRed:t6,bgGreen:a6,bgYellow:s6,bgBlue:o6,bgMagenta:e6,bgCyan:wK,bgWhite:$K,isColorSupported:YK},QA=AK,JK=["up","down","left","right","space","enter","cancel"],WA={actions:new Set(JK),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function hB(w,$){if(typeof w==="string")return WA.aliases.get(w)===$;for(let Y of w){if(Y===void 0)continue;if(hB(Y,$))return!0}return!1}function UK(w,$){if(w===$)return[];let Y=w.split(`
324
+ `)),this.enableDidYouMean){let $=[];for(let A of this.commands){if(A.displayName)$.push(A.displayName);if(A.aliasNames)$.push(...A.aliasNames)}let Y=Jj(w,$);if(Y.length>0)console.log(r1.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${r1.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(r1.dim("Run"),`${this.name} --help`,r1.dim("to see all available commands")),W$.exit(1)}async parse(w=oQ,$={}){let{run:Y=!0,exitOnError:A=!1}=$;if(A)try{return await this.parse(w,{run:Y})}catch(W){throw this.handleUsageError(W),W}if(this.rawArgs=w,!this.name)this.name=w[1]?oG(w[1]):"cli";let X=!0,J=w.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let W of this.commands)if(W.isMatched(U)){let j=this.mri(J,W);X=!1;let B={...j,args:j.args.slice(1)};this.setParsedInfo(B,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(w.slice(2));this.setParsedInfo(W)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),Y=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Y=!1,this.unsetMatchedCommand();let Q={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 Q}mri(w,$){let Y=[...this.globalCommand.options,...$?$.options:[]],A=rG(Y),X=[],J=w.indexOf("--");if(J>-1)X=w.slice(J+1),w=w.slice(0,J);let U=lG(w,A),Q={_:U._};for(let z of Object.keys(U))if(z!=="_")Q[Xj(z)]=U[z];let W=Q._,j={"--":X},B=$&&$.config.ignoreOptionDefaultValue?$.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,f=Object.create(null);for(let z of Y){if(!B&&z.config.default!==void 0)for(let G of z.names)j[G]=z.config.default;if(Array.isArray(z.config.type)){if(f[z.name]===void 0)f[z.name]={shouldTransform:!0,transformFunction:z.config.type[0]}}}for(let z of Object.keys(Q))if(z!=="_"){let G=z.split(".");aG(j,G,Q[z]),sG(j,f)}return{args:W,options:j}}async run(w=oQ){return this.parse(w,{run:!0,exitOnError:!0})}handleUsageError(w){if(!(!!w&&typeof w==="object"&&w.name==="ClappError"&&w.isUsageError!==!1))return;let A=w,X=A.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
325
+ Run \`${this.name??"cli"} --help\` for usage.`;W$.stderr.write(`${J}${X}${U}
326
+ `),W$.exit(A.exitCode??2)}async runMatchedCommand(){let{args:w,options:$,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((Q,W)=>{if(Q.variadic)A.push(w.slice(W));else A.push(w[W])}),A.push($);let X={command:Y,args:A,options:$};for(let Q of Y.beforeHooks)await Q(X);let J,U=async()=>{let Q=Y.commandAction.apply(this,A);if(Q instanceof Promise)J=await Q;else J=Q;return J};if(Y.middleware.length>0){let Q=0,W=async()=>{if(Q<Y.middleware.length){let j=Y.middleware[Q++];await j({...X,next:W})}else await U()};await W()}else await U();for(let Q of Y.afterHooks)await Q(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return W$.removeAllListeners("SIGINT"),W$.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class Wj{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get(w){if(!this.enabled){this.misses++;return}let $=this.cache.get(w);if(!$){this.misses++;return}if(Date.now()-$.timestamp>$.ttl){this.cache.delete(w),this.misses++;return}return this.hits++,$.value}set(w,$,Y=5000){if(!this.enabled)return;this.cache.set(w,{value:$,timestamp:Date.now(),ttl:Y})}has(w){if(!this.enabled)return!1;let $=this.cache.get(w);if(!$)return!1;if(Date.now()-$.timestamp>$.ttl)return this.cache.delete(w),!1;return!0}delete(w){this.cache.delete(w)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let w=Date.now();for(let[$,Y]of this.cache.entries())if(w-Y.timestamp>Y.ttl)this.cache.delete($)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var sR=new Wj;function U5(){if("FORCE_COLOR"in t1.env)return t1.env.FORCE_COLOR!=="0";if("NO_COLOR"in t1.env||t1.env.TERM==="dumb")return!1;if(t1.platform==="win32")return!0;return eQ.isatty(1)&&eQ.isatty(2)}var Qj=U5();function X0(w,$){if(!Qj)return(Y)=>Y;return(Y)=>w+Y+$}var W5=X0("\x1B[0m","\x1B[0m"),Q5=X0("\x1B[31m","\x1B[39m"),j5=X0("\x1B[32m","\x1B[39m"),B5=X0("\x1B[33m","\x1B[39m"),f5=X0("\x1B[34m","\x1B[39m"),z5=X0("\x1B[35m","\x1B[39m"),G5=X0("\x1B[36m","\x1B[39m"),E5=X0("\x1B[37m","\x1B[39m"),K5=X0("\x1B[90m","\x1B[39m"),F5=X0("\x1B[1m","\x1B[22m"),T5=X0("\x1B[3m","\x1B[23m"),q5=X0("\x1B[4m","\x1B[24m"),N5=X0("\x1B[2m","\x1B[22m"),H5=X0("\x1B[7m","\x1B[27m"),R5=X0("\x1B[8m","\x1B[28m"),M5=X0("\x1B[9m","\x1B[29m"),y5=X0("\x1B[41m","\x1B[49m"),I5=X0("\x1B[42m","\x1B[49m"),C5=X0("\x1B[43m","\x1B[49m"),V5=X0("\x1B[44m","\x1B[49m"),L5=X0("\x1B[45m","\x1B[49m"),S5=X0("\x1B[46m","\x1B[49m"),O5=X0("\x1B[47m","\x1B[49m"),h5=Qj,_5={reset:W5,red:Q5,green:j5,yellow:B5,blue:f5,magenta:z5,cyan:G5,white:E5,gray:K5,bold:F5,italic:T5,underline:q5,dim:N5,inverse:H5,hidden:R5,strikethrough:M5,bgRed:y5,bgGreen:I5,bgYellow:C5,bgBlue:V5,bgMagenta:L5,bgCyan:S5,bgWhite:O5,isColorSupported:h5},tY=_5,k5=["up","down","left","right","space","enter","cancel"],aY={actions:new Set(k5),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function jj(w,$){if(typeof w==="string")return aY.aliases.get(w)===$;for(let Y of w){if(Y===void 0)continue;if(jj(Y,$))return!0}return!1}function Z5(w,$){if(w===$)return[];let Y=w.split(`
326
327
  `),A=$.split(`
327
- `),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var w4=XK.platform.startsWith("win"),VB=Symbol("clapp:cancel");function XA(w,$){let Y=w;if(Y.isTTY)Y.setRawMode($)}function jK(w){return w.replace(/\x1b\[[0-9;]*m/g,"")}function zK(w){return jK(w).length}function yB(w,$,Y){if(!$||$<1)return w;let A=Y?.hard??!1,X=Y?.trim??!0,J=w.split(`
328
- `),U=[];for(let W of J){if(zK(W)<=$){U.push(X?W.trimEnd():W);continue}if(A){let Q="",B=0,j=0;while(j<W.length){let z=W.slice(j).match(/^\x1b\[[0-9;]*m/);if(z){Q+=z[0],j+=z[0].length;continue}if(B>=$)U.push(X?Q.trimEnd():Q),Q="",B=0;Q+=W[j],B++,j++}if(Q)U.push(X?Q.trimEnd():Q)}else U.push(X?W.trimEnd():W)}return U.join(`
329
- `)}class yJ{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=QK,output:A=WK,render:X,signal:J,...U}=w;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=$,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber(w,$){let Y=this._subscribers.get(w)??[];Y.push($),this._subscribers.set(w,Y)}on(w,$){return this.setSubscriber(w,{cb:$}),this}once(w,$){return this.setSubscriber(w,{cb:$,once:!0}),this}emit(w,...$){let Y=this._subscribers.get(w)??[],A=[];for(let X of Y)if(X.cb(...$),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise((w)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),w(VB);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=BK.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),XA(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(cw.show),this.output.off("resize",this.render),XA(this.input,!1),w(this.value)}),this.once("cancel",()=>{this.output.write(cw.show),this.output.off("resize",this.render),XA(this.input,!1),w(VB)})})}_isActionKey(w,$){return w==="\t"}_setValue(w){this.value=w,this.emit("value",this.value)}_setUserInput(w,$){if(this.userInput=w??"",this.emit("userInput",this.userInput),$&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(w,$){if(this._track&&$.name!=="return"){if($.name&&this._isActionKey(w,$))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=$.name==="tab"||$.name==="escape"||$.name==="backspace"||$.name==="delete"||$.name==="enter"||$.name==="return"||$.name&&["up","down","left","right"].includes($.name);if(w&&!Y&&w.length===1&&w>=" ")this._manualLine+=w;else if($.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let A=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(A)}if(this.state==="error")this.state="active",this.error="";if($?.name){if(!this._track&&WA.aliases.has($.name))this.emit("cursor",WA.aliases.get($.name));if(WA.actions.has($.name))this.emit("cursor",$.name)}if(w&&(w.toLowerCase()==="y"||w.toLowerCase()==="n"))this.emit("confirm",w.toLowerCase()==="y");if(this.emit("key",w?.toLowerCase(),$),$?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(hB([w,$?.name,$?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
330
- `),XA(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let w=yB(this._prevFrame,CB.stdout.columns,{hard:!0,trim:!1}).split(`
331
- `).length-1;this.output.write(cw.move(-999,w*-1))}render(){let w=yB(this._render(this)??"",CB.stdout.columns,{hard:!0,trim:!1});if(w===this._prevFrame)return;if(this.state==="initial")this.output.write(cw.hide);else{let $=UK(this._prevFrame,w);if(this.restoreCursor(),$&&$?.length===1){let Y=$[0];this.output.write(cw.move(0,Y)),this.output.write(HJ.lines(1));let A=w.split(`
332
- `);this.output.write(A[Y]),this._prevFrame=w,this.output.write(cw.move(0,A.length-Y-1));return}if($&&$?.length>1){let Y=$[0];this.output.write(cw.move(0,Y)),this.output.write(HJ.down());let X=w.split(`
328
+ `),X=[];for(let J=0;J<Math.max(Y.length,A.length);J++)if(Y[J]!==A[J])X.push(J);return X}var AM=D5.platform.startsWith("win"),wj=Symbol("clapp:cancel");function lY(w,$){let Y=w;if(Y.isTTY)Y.setRawMode($)}function b5(w){return w.replace(/\x1b\[[0-9;]*m/g,"")}function u5(w){return b5(w).length}function Yj(w,$,Y){if(!$||$<1)return w;let A=Y?.hard??!1,X=Y?.trim??!0,J=w.split(`
329
+ `),U=[];for(let Q of J){if(u5(Q)<=$){U.push(X?Q.trimEnd():Q);continue}if(A){let W="",j=0,B=0;while(B<Q.length){let f=Q.slice(B).match(/^\x1b\[[0-9;]*m/);if(f){W+=f[0],B+=f[0].length;continue}if(j>=$)U.push(X?W.trimEnd():W),W="",j=0;W+=Q[B],j++,B++}if(W)U.push(X?W.trimEnd():W)}else U.push(X?Q.trimEnd():Q)}return U.join(`
330
+ `)}class BJ{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor(w,$=!0){let{input:Y=x5,output:A=P5,render:X,signal:J,...U}=w;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=$,this._abortSignal=J,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber(w,$){let Y=this._subscribers.get(w)??[];Y.push($),this._subscribers.set(w,Y)}on(w,$){return this.setSubscriber(w,{cb:$}),this}once(w,$){return this.setSubscriber(w,{cb:$,once:!0}),this}emit(w,...$){let Y=this._subscribers.get(w)??[],A=[];for(let X of Y)if(X.cb(...$),X.once)A.push(()=>Y.splice(Y.indexOf(X),1));for(let X of A)X();return this}prompt(){return new Promise((w)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),w(wj);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=i5.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),lY(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(xw.show),this.output.off("resize",this.render),lY(this.input,!1),w(this.value)}),this.once("cancel",()=>{this.output.write(xw.show),this.output.off("resize",this.render),lY(this.input,!1),w(wj)})})}_isActionKey(w,$){return w==="\t"}_setValue(w){this.value=w,this.emit("value",this.value)}_setUserInput(w,$){if(this.userInput=w??"",this.emit("userInput",this.userInput),$&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress(w,$){if(this._track&&$.name!=="return"){if($.name&&this._isActionKey(w,$))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=$.name==="tab"||$.name==="escape"||$.name==="backspace"||$.name==="delete"||$.name==="enter"||$.name==="return"||$.name&&["up","down","left","right"].includes($.name);if(w&&!Y&&w.length===1&&w>=" ")this._manualLine+=w;else if($.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let A=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(A)}if(this.state==="error")this.state="active",this.error="";if($?.name){if(!this._track&&aY.aliases.has($.name))this.emit("cursor",aY.aliases.get($.name));if(aY.actions.has($.name))this.emit("cursor",$.name)}if(w&&(w.toLowerCase()==="y"||w.toLowerCase()==="n"))this.emit("confirm",w.toLowerCase()==="y");if(this.emit("key",w?.toLowerCase(),$),$?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(jj([w,$?.name,$?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
331
+ `),lY(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let w=Yj(this._prevFrame,$j.stdout.columns,{hard:!0,trim:!1}).split(`
332
+ `).length-1;this.output.write(xw.move(-999,w*-1))}render(){let w=Yj(this._render(this)??"",$j.stdout.columns,{hard:!0,trim:!1});if(w===this._prevFrame)return;if(this.state==="initial")this.output.write(xw.hide);else{let $=Z5(this._prevFrame,w);if(this.restoreCursor(),$&&$?.length===1){let Y=$[0];this.output.write(xw.move(0,Y)),this.output.write(XJ.lines(1));let A=w.split(`
333
+ `);this.output.write(A[Y]),this._prevFrame=w,this.output.write(xw.move(0,A.length-Y-1));return}if($&&$?.length>1){let Y=$[0];this.output.write(xw.move(0,Y)),this.output.write(XJ.down());let X=w.split(`
333
334
  `).slice(Y);this.output.write(X.join(`
334
- `)),this._prevFrame=w;return}this.output.write(HJ.down())}if(this.output.write(w),this.state==="initial")this.state="active";this._prevFrame=w}}function GK(w,$){if(w===void 0)return 0;if($.length===0)return 0;let A=$.findIndex((X)=>X.value===w);return A!==-1?A:0}function KK(w,$){return($.label??String($.value)).toLowerCase().includes(w.toLowerCase())}function FK(w,$){if(!$)return;if(w)return $;return $[0]}class qK extends yJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#w=0;#Y="";#A;#$;get cursor(){return this.#w}get userInputWithCursor(){if(!this.userInput)return QA.inverse(QA.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let w=this.userInput.slice(0,this._cursor),[$,...Y]=this.userInput.slice(this._cursor);return`${w}${QA.inverse($)}${Y.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(w){super(w);this.#$=w.options;let $=this.options;this.filteredOptions=[...$],this.multiple=w.multiple===!0,this.#A=w.filter??KK;let Y;if(w.initialValue&&Array.isArray(w.initialValue))if(this.multiple)Y=w.initialValue;else Y=w.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let A of Y){let X=$.findIndex((J)=>J.value===A);if(X!==-1)this.toggleSelected(A),this.#w=X}this.focusedValue=this.options[this.#w]?.value,this.on("key",(A,X)=>this.#X(A,X)),this.on("userInput",(A)=>this.#J(A))}_isActionKey(w,$){return w==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&w!==void 0&&w!==""}#X(w,$){let Y=$.name==="up",A=$.name==="down",X=$.name==="return";if(Y||A){if(this.#w=Math.max(0,Math.min(this.#w+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=FK(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(w){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(w))this.selectedValues=this.selectedValues.filter(($)=>$!==w);else this.selectedValues=[...this.selectedValues,w];else this.selectedValues=[w]}#J(w){if(w!==this.#Y){this.#Y=w;let $=this.options;if(w)this.filteredOptions=$.filter((Y)=>this.#A(w,Y));else this.filteredOptions=[...$];if(this.#w=GK(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class NK extends yJ{options;cursor=0;#w;getGroupItems(w){return this.options.filter(($)=>$.group===w)}isGroupSelected(w){let $=this.getGroupItems(w),Y=this.value;if(Y===void 0)return!1;return $.every((A)=>Y.includes(A.value))}toggleValue(){let w=this.options[this.cursor];if(this.value===void 0)this.value=[];if(w.group===!0){let $=String(w.value),Y=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((A)=>Y.findIndex((X)=>X.value===A)===-1);else this.value=[...this.value,...Y.map((A)=>A.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(w.value);this.value=$?this.value.filter((Y)=>Y!==w.value):[...this.value,w.value]}}constructor(w){super(w,!1);let{options:$}=w;this.#w=w.selectableGroups!==!1,this.options=Object.entries($).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((X)=>({...X,group:Y}))]),this.value=[...w.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===w.cursorAt),this.#w?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let A=this.options[this.cursor]?.group===!0;if(!this.#w&&A)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let A=this.options[this.cursor]?.group===!0;if(!this.#w&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var EK=C6();var e=(w,$)=>EK?w:$,A4=e("◆","*"),X4=e("■","x"),J4=e("▲","x"),U4=e("◇","o"),Q4=e("┌","T"),fK=e("│","|"),W4=e("└","—"),B4=e("●",">"),j4=e("○"," "),z4=e("◻","[•]"),G4=e("◼","[+]"),K4=e("◻","[ ]"),F4=e("▪","•"),q4=e("─","-"),N4=e("╮","+"),E4=e("├","+"),f4=e("╯","+"),T4=e("●","•"),H4=e("◆","*"),R4=e("▲","!"),M4=e("■","x");var I4={light:e("─","-"),heavy:e("━","="),block:e("█","#")};function TK(){return`${QA.gray(fK)} `}var V4=TK();NU();import{homedir as EU}from"node:os";import{join as fU,resolve as LF}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",Y9={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:fU(EU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:fU(EU(),".stacks","ssl","stacks.localhost.crt"),keyPath:fU(EU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},TU=null;async function A9(){if(!TU)TU=await qU({name:"rpx",cwd:LF(__dirname,".."),defaultConfig:Y9});return TU}var F1=Y9;import{existsSync as _F,readdirSync as SF,readFileSync as ZF,statSync as kF}from"node:fs";import{homedir as J9}from"node:os";import{isAbsolute as hF,join as N1}from"node:path";var U9=["~/Code"],Q9=["localhost","test"],DF=1800000,HU={dirExists:(w)=>{try{return kF(w).isDirectory()}catch{return!1}},fileExists:(w)=>{try{return _F(w)}catch{return!1}},readText:(w)=>{try{return ZF(w,"utf8")}catch{return null}}};function RU(w,$){if(w==="~")return $;if(w.startsWith("~/"))return N1($,w.slice(2));return w}function xF(w){let $=w.indexOf(":");return($===-1?w:w.slice(0,$)).toLowerCase()}function rA(w){return w.replace(/[^a-z0-9._-]/gi,"-").replace(/^[-.]+|[-.]+$/g,"")||"site"}function PF(w,$){for(let Y of $){let A=`.${Y}`;if(w.endsWith(A)){let X=w.slice(0,-A.length);if(X.length>0&&!X.includes(".")&&/^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$/i.test(X))return X}}return null}function bF(w,$){let Y=$.readText(N1(w,"rpx.site.json"));if(Y)try{let X=JSON.parse(Y);if(X&&typeof X==="object")return X}catch{}let A=$.readText(N1(w,"package.json"));if(A)try{let X=JSON.parse(A);if(X.rpx&&typeof X.rpx==="object")return X.rpx}catch{}return null}function uF(w){let $=w.selfRegisters??!1;return{command:w.command,env:w.env,urlEnv:w.urlEnv,selfRegisters:$,routes:w.routes??($?void 0:[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}])}}function cF(w,$){let Y=bF(w,$);if(Y?.command)return uF(Y);let A=$.fileExists(N1(w,"buddy")),X=$.readText(N1(w,"package.json")),J=null;if(X)try{J=JSON.parse(X)}catch{J=null}let U={...J?.dependencies??{},...J?.devDependencies??{}};if(A||Object.keys(U).some((Q)=>Q==="stacks"||Q.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 vF(w,$={}){let Y={dirExists:$.dirExists??HU.dirExists,fileExists:$.fileExists??HU.fileExists,readText:$.readText??HU.readText},A=$.detect??cF,X=$.homeDir??J9(),J=w.tlds??Q9,U=(w.roots??U9).map((G)=>RU(G,X)),W=w.idleTimeoutMs??DF,Q=new Map;for(let G of w.sites??[])Q.set(G.to,G);let B=(G)=>G.idleTimeoutMs??W;function j(G){let K=pA(Q,G);if(!K)return null;let E=hF(K.dir)?K.dir:RU(K.dir,X),q=K.selfRegisters??!1,N=K.routes??[];if(!q&&N.length===0)N=A(E,Y)?.routes??[{path:"/",portEnv:"PORT",defaultPort:3000,readyGate:!0}];let f=X9({...K.env??{}},void 0,G);return{host:G,id:rA(G),dir:E,command:K.command,env:f,routes:N,selfRegisters:q,idleTimeoutMs:B(K),source:"config"}}function z(G){let K=PF(G,J);if(!K)return null;for(let E of U){let q=N1(E,K);if(!Y.dirExists(q))continue;let N=A(q,Y);if(!N)continue;let f=N.selfRegisters??!1;return{host:G,id:rA(G),dir:q,command:N.command,env:X9({...N.env??{}},N.urlEnv,G),routes:f?[]:N.routes??[],selfRegisters:f,idleTimeoutMs:W,source:"discovered"}}return null}return{resolve(G){let K=xF(G);if(!K)return null;return j(K)??z(K)}}}function iF(w){try{return SF(w,{withFileTypes:!0}).filter(($)=>$.isDirectory()).map(($)=>$.name)}catch{return[]}}function W9(w,$={}){let Y=$.homeDir??J9(),A=w.tlds??Q9,X=(w.roots??U9).map((z)=>RU(z,Y)),J=$.readdir??iF,U=vF(w,$),W=[],Q=new Set,B=(z)=>{if(z&&!Q.has(z.host))Q.add(z.host),W.push(z)};for(let z of w.sites??[])if(!z.to.includes("*"))B(U.resolve(z.to));let j=A[0]??"localhost";for(let z of X)for(let G of J(z))B(U.resolve(`${G}.${j}`));return W}function X9(w,$,Y){if(!$)return w;let A=`https://${Y}`;for(let X of $)if(w[X]===void 0)w[X]=A;return w}nw();L8();k8();h8();dY();x8();b8();xW();iW();mY();cY();t$();p8();JY();X0();import{spawn as x5}from"node:child_process";import*as u0 from"node:fs/promises";import{homedir as P5}from"node:os";import*as hw from"node:path";import*as C from"node:process";var XM=5000;function Aw(){return hw.join(P5(),".stacks","rpx")}function x$(w=Aw()){return hw.join(w,"daemon.pid")}async function D$(w=Aw()){try{let $=await u0.readFile(x$(w),"utf8"),Y=Number.parseInt($.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch($){if($.code==="ENOENT")return null;throw $}}async function $J(w=Aw()){let $=await D$(w);return $!==null&&b0($)}async function b5(w=Aw()){await u0.mkdir(w,{recursive:!0});let $=x$(w);while(!0){try{let A=await u0.open($,"wx");try{await A.write(`${C.pid}
335
- `)}finally{await A.close()}return $}catch(A){if(A.code!=="EEXIST")throw A}let Y=await D$(w);if(Y!==null&&b0(Y))throw Error(`rpx daemon already running (pid=${Y})`);await u0.unlink($).catch(()=>{})}}async function QY(w=Aw()){await u0.unlink(x$(w)).catch(()=>{})}var e8=new Map;function wJ(w){for(let[$,Y]of e8)if(!w.has($))n$(Y),e8.delete($)}function JM(w,$){let Y=_W($??"localhost:1");if(w.upstreams.length!==Y.length)return!1;return w.upstreams.every((A,X)=>A.url===Y[X])}function u5(w){let $=w.cleanUrls??!1,Y=Sw(w.path),A=t1(w.auth);if(w.static)return{static:iY(w.static,$),cleanUrls:$,basePath:Y,auth:A};let X=w.from??"localhost:1",J=_$(X),U=new URL(J.startsWith("http")?J:`http://${J}`),W=e8.get(w.id);if(W&&!JM(W,X))n$(W),W=void 0;if(!W)W=p1(X,w.loadBalancer),r1(W),e8.set(w.id,W);return{sourceHost:U.host,upstreamPool:W,cleanUrls:$,changeOrigin:w.changeOrigin??!1,pathRewrites:w.pathRewrites,basePath:Y,auth:A}}function UM(w){return w.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??w[0]??"rpx.localhost"}async function o8(w,$,Y=[],A=!1){let X=await Zw($,w.verbose),J=[...new Set([...X.map((j)=>j.to).filter(Boolean),...Y])],U=UM(J),W=[...new Set([U,...J,"rpx.localhost"])],Q=LW(J,U,w.verbose);if(typeof w.https==="object"&&typeof Q.https==="object")Q.https={...Q.https,...w.https};let B=await W$(Q);if(B&&(A||!gX(y8,W)))F("daemon",`regenerating shared cert for host(s): ${W.join(", ")}`,w.verbose),O8(),B=null;if(!B)F("daemon","no usable cert on disk, generating one via tlsx",w.verbose),await n1({...Q,forceRegenerate:!0}),B=await W$(Q);if(!B)throw Error("failed to bootstrap TLS for rpx daemon");return B}async function QM(w,$,Y,A){let X=C.env.SUDO_PASSWORD,J=C.env.HOME??P5(),U=[C.execPath,...C.argv.slice(1)],W=[`HOME=${J}`,`PATH=${C.env.PATH??""}`];if(A)W.push("RPX_VERBOSE=1");for(let[E,q]of Object.entries(C.env))if(q!==void 0&&E!=="RPX_VERBOSE"&&/^(?:RPX_|STACKS_RPX_)/.test(E))W.push(`${E}=${q}`);let Q=X?["-S","-p","","env",...W,...U]:["-n","env",...W,...U];F("daemon",`elevating daemon via sudo for privileged ports ${$}/${Y}`,A);let B=x5("sudo",Q,{detached:!0,stdio:["pipe","ignore","ignore"]}),j=null,z=null;if(B.once("error",(E)=>{j=E}),B.once("exit",(E)=>{z=E??0}),X&&B.stdin)B.stdin.write(`${X}
336
- `),B.stdin.end();B.unref();let G=x$(w),K=Date.now()+15000;while(Date.now()<K){if(j)throw j;let E=await D$(w);if(E!==null&&b0(E)){if(A)H.success(`rpx daemon elevated to root (pid=${E}, https on :${$})`);return{httpsPort:$,httpPort:Y,pidPath:G,done:Promise.resolve(),stop:async()=>{try{C.kill(E,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}if(z!==null&&z!==0)throw Error(`rpx daemon could not elevate to bind :${$} (sudo exited ${z}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((q)=>setTimeout(q,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${w})`)}var k5=!1;function XB(){if(k5)return;k5=!0,C.on("uncaughtException",(w)=>{H.error(`rpx daemon: uncaught exception (continuing): ${w?.stack??w}`)}),C.on("unhandledRejection",(w)=>{H.error(`rpx daemon: unhandled rejection (continuing): ${w}`)})}function c5(w,$,Y){let A;try{A=new URL(w.url)}catch{return new Response("Bad Request",{status:400})}let X=(w.headers.get("host")??A.hostname).split(":")[0];if(A.pathname.startsWith("/.well-known/acme-challenge/")){if($){let J=$.challengeStore.handlePath(A.pathname);if(J!==void 0)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if(Y){let J=gY(Y,A.pathname);if(J!=null)return new Response(J,{status:200,headers:{"content-type":"text/plain"}})}if($)return new Response("challenge not found",{status:404})}if($&&!$.hasCert(X))$.ensureCert(X).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${X}${A.pathname}${A.search}`}})}async function v5(w={}){XB();let $=w.verbose??!1,Y=w.rpxDir??Aw(),A=w.registryDir??hw.join(Y,"registry.d"),X=w.httpsPort??443,J=w.httpPort??80,U=w.hostname??"0.0.0.0",W=w.gcIntervalMs??XM;if(C.env.RPX_DAEMON_WORKER==="1")return jM({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"||$});let Q=X>0&&X<1024||J>0&&J<1024,B=typeof C.getuid==="function"&&C.getuid()===0;if(C.platform!=="win32"&&Q&&!B)return QM(Y,X,J,$);let j=Math.max(1,w.workers??(Number.parseInt(C.env.RPX_WORKERS??"",10)||1));if(j>1){if(w.onDemandSites?.enabled)H.warn("rpx: on-demand sites are not supported in cluster mode (workers > 1); ignoring");return zM(w,{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:$,gcIntervalMs:W,workers:j})}let z=await b5(Y),G=new Map,K=(I,k)=>e1(G,I,k);function E(I){G=o1(I.map((Lw)=>({host:Lw.to,path:Lw.path,route:u5(Lw)}))),wJ(new Set(I.map((Lw)=>Lw.id)));let k=Array.from(G.keys());F("daemon",`routing table now covers ${k.length} host(s): ${k.join(", ")||"<empty>"}`,$)}await YY(A,$).catch((I)=>{F("daemon",`initial gc failed: ${I}`,$)}),await XY({verbose:$}).catch((I)=>{F("daemon",`stale hosts GC on start failed: ${I}`,$)});let q=await Zw(A,$);E(q),await G$({rpxDir:Y,verbose:$}).catch((I)=>{F("daemon",`DNS reconcile on start failed: ${I}`,$)}),await s$(q,{rpxDir:Y,verbose:$,ownerPid:C.pid}).catch((I)=>{F("daemon",`DNS setup on start failed: ${I}`,$)});let N=[];if(w.productionCerts){if(N=await wY(w.productionCerts,$),$&&N.length>0)H.info(`SNI: serving ${N.length} real cert(s): ${N.map((I)=>I.serverName).join(", ")}`)}let f=new Set,R=null,O;if(w.onDemandSites?.enabled){if(R=new g8({resolver:DW(w.onDemandSites),registryDir:A,rpxDir:Y,verbose:$,startupTimeoutMs:w.onDemandSites.startupTimeoutMs,isHostRoutable:(I)=>D8(G,I)!==void 0,onSiteActivating:(I)=>{yw(I)}}),O=async(I)=>{let k=await R.onRequest(I);switch(k.kind){case"ready":return{retry:!0};case"starting":return mW({host:k.host,sinceMs:k.sinceMs,logTail:k.logTail});case"failed":return gW({host:k.host,error:k.error,logTail:k.logTail});case"unknown":default:return}},$)H.info("rpx: on-demand sites enabled")}let y=a1(K,$,O),T=s1($),M=null;if(N.length===0)M=await o8(w,A);let V=w.onDemandTls,S=V?.enabled?new r$({config:V,certsDir:V.certsDir??w.productionCerts?.certsDir??hw.join(Y,"on-demand-certs"),initial:N,verbose:$,onCertAdded:(I)=>{uw(I)}}):null;function U0(I){if(I.length>0)return S$(I.map((k)=>({serverName:k.serverName,cert:k.cert,key:k.key})));return S$({key:M.key,cert:M.cert,ca:M.ca,requestCert:!1,rejectUnauthorized:!1})}function v0(I){return Bun.serve({port:X,hostname:U,reusePort:g1(),tls:U0(I),fetch(k,Lw){return y(k,Lw)},websocket:T,error(k){return F("daemon",`https server error: ${k}`,$),new Response(`Server Error: ${k.message}`,{status:500})}})}let Kw=(I)=>[...new Set(I.map((k)=>k.to).filter(Boolean))],P$=(I)=>{if(!M)return N;return OW([...Kw(I),...f,"rpx.localhost"],M)},Pw=v0(S?S.sniEntries():N.length>0?N:P$(q)),bw=null,Fw=!1;async function uw(I){if(Ow)return;if(bw=I,Fw)return;Fw=!0;try{while(!Ow&&bw){let k=bw;bw=null,F("daemon",`rebuilding :443 with ${k.length} SNI cert(s)`,$),Pw.stop(!1);let Lw,qJ=!1,EB=60,B6=500;for(let NJ=0;!Ow&&!qJ;NJ++)try{Pw=v0(k),qJ=!0;break}catch(j6){if(Lw=j6,NJ>=EB)break;await new Promise((z6)=>setTimeout(z6,Math.min(25*2**Math.min(NJ,4),B6)))}if(!qJ)H.error(`rpx: CRITICAL — could not rebind :443 after ${EB} attempts issuing cert; HTTPS unbound until the next cert event or a gateway restart: ${Lw?.message}`)}}finally{Fw=!1}}let s0=null;if(J>0)s0=Bun.serve({port:J,hostname:U,fetch(I){return c5(I,S,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});if($)H.success(`rpx daemon listening on https://${U}:${X}${s0?` (http→https on :${J})`:""}`),H.info(`pid file: ${z}`),H.info(`registry: ${A}`);async function Z(I){if(Ow||N.length>0||S||!M)return;try{M=await o8(w,A,[...f]),await uw(P$(I))}catch(k){F("daemon",`TLS sync on registry change failed: ${k}`,$)}}async function yw(I){if(Ow||N.length>0||S||!M||!I)return;if(f.has(I))return;f.add(I);try{M=await o8(w,A,[...f],!0);let k=await Zw(A,$);await uw(P$(k))}catch(k){F("daemon",`dev cert refresh for ${I} failed: ${k}`,$)}}let BY=rY((I)=>{E(I),Z(I),s$(I,{rpxDir:Y,verbose:$,ownerPid:C.pid}).catch((k)=>{F("daemon",`DNS sync on registry change failed: ${k}`,$)})},{dir:A,verbose:$}),e$=setInterval(()=>{YY(A,$).then((I)=>{if(I>0)F("daemon",`gc reaped ${I} stale entries`,$)}).catch((I)=>{F("daemon",`periodic gc failed: ${I}`,$)}),XY({verbose:$}).then((I)=>{if(I.length>0)F("daemon",`gc reaped stale hosts entries: ${I.join(", ")}`,$)}).catch((I)=>{F("daemon",`periodic hosts gc failed: ${I}`,$)})},W);if(typeof e$.unref==="function")e$.unref();let Ow=!1,jY,w1=new Promise((I)=>{jY=I});async function FJ(){if(Ow)return w1;if(Ow=!0,clearInterval(e$),BY.close(),await R?.stopAll().catch((I)=>{F("daemon",`site supervisor stopAll failed: ${I}`,$)}),Pw.stop(!1),s0?.stop(!1),await k$({rpxDir:Y,verbose:$}).catch((I)=>{F("daemon",`DNS teardown failed: ${I}`,$)}),wJ(new Set),await QY(Y),$)H.info("rpx daemon stopped");return jY(),w1}let NB=(I)=>{F("daemon",`received ${I}, shutting down`,$),FJ().catch(()=>{})};return C.once("SIGINT",NB),C.once("SIGTERM",NB),{stop:FJ,done:w1,httpsPort:typeof Pw.port==="number"?Pw.port:X,httpPort:s0&&typeof s0.port==="number"?s0.port:J,pidPath:z,ensureCert:(I)=>S?S.ensureCert(I):Promise.resolve(!1),listSites:()=>R?.list()??[]}}function JB(w){return hw.join(w,"cluster-sni.json")}async function h5(w,$,Y){let A=JB(w),X=`${A}.${C.pid}.tmp`;await u0.writeFile(X,JSON.stringify({sni:$,dev:Y}),"utf8"),await u0.rename(X,A)}async function D5(w){try{return JSON.parse(await u0.readFile(JB(w),"utf8"))}catch{return{sni:[],dev:null}}}function WM(w){if(w.sni.length>0)return S$(w.sni.map(($)=>({serverName:$.serverName,cert:$.cert,key:$.key})));if(w.dev)return S$({key:w.dev.key,cert:w.dev.cert,ca:w.dev.ca,requestCert:!1,rejectUnauthorized:!1});return}function BM(){let w=C.execPath,$=C.env.RPX_WORKER_BIN;if($)return[w,$,"daemon:start"];let Y=hw.basename(w).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&C.argv[1])return[w,C.argv[1],"daemon:start"];return[w,"daemon:start"]}async function jM(w){XB();let{rpxDir:$,registryDir:Y,httpsPort:A,hostname:X,verbose:J}=w,U=new Map,W=(M,V)=>e1(U,M,V),Q=(M)=>{U=o1(M.map((V)=>({host:V.to,path:V.path,route:u5(V)}))),wJ(new Set(M.map((V)=>V.id)))};Q(await Zw(Y,J));let B=a1(W,J),j=s1(J),z=!1,G=(M)=>Bun.serve({port:A,hostname:X,reusePort:!0,tls:WM(M),fetch(V,S){return B(V,S)},websocket:j,error(V){return F("daemon",`worker https error: ${V}`,J),new Response(`Server Error: ${V.message}`,{status:500})}}),K=G(await D5($));async function E(){if(z)return;let M=await D5($),V=null;for(let U0=0;U0<20&&!z;U0++)try{V=G(M);break}catch{await new Promise((v0)=>setTimeout(v0,25))}if(!V){F("daemon","worker reloadTls: could not bind new listener; keeping current",J);return}let S=K;K=V,S.stop(!1)}let q=rY((M)=>Q(M),{dir:Y,verbose:J}),N=()=>{E().catch(()=>{})};C.on("SIGHUP",N);let f=()=>{let M=C.removeListener??C.off;if(typeof M==="function")M.call(C,"SIGHUP",N)},R,O=new Promise((M)=>{R=M});async function y(){if(z)return O;return z=!0,f(),q.close(),K.stop(!1),wJ(new Set),R(),O}let T=()=>{y().then(()=>C.exit(0)).catch(()=>C.exit(0))};if(C.once("SIGTERM",T),C.once("SIGINT",T),J)H.success(`rpx worker (pid ${C.pid}) serving :${A}`);return{stop:y,done:O,httpsPort:typeof K.port==="number"?K.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1),listSites:()=>[]}}async function zM(w,$){XB();let{rpxDir:Y,registryDir:A,httpsPort:X,httpPort:J,hostname:U,verbose:W,gcIntervalMs:Q,workers:B}=$,j=await b5(Y),z=[];if(w.productionCerts)z=await wY(w.productionCerts,W);let G=null;if(z.length===0)G=await o8(w,A);let K=G?{key:G.key,cert:G.cert,ca:Array.isArray(G.ca)?G.ca.join(`
337
- `):G.ca}:null,E=!1,q=[];function N(Z){for(let yw of q)try{yw.kill(Z)}catch{}}async function f(Z){await h5(Y,Z,K),N("SIGHUP")}let R=w.onDemandTls,O=R?.enabled?new r$({config:R,certsDir:R.certsDir??w.productionCerts?.certsDir??hw.join(Y,"on-demand-certs"),initial:z,verbose:W,onCertAdded:(Z)=>{f(Z)}}):null;await h5(Y,O?O.sniEntries():z,K);let y=await Zw(A,W);await G$({rpxDir:Y,verbose:W}).catch((Z)=>{F("daemon",`DNS reconcile on start failed: ${Z}`,W)}),await s$(y,{rpxDir:Y,verbose:W,ownerPid:C.pid}).catch((Z)=>{F("daemon",`DNS setup on start failed: ${Z}`,W)}),await YY(A,W).catch(()=>{}),await XY({verbose:W}).catch(()=>{});let T=rY((Z)=>{s$(Z,{rpxDir:Y,verbose:W,ownerPid:C.pid}).catch((yw)=>{F("daemon",`DNS sync on registry change failed: ${yw}`,W)})},{dir:A,verbose:W}),M=setInterval(()=>{YY(A,W).catch(()=>{}),XY({verbose:W}).catch(()=>{})},Q);M.unref?.();let V=null;if(J>0)V=Bun.serve({port:J,hostname:U,fetch(Z){return c5(Z,O,w.acmeChallengeWebroot)},error(){return new Response("Bad Request",{status:400})}});let S=10,U0=60000,v0=30000,Kw=0,P$=Date.now();function Pw(){if(E)return;let Z={...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:W?"1":"0"},yw=Bun.spawn(BM(),{env:Z,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(BY,e$){if(E)return;let Ow=q.indexOf(BY);if(Ow!==-1)q.splice(Ow,1);let jY=Date.now();if(jY-P$>U0)P$=jY,Kw=0;if(Kw++,Kw>S){H.error(`rpx: worker keeps exiting (code ${e$}); giving up after ${S} restarts in ${Math.round(U0/1000)}s`);return}let w1=Math.min(v0,100*2**Math.min(Kw,8));F("daemon",`worker exited (code ${e$}); respawning in ${w1}ms (restart ${Kw}/${S})`,W),setTimeout(Pw,w1).unref?.()}});q.push(yw)}for(let Z=0;Z<B;Z++)Pw();if(W)H.success(`rpx coordinator listening on https://${U}:${X} via ${B} worker(s)${V?` (http→https on :${J})`:""}`),H.info(`pid file: ${j}`);let bw,Fw=new Promise((Z)=>{bw=Z});async function uw(){if(E)return Fw;if(E=!0,clearInterval(M),T.close(),V?.stop(!1),N("SIGTERM"),await Promise.race([Promise.all(q.map((Z)=>Z.exited)),new Promise((Z)=>setTimeout(Z,3000))]),N("SIGKILL"),await k$({rpxDir:Y,verbose:W}).catch((Z)=>{F("daemon",`DNS teardown failed: ${Z}`,W)}),await QY(Y),await u0.unlink(JB(Y)).catch(()=>{}),W)H.info("rpx coordinator stopped");return bw(),Fw}let s0=(Z)=>{F("daemon",`coordinator received ${Z}, shutting down`,W),uw().catch(()=>{})};return C.once("SIGINT",s0),C.once("SIGTERM",s0),{stop:uw,done:Fw,httpsPort:X,httpPort:J,pidPath:j,ensureCert:(Z)=>O?O.ensureCert(Z):Promise.resolve(!1),listSites:()=>[]}}function GM(){let w=C.execPath,$=hw.basename(w).toLowerCase();if(($==="bun"||$==="node"||$.startsWith("bun-"))&&C.argv[1])return[w,C.argv[1],"daemon:start"];return[w,"daemon:start"]}async function i5(w={}){let $=w.rpxDir??Aw(),Y=w.verbose??!1;await G$({rpxDir:$,verbose:Y}).catch((j)=>{F("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,Y)});let A=await D$($);if(A!==null&&b0(A))return F("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)F("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await QY($);await u0.mkdir($,{recursive:!0});let X=w.spawnCommand??GM();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");F("daemon",`spawning daemon: ${X.join(" ")}`,Y);let J=x5(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:w.spawnCwd??C.cwd(),env:w.spawnEnv?{...C.env,...w.spawnEnv}:C.env});J.unref();let U=null;J.once("error",(j)=>{U=j});let W=w.startupTimeoutMs??5000,Q=w.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let j=await D$($);if(j!==null&&b0(j))return F("daemon",`daemon registered with pid=${j}`,Y),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,Q))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${$})`)}async function m5(w={}){let $=w.rpxDir??Aw(),Y=w.verbose??!1,A=w.timeoutMs??5000,X=w.pollIntervalMs??50,J=w.forceAfterTimeout??!0,U=await D$($);if(U===null||!b0(U)){if(U!==null)await QY($);return await G$({rpxDir:$,verbose:Y}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{C.kill(U,"SIGTERM")}catch(Q){let B=Q.code;if(B==="ESRCH")return await QY($),{stopped:!1,pid:U,forced:!1};if(B==="EPERM")Q$(`kill -TERM ${U}`);else throw Q}let W=Date.now()+A;while(Date.now()<W){if(!b0(U))return F("daemon",`daemon pid=${U} stopped cleanly`,Y),{stopped:!0,pid:U,forced:!1};await new Promise((Q)=>setTimeout(Q,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${A}ms`);F("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,Y);try{C.kill(U,"SIGKILL")}catch(Q){let B=Q.code;if(B==="EPERM")Q$(`kill -KILL ${U}`);else if(B!=="ESRCH")throw Q}return await QY($),await k$({rpxDir:$,verbose:Y}).catch((Q)=>{F("daemon",`DNS teardown after SIGKILL: ${Q}`,Y)}),{stopped:!0,pid:U,forced:!0}}async function g5(w={}){let $=w.rpxDir??Aw();if(await $J($))return;await G$({rpxDir:$,verbose:w.verbose})}nw();X0();import{spawn as KM}from"node:child_process";import*as YJ from"node:process";class d5{processes=new Map;isShuttingDown=!1;async startProcess(w,$,Y){if(this.processes.has(w)){F("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||YJ.cwd();F("start",`Starting process ${w}:`,Y),F("start",` Command: ${A} ${X.join(" ")}`,Y),F("start",` Working directory: ${J}`,Y),F("start",` Environment variables: ${Iw($.env)}`,Y);let U=KM(A,X,{cwd:J,env:{...YJ.env,...$.env},shell:!0,stdio:"inherit"});return this.processes.set(w,{command:$.command,cwd:J,process:U,env:$.env}),new Promise((W,Q)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)F("start",`Process ${w} failed to start: ${B}`,Y),this.processes.delete(w),Q(B)}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)F("start",`Process ${w} exited with code ${B}; leaving the proxy running`,Y),this.processes.delete(w),Q(Error(`Process ${w} exited with code ${B}`))}),Y)U.stdout?.on("data",(B)=>{F("process",`[${w}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{F("process",`[${w}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete(w),Q(Error(`Process ${w} was killed during startup`));else F("start",`Process ${w} started successfully`,Y),W()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);if(!Y?.process){F("start",`No process found for ${w}`,$);return}return F("start",`Stopping process ${w}`,$),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete(w),F("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){F("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){F("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){F("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,F("start","Stopping all processes",w);let $=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,w).catch((A)=>{H.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled($),this.processes.clear(),this.isShuttingDown=!1}isRunning(w){let $=this.processes.get(w);return!!$?.process&&!$.process.killed}}var AJ=new d5;X0();import*as t0 from"node:fs/promises";import{homedir as FM}from"node:os";import*as UB from"node:path";import*as QB from"node:process";var qM=/^[a-zA-Z0-9._-]+$/;function o$(){return UB.join(FM(),".stacks","rpx","registry.d")}function WY(w){return typeof w==="string"&&w.length>0&&w.length<=128&&qM.test(w)}function WB(w,$){if(!WY($))throw Error(`invalid registry id: ${JSON.stringify($)}`);return UB.join(w,`${$}.json`)}function l5(w){if(!w||typeof w!=="object")return!1;let $=w,Y=$.pid===void 0||typeof $.pid==="number"&&Number.isInteger($.pid)&&$.pid>0,A=typeof $.from==="string"&&$.from.length>0||Array.isArray($.from)&&$.from.length>0,X=typeof $.static==="string"||!!$.static&&typeof $.static==="object"&&typeof $.static.dir==="string",J=$.path===void 0||typeof $.path==="string";return typeof $.id==="string"&&WY($.id)&&(A||X)&&typeof $.to==="string"&&$.to.length>0&&J&&Y&&typeof $.createdAt==="string"}async function NM(w){await t0.mkdir(w,{recursive:!0})}async function n5(w,$=o$(),Y){if(!l5(w))throw Error(`invalid registry entry: ${JSON.stringify(w)}`);await NM($);let A=WB($,w.id),X=`${A}.tmp.${QB.pid}.${Date.now()}`,J=JSON.stringify(w,null,2);try{await t0.writeFile(X,J,{encoding:"utf8",mode:420}),await t0.rename(X,A),F("registry",`wrote entry ${w.id} → ${A}`,Y)}catch(U){throw await t0.unlink(X).catch(()=>{}),U}}async function p5(w,$=o$(),Y){let A=WB($,w);try{await t0.unlink(A),F("registry",`removed entry ${w}`,Y)}catch(X){if(X.code!=="ENOENT")throw X}}async function BB(w,$=o$(),Y){let A=WB($,w);try{let X=await t0.readFile(A,"utf8"),J=JSON.parse(X);if(!l5(J))return F("registry",`entry ${w} failed validation, removing`,Y),await t0.unlink(A).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return F("registry",`entry ${w} has invalid JSON, removing`,Y),await t0.unlink(A).catch(()=>{}),null;throw X}}async function jB(w=o$(),$){let Y;try{Y=await t0.readdir(w)}catch(X){if(X.code==="ENOENT")return[];throw X}let A=[];for(let X of Y){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!WY(J))continue;let U=await BB(J,w,$);if(U)A.push(U)}return A}nw();import{execSync as IM}from"node:child_process";import*as GJ from"node:http";import*as o5 from"node:net";import*as e5 from"node:os";import*as w6 from"node:path";import*as J0 from"node:process";var XJ=(w,$)=>(Y)=>`\x1B[${w}m${Y}\x1B[${$}m`,Dw={bold:XJ(1,22),dim:XJ(2,22),green:XJ(32,39),cyan:XJ(36,39)};kQ();pW();nw();t$();X0();import*as r5 from"node:fs";import*as t5 from"node:path";import*as xw from"node:process";function EM(w,$){let A=($&&$!=="/"?`${w}${$}`:w).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function zB(w){if(w.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let $=w.verbose??!1,Y=w.registryDir,A=new Set,X=w.proxies.map((G)=>{let K=G.id??EM(G.to,G.path);if(!nY(K))throw Error(`invalid registry id "${K}" derived from to="${G.to}"`);if(A.has(K))throw Error(`duplicate registry id "${K}" — set an explicit \`id\` on one of the proxies`);return A.add(K),{...G,id:K}}),J=new Date().toISOString();for(let G of X)await m8({id:G.id,from:G.from,to:G.to,path:G.path,pid:w.persistent?void 0:xw.pid,cwd:xw.cwd(),createdAt:J,cleanUrls:G.cleanUrls,changeOrigin:G.changeOrigin,pathRewrites:G.pathRewrites,static:G.static,loadBalancer:G.loadBalancer},Y,$);let U=await q5({rpxDir:w.rpxDir,verbose:$,spawnCommand:w.spawnCommand,startupTimeoutMs:w.startupTimeoutMs,spawnEnv:w.spawnEnv});for(let G of X){let K=G.static?`static ${typeof G.static==="string"?G.static:G.static.dir}`:G.from;H.success(`https://${G.to} → ${K}`)}if(H.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),w.detached)return;let W=!1,Q=Y??kw(),B=X.map((G)=>G.id),j=async()=>{if(W)return;W=!0;for(let G of B)await pY(G,Y,$).catch((K)=>{F("runner",`removeEntry(${G}) failed: ${K}`,$)})},z=(G)=>{F("runner",`received ${G}, unregistering ${B.length} entries`,$),j().finally(()=>xw.exit(0))};xw.once("SIGINT",z),xw.once("SIGTERM",z),xw.once("exit",()=>{if(W)return;for(let G of B)try{r5.unlinkSync(t5.join(Q,`${G}.json`))}catch{}}),await new Promise(()=>{})}p8();L8();bW();nw();X0();import{spawn as fM}from"node:child_process";import*as JJ from"node:process";class UJ{processes=new Map;isShuttingDown=!1;async startProcess(w,$,Y){if(this.processes.has(w)){F("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||JJ.cwd();F("start",`Starting process ${w}:`,Y),F("start",` Command: ${A} ${X.join(" ")}`,Y),F("start",` Working directory: ${J}`,Y),F("start",` Environment variables: ${Iw($.env)}`,Y);let U=fM(A,X,{cwd:J,env:{...JJ.env,...$.env},shell:!0,stdio:"inherit"});return this.processes.set(w,{command:$.command,cwd:J,process:U,env:$.env}),new Promise((W,Q)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)F("start",`Process ${w} failed to start: ${B}`,Y),this.processes.delete(w),Q(B)}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)F("start",`Process ${w} exited with code ${B}; leaving the proxy running`,Y),this.processes.delete(w),Q(Error(`Process ${w} exited with code ${B}`))}),Y)U.stdout?.on("data",(B)=>{F("process",`[${w}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{F("process",`[${w}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete(w),Q(Error(`Process ${w} was killed during startup`));else F("start",`Process ${w} started successfully`,Y),W()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);if(!Y?.process){F("start",`No process found for ${w}`,$);return}return F("start",`Stopping process ${w}`,$),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete(w),F("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){F("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){F("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){F("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,F("start","Stopping all processes",w);let $=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,w).catch((A)=>{H.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled($),this.processes.clear(),this.isShuttingDown=!1}isRunning(w){let $=this.processes.get(w);return!!$?.process&&!$.process.killed}}var qS=new UJ;import{timingSafeEqual as TM}from"node:crypto";function HM(w,$){if(w==null)return!1;let Y=Buffer.from(w),A=Buffer.from($);if(Y.length!==A.length)return!1;return TM(Y,A)}function QJ(w){return w.toLowerCase().replace(/\.$/,"")}var RM=["/.well-known/acme-challenge/"];function MM(w){let $=w.headers.get("host");if($)return QJ($.split(":")[0]);try{return QJ(new URL(w.url).hostname)}catch{return""}}function a5(w){let $=w.header.toLowerCase(),Y=new Set,A=[];for(let Q of w.hosts){let B=QJ(Q);if(B.startsWith("*."))A.push(B);else Y.add(B)}let X=w.exemptPaths??RM,J=w.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
338
- `,U=(Q)=>{let B=QJ(Q);return Y.has(B)||A.some((j)=>TY(B,j))},W=(Q)=>{let B=MM(Q);if(!U(B))return;let j="/";try{j=new URL(Q.url).pathname}catch{}if(X.some((z)=>j.startsWith(z)))return;if(HM(Q.headers.get($),w.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return W.protects=U,W}k8();h8();cY();dY();x8();b8();mY();X0();var BJ=new UJ,VM="0.12.0",CM=new c8("0.0.0.0"),YA=new Set,zJ=new Set,GB=!1,WJ=null,KB=null;async function KJ(w){if(GB)return F("cleanup","Cleanup already in progress, skipping",w?.verbose),KB||Promise.resolve();GB=!0,F("cleanup","Starting cleanup process",w?.verbose),KB=new Promise(($)=>{WJ=$});try{await BJ.stopAll(w?.verbose),H.info("Shutting down proxy servers...");let $=[],Y=Array.from(YA).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),F("cleanup","Bun server stopped",w?.verbose),X();else if(typeof J.close==="function")J.close(()=>{F("cleanup","Server closed successfully",w?.verbose),X()});else X()}catch(U){F("cleanup",`Error stopping server: ${U}`,w?.verbose),X()}}));$.push(...Y),YA.clear();for(let A of zJ)n$(A);if(zJ.clear(),w?.hosts&&w.domains?.length){F("cleanup","Cleaning up hosts file entries",w?.verbose),F("cleanup",`Original domains for cleanup: ${JSON.stringify(w.domains)}`,w?.verbose);let A=w.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(F("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,w?.verbose),A.length>0)H.info("Cleaning up hosts file entries..."),$.push(G5(A,w?.verbose).then(()=>{F("cleanup",`Removed hosts entries for ${A.join(", ")}`,w?.verbose)}).catch((X)=>{F("cleanup",`Failed to remove hosts entries: ${X}`,w?.verbose),H.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if(w?.certs&&w.domains?.length){F("cleanup","Cleaning up SSL certificates",w?.verbose),H.info("Cleaning up SSL certificates...");let A=w.domains.map(async(X)=>{try{await OG(X,w?.verbose),F("cleanup",`Removed certificates for ${X}`,w?.verbose)}catch(J){F("cleanup",`Failed to remove certificates for ${X}: ${J}`,w?.verbose),H.warn(`Failed to clean up certificates for ${X}:`,J)}});$.push(...A)}await Promise.allSettled($),F("cleanup","All cleanup tasks completed successfully",w?.verbose),H.success("All cleanup tasks completed successfully")}catch($){F("cleanup",`Error during cleanup: ${$}`,w?.verbose),H.error("Error during cleanup:",$)}finally{if(WJ)WJ();WJ=null,GB=!1;let $=w&&"vitePluginUsage"in w&&w.vitePluginUsage===!0;if(J0.env.NODE_ENV!=="test"&&J0.env.BUN_ENV!=="test"&&!$)J0.exit(0)}return KB}var FB=!1;function $6(w){if(FB){F("signal",`Received second ${w} signal, forcing exit`,!0),J0.exit(1);return}FB=!0,F("signal",`Received ${w} signal, initiating cleanup`,!0),KJ().catch(($)=>{F("signal",`Cleanup failed after ${w}: ${$}`,!0),J0.exit(1)}).finally(()=>{FB=!1})}J0.once("SIGINT",()=>$6("SIGINT"));J0.once("SIGTERM",()=>$6("SIGTERM"));J0.on("uncaughtException",(w)=>{H.error("Uncaught exception (continuing):",w)});J0.on("unhandledRejection",(w)=>{H.error("Unhandled rejection (continuing):",w)});async function AA(w,$,Y,A=5){F("connection",`Testing connection to ${w}:${$} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(J0.env.RPX_BYPASS_CONNECTION_TEST==="true"){F("connection",`Bypassing connection test for ${w}:${$} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((W,Q)=>{let B=o5.connect({host:w,port:$,timeout:3000});B.once("connect",()=>{F("connection",`Successfully connected to ${w}:${$}`,Y),B.end(),W()}),B.once("timeout",()=>{F("connection",`Connection to ${w}:${$} timed out`,Y),B.destroy(),Q(Error("Connection timed out"))}),B.once("error",(j)=>{F("connection",`Failed to connect to ${w}:${$}: ${j}`,Y),B.destroy(),Q(j)})});try{await U()}catch(W){let Q=W;if(Date.now()-J>X){F("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),H.warn(`Connection test to ${w}:${$} timed out, but RPX will try to proceed anyway.`);return}if(Q.code==="ECONNREFUSED"&&A>0)return F("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((j)=>setTimeout(j,2000)),AA(w,$,Y,A-1);if(A>0)try{F("connection",`Trying HTTP request to ${w}:${$}`,Y),await new Promise((j,z)=>{let G=GJ.request({hostname:w,port:$,path:"/",method:"HEAD",timeout:5000},(K)=>{F("connection",`Received HTTP response with status: ${K.statusCode}`,Y),j()});G.on("error",(K)=>z(K)),G.on("timeout",()=>{G.destroy(),z(Error("HTTP request timed out"))}),G.end()}),F("connection",`HTTP request to ${w}:${$} succeeded`,Y);return}catch(j){return F("connection",`HTTP request to ${w}:${$} failed: ${j}`,Y),F("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),AA(w,$,Y,A-1)}let B=`Failed to connect to ${w}:${$} after ${5-A} attempts: ${Q.message}`;F("connection",`${B}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),H.warn(B),H.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function Y6(w){F("server",`Starting server with options: ${Iw(w)}`,w.verbose);let $=_$(w.from),Y=new URL($.startsWith("http")?$:`http://${$}`),A=new URL((w.to?.startsWith("http")?w.to:`http://${w.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(qB(w)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){F("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,w?.verbose);try{if(!(await oY(J,w.verbose))[0]){H.info(`Adding ${A.hostname} to hosts file...`),H.info("This may require sudo/administrator privileges");try{await sY(J,w.verbose)}catch(Q){if(H.error("Failed to add hosts entry:",Q.message),H.warn("You can manually add this entry to your hosts file:"),H.warn(`127.0.0.1 ${A.hostname}`),H.warn(`::1 ${A.hostname}`),J0.platform==="win32")H.warn("On Windows:"),H.warn("1. Run notepad as administrator"),H.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else H.warn("On Unix systems:"),H.warn("sudo nano /etc/hosts")}}else F("hosts",`Host entry already exists for ${A.hostname}`,w.verbose)}catch(W){H.error("Failed to check hosts file:",W.message)}}try{await AA(Y.hostname,X,w.verbose)}catch(W){F("server",`Connection test failed: ${W}`,w.verbose),H.error(W.message),H.warn("Continuing with proxy setup despite connection test failure..."),H.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=w._cachedSSLConfig||null;if(w.https)try{if(w.https===!0)w.https=PY({...w,to:A.hostname});if(U=await W$({...w,to:A.hostname,https:w.https}),!U){if(F("ssl",`Generating new certificates for ${A.hostname}`,w.verbose),await n1({...w,from:Y.toString(),to:A.hostname,https:w.https}),U=await W$({...w,to:A.hostname,https:w.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(W){throw F("server",`SSL setup failed: ${W}`,w.verbose),W}F("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,w.verbose),await OM({...w,from:$,originalFrom:w.from||$,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function yM(w,$,Y,A,X,J,U,W,Q,B,j,z){F("proxy",`Creating proxy server ${w} -> ${$} with cleanUrls: ${W}`,U);let G=p1(j??A.host,z);r1(G);let K=[{host:$,route:{sourceHost:A.host,upstreamPool:G,cleanUrls:W||!1,changeOrigin:Q||!1,basePath:"/",auth:B}}];if(!jJ({routeEntries:K,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw n$(G),Error(`Failed to start proxy server for ${$} on port ${Y}`);zJ.add(G),_M({from:w,to:$,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:W,verbose:U})}async function OM(w){F("setup",`Setting up reverse proxy: ${Iw(w)}`,w.verbose);let{from:$,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:W,vitePluginUsage:Q,changeOrigin:B,cleanUrls:j}=w,z=80,G=443,K="0.0.0.0",E=w.portManager||CM,q=qB(w);try{if(q&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await oY([A],U))[0]){H.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await sY([A],U),H.success(`Added ${A} to your hosts file.`)}catch(y){H.error(`Failed to add ${A} to your hosts file: ${y}`),H.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]){F("hosts",`${A} not found in hosts file, adding...`,U);try{await sY([A],U)}catch(y){F("hosts",`Failed to add ${A} to hosts file: ${y}`,U)}}}if(J&&!E.usedPorts.has(z)){if(!await Z$(z,K,U))F("setup","Starting HTTP redirect server",U),A6(U),E.usedPorts.add(z);else if(F("setup","Port 80 is in use, skipping HTTP redirect",U),U)H.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let N=J?G:z,f=await Z$(N,K,U),R;if(f){if(F("setup",`Port ${N} is already in use`,U),U)H.warn(`Port ${N} is already in use. This may be another instance of rpx or another service.`);if(N===443){if(R=await E.getNextAvailablePort(3443,!0),F("setup",`Using port ${R} instead of ${N}`,U),U)H.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await E.getNextAvailablePort(N+1000,!0),F("setup",`Using port ${R} instead of ${N}`,U),U)H.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=N,E.usedPorts.add(R),F("setup",`Using standard ${N===443?"HTTPS":"HTTP"} port ${N} for ${A}`,U);await yM($,A,R,X,J,Q,U,j,B,t1(w.auth),Y,w.loadBalancer)}catch(N){F("setup",`Setup failed: ${N}`,U),H.error(`Failed to setup reverse proxy: ${N.message}`),KJ({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:U,vitePluginUsage:Q})}}function A6(w,$=80,Y=443,A,X){F("redirect",`Starting HTTP redirect server on port ${$}`,w);let J=GJ.createServer((U,W)=>{let Q=U.url?U.url.split("?",1)[0]:"";if(Q.startsWith("/.well-known/acme-challenge/")){if(X){let G=X.challengeStore.handlePath(Q);if(G!==void 0){F("redirect",`Serving on-demand ACME challenge ${Q}`,w),W.writeHead(200,{"content-type":"text/plain"}),W.end(G);return}}if(A){let G=gY(A,Q);if(G!=null){F("redirect",`Serving ACME challenge ${Q}`,w),W.writeHead(200,{"content-type":"text/plain"}),W.end(G);return}}if(X){W.writeHead(404,{"content-type":"text/plain"}),W.end("challenge not found");return}}let B=U.headers.host||"",j=B.includes(":")?B.slice(0,B.indexOf(":")):B;if(X&&j&&!X.hasCert(j))X.ensureCert(j).catch(()=>{});let z=Y===443?j:`${j}:${Y}`;F("redirect",`Redirecting request from ${B}${U.url} to https://${z}`,w),W.writeHead(301,{Location:`https://${z}${U.url}`}),W.end()}).listen($);YA.add(J),F("redirect","HTTP redirect server started",w)}function X6(w){let $={...ZQ,...w};if(F("proxy",`Starting proxy with options: ${Iw($)}`,$?.verbose),$.viaDaemon){if(!$.from||!$.to){H.error("viaDaemon mode requires both `from` and `to`");return}zB({proxies:[{id:$.id,from:$.from,to:$.to,path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}],verbose:$.verbose}).catch((Q)=>{H.error(`Failed to register with rpx daemon: ${Q.message}`),J0.exit(1)});return}let Y=$.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)&&$?.verbose)H.warn(`The .${A} TLD may not work reliably for local development`),H.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),H.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (JY(),s8)).then(({setupDevelopmentDns:Q})=>{Q({domains:[Y],verbose:$.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if($.verbose)if(U.includes(A))H.success(`DNS server started for .${A} domains`);else H.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else F("dns",`Could not start DNS server - ${Y} may not resolve in browser`,$.verbose)})}).catch((Q)=>{F("dns",`Failed to start DNS server: ${Q}`,$.verbose)});let W={from:$.from,to:$.to,cleanUrls:$.cleanUrls,https:PY($),cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,changeOrigin:$.changeOrigin,verbose:$.verbose,regenerateUntrustedCerts:$.regenerateUntrustedCerts};F("proxy",`Server options: ${Iw(W)}`,$.verbose),Y6(W).catch((Q)=>{F("proxy",`Failed to start proxy: ${Q}`,$.verbose),H.error(`Failed to start proxy: ${Q.message}`),KJ({domains:[$.to],hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose})})}function LM(w){return w?.verbose||!1}function qB(w){if(w?.hostsManagement===!1)return!1;let $=w?.cleanup;if($===!1)return!1;if($&&typeof $==="object"&&$.hosts===!1)return!1;return!0}async function J6(w){let $={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(w)$={...$,...w};let Y=LM($),A=qB($);if(F("config",`Starting with config: ${Iw($,2)}`,Y),F("config",`Is multi-proxy? ${"proxies"in $}`,Y),F("config",`Hosts management enabled? ${A}`,Y),$.viaDaemon){let M="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((V)=>({id:V.id,from:V.from,to:V.to,path:V.path,cleanUrls:V.cleanUrls??$.cleanUrls,changeOrigin:V.changeOrigin??$.changeOrigin,pathRewrites:V.pathRewrites})):[{id:$.id,from:$.from,to:$.to??"rpx.localhost",path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}];await zB({proxies:M,verbose:Y});return}if("proxies"in $&&Array.isArray($.proxies)){F("servers",`Found ${$.proxies.length} proxies in config`,Y);for(let T of $.proxies)if(T.start){let M=`${T.from}-${T.to}`;try{F("watch",`Starting command for ${M} with command: ${T.start.command}`,Y),H.info(`Starting command for ${M}...`),await BJ.startProcess(M,T.start,Y);let V=_$(T.from),S=new URL(V.startsWith("http")?V:`http://${V}`),U0=S.hostname||"localhost",v0=Number(S.port)||80;try{await AA(U0,v0,Y),F("watch",`Dev server is ready at ${U0}:${v0}`,Y)}catch(Kw){F("watch",`Connection check failed, but continuing with proxy setup: ${Kw}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(V){throw F("watch",`Failed to start command for ${M}: ${V}`,Y),Error(`Failed to start command for ${M}: ${V}`)}}else F("watch",`No start command for proxy ${T.from} -> ${T.to}`,Y)}else if("start"in $&&$.start){F("watch","Found start command in single proxy config",Y);let T=`${$.from}-${$.to}`;try{if($.start)F("watch",`Starting command: ${$.start.command}`,Y),await BJ.startProcess(T,$.start,Y);let M=_$($.from),V=new URL(M.startsWith("http")?M:`http://${M}`),S=V.hostname||"localhost",U0=Number(V.port)||80;try{await AA(S,U0,Y),F("watch",`Dev server is ready at ${S}:${U0}`,Y)}catch(v0){F("watch",`Connection check failed, but continuing with proxy setup: ${v0}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw F("watch",`Failed to run start command: ${M}`,Y),Error(`Failed to run start command: ${M}`)}}else F("watch","No start command found in config",Y);let X="proxies"in $&&Array.isArray($.proxies)?$.proxies[0]?.to:("to"in $)?$.to:"rpx.localhost";if(J0.platform!=="win32"&&($.https||A)){if(!V$())try{F("sudo","Pre-acquiring sudo credentials for privileged operations",Y),IM("sudo -v",{stdio:"inherit"})}catch{F("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if($.productionCerts){if(J=await wY($.productionCerts,Y),J.length>0)F("ssl",`Using ${J.length} production SNI cert(s): ${J.map((T)=>T.serverName).join(", ")}`,Y)}if($.https){let T=J.length>0?null:await W$($);if(!T&&J.length===0){if(F("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,$.verbose),await n1($),T=await W$($),!T)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else F("ssl",`Using existing and trusted certificates for ${X}`,$.verbose);$._cachedSSLConfig=T}let U="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((T)=>({...T,https:$.https,cleanup:$.cleanup,cleanUrls:T.cleanUrls??("cleanUrls"in $?$.cleanUrls:!1),vitePluginUsage:$.vitePluginUsage,changeOrigin:T.changeOrigin??$.changeOrigin,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig})):[{from:"from"in $?$.from:"localhost:5173",to:"to"in $?$.to:"rpx.localhost",cleanUrls:"cleanUrls"in $?$.cleanUrls:!1,https:$.https,cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,start:"start"in $?$.start:void 0,changeOrigin:$.changeOrigin,auth:"auth"in $?$.auth:void 0,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig}],W=U.map((T)=>T.to||"rpx.localhost"),Q=J.length>0?J:$._cachedSSLConfig??null,B=W.filter((T)=>T&&!T.includes("localhost")&&!T.includes("127.0.0.1")),j=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"],G=[...new Set(B.map((T)=>T.split(".").pop()?.toLowerCase()))],K=G.filter((T)=>!!T&&j.includes(T));if(K.length>0&&Y)H.warn(`The following TLDs may not work reliably for local development: ${K.map((T)=>`.${T}`).join(", ")}`),H.info(" These TLDs have HSTS preloading which can bypass local DNS"),H.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&J0.platform==="darwin"&&B.length>0){let{setupDevelopmentDns:T}=await Promise.resolve().then(() => (JY(),s8));if(await T({domains:B,verbose:Y})){if(Y)if(G.every((S)=>!!S&&z.includes(S)))H.success(`DNS server started for ${G.map((S)=>`.${S}`).join(", ")} domains`);else H.success(`DNS server started for ${G.map((S)=>`.${S}`).join(", ")} domains (hosts file entries also added)`)}else F("dns","Could not start DNS server - custom domains may not resolve",Y)}let E=async()=>{F("cleanup","Starting cleanup handler",$.verbose);try{let{tearDownDevelopmentDns:T}=await Promise.resolve().then(() => (JY(),s8));await T({verbose:$.verbose})}catch(T){F("cleanup",`Error stopping DNS server: ${T}`,$.verbose)}try{await BJ.stopAll($.verbose)}catch(T){F("cleanup",`Error stopping processes: ${T}`,$.verbose)}await KJ({domains:W,hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose||!1})};J0.on("SIGINT",E),J0.on("SIGTERM",E);let q=$.singlePortMode===!0,N=$.httpsPort??443,f=$.httpPort??80,R=$.originGuard?a5($.originGuard):null,O=!!Q&&(U.length>1||q||J.length>0),y=!Q&&q&&U.length>0;if(O&&Q){F("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${N}`,Y);let T=await s5(U,A,Y),M=null,V=$.onDemandTls,S=V?.enabled?new r$({config:V,certsDir:V.certsDir??$.productionCerts?.certsDir??w6.join(e5.homedir(),".stacks","rpx","on-demand-certs"),initial:J,verbose:Y,onCertAdded:(Fw)=>{Kw(Fw)}}):null,U0=null,v0=!1;async function Kw(Fw){if(U0=Fw,v0)return;v0=!0;try{while(U0){let uw=U0;if(U0=null,F("proxies",`rebuilding :${N} with ${uw.length} SNI cert(s)`,Y),M)YA.delete(M),M.stop(!1);let s0=!1;for(let Z=0;!s0&&Z<60;Z++){let yw=jJ({routeEntries:T,listenPort:N,sslConfig:uw,originGuard:R,verbose:Y});if(yw){M=yw,s0=!0;break}await new Promise((BY)=>setTimeout(BY,Math.min(25*2**Math.min(Z,4),500)))}if(!s0)H.error(`rpx: CRITICAL — could not rebind :${N} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{v0=!1}}if(!await Z$(f,"0.0.0.0",Y))A6(Y,f,N,$.acmeChallengeWebroot,S);if(await Z$(N,"0.0.0.0",Y)){if(F("proxies",`Port ${N} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${N} is in use. Shared HTTPS proxy cannot start.`);return}let bw=S&&S.sniEntries().length>0?S.sniEntries():Q;if(M=jJ({routeEntries:T,listenPort:N,sslConfig:bw,originGuard:R,verbose:Y}),!M){H.error(`Shared HTTPS proxy failed to bind :${N}; not exiting`);return}}else if(y){F("proxies",`Creating shared HTTP server for ${U.length} domains on port ${f}`,Y);let T=await s5(U,A,Y);if(await Z$(f,"0.0.0.0",Y)){if(F("proxies",`Port ${f} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${f} is in use. Shared HTTP proxy cannot start.`);return}if(!jJ({routeEntries:T,listenPort:f,sslConfig:null,originGuard:R,verbose:Y})){H.error(`Shared HTTP proxy failed to bind :${f}; not exiting`);return}}else for(let T of U)try{let M=T.to||"rpx.localhost";F("proxy",`Starting proxy for ${M} with SSL config: ${!!Q}`,T.verbose),await Y6({from:T.from||"localhost:5173",to:M,cleanUrls:T.cleanUrls||!1,https:T.https||!1,cleanup:T.cleanup||!1,vitePluginUsage:T.vitePluginUsage||!1,verbose:T.verbose||!1,_cachedSSLConfig:$._cachedSSLConfig,changeOrigin:T.changeOrigin||!1,loadBalancer:T.loadBalancer,auth:T.auth,path:T.path,pathRewrites:T.pathRewrites})}catch(M){F("proxies",`Failed to start proxy for ${T.to}: ${M}`,T.verbose),H.error(`Failed to start proxy for ${T.to}:`,M)}}async function s5(w,$,Y){let A=[],X=new Set;for(let J of w){let U=J.to||"rpx.localhost",W=J.cleanUrls||!1,Q=J.path,B=Sw(Q),j=t1(J.auth);if(J.redirect){let z=mG(J.redirect);A.push({host:U,path:Q,route:{redirect:z,basePath:B,auth:j}}),F("proxies",`Route: ${U}${Q??""} → redirect ${z.status} ${z.to}${j?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:Q,route:{static:iY(J.static,W),cleanUrls:W,basePath:B,auth:j}}),F("proxies",`Route: ${U}${Q??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${j?" (auth)":""}`,Y);else{let z=_$(J.from),G=new URL(z.startsWith("http")?z:`http://${z}`),K=p1(J.from??G.host,J.loadBalancer);r1(K),zJ.add(K),A.push({host:U,path:Q,route:{sourceHost:G.host,upstreamPool:K,cleanUrls:W,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:B,auth:j}}),F("proxies",`Route: ${U}${Q??""} → ${G.host}${j?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),$&&!q1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await oY([U],Y))[0])await sY([U],Y)}catch{F("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function jJ(w){let{routeEntries:$,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=w,U=o1($),W=a1((j,z)=>e1(U,j,z),J),Q=X?(j,z)=>X(j)??W(j,z):W,B=s1(J);try{let j=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:g1(),...A?{tls:S$(Array.isArray(A)?A.map((z)=>({serverName:z.serverName,key:z.key,cert:z.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(z,G){return Q(z,G)},websocket:B,error(z){return F("server",`Shared proxy server error: ${z}`,J),new Response(`Server Error: ${z.message}`,{status:500})}});return YA.add(j),F("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),j}catch(j){return F("proxies",`Failed to start shared proxy: ${j}`,J),console.error("Failed to start shared proxy:",j),null}}function _M(w){if(w?.vitePluginUsage||!w?.verbose)return;if(console.log(""),console.log(` ${Dw.green(Dw.bold("rpx"))} ${Dw.green(`v${VM}`)}`),console.log(` ${Dw.green("➜")} ${Dw.dim(w?.from??"")} ${Dw.dim("➜")} ${Dw.cyan(w?.ssl?`https://${w?.to}`:`http://${w?.to}`)}`),w?.listenPort!==(w?.ssl?443:80))console.log(` ${Dw.green("➜")} Listening on port ${w?.listenPort}`);if(w?.cleanUrls)console.log(` ${Dw.green("➜")} Clean URLs enabled`)}NW();var nS=new d$("rpx",{showTags:!1});function U6(w){return!!(w&&("proxies"in w)&&Array.isArray(w.proxies))}P0.chdir(ZM(SM(kM(import.meta.url)),".."));var c0=new CJ("rpx"),Q6="0.12.0";c0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async(w)=>{if(!w?.from||!w.to)return J6(F1);let $={from:w.from,to:w.to,https:{keyPath:w.keyPath,certPath:w.certPath,caCertPath:w.caCertPath},cleanup:{certs:w.certsCleanup||!1,hosts:w.hostsCleanup||!1},verbose:w.verbose||!1,changeOrigin:w.changeOrigin||!1,singlePortMode:w.singlePortMode||!1,httpPort:w.httpPort!==void 0?Number(w.httpPort):void 0,httpsPort:w.httpsPort!==void 0?Number(w.httpsPort):void 0,viaDaemon:w.viaDaemon||!1,id:w.id};if(w.startCommand){let Y={command:w.startCommand};if(w.startCwd)Y.cwd=w.startCwd;if(w.startEnv)try{Y.env=JSON.parse(w.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),P0.exit(1)}$.start=Y}return X6($)});c0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{let Y=U6(F1)?F1.proxies.find((A)=>A.to===w||`${A.from}-${A.to}`===w):F1.to===w?F1:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${w}`),P0.exit(1);try{await AJ.startProcess(w,Y.start,$.verbose),console.log(`Started dev server for ${w}`)}catch(A){console.error(`Failed to start dev server for ${w}:`,A),P0.exit(1)}});c0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{try{await AJ.stopProcess(w,$.verbose),console.log(`Stopped dev server for ${w}`)}catch(Y){console.error(`Failed to stop dev server for ${w}:`,Y),P0.exit(1)}});c0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(w)=>{try{await AJ.stopAll(w.verbose),console.log("Stopped all dev servers")}catch($){console.error("Failed to stop all dev servers:",$),P0.exit(1)}});async function W6(w){let Y={...(await A9().catch(()=>null))?.onDemand??{},enabled:!0};if(w){let A=w.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}c0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(w)=>{try{let $=w.onDemand?await W6(w.roots):void 0;await(await v5({rpxDir:w.rpxDir,registryDir:w.registryDir,httpsPort:typeof w.httpsPort==="string"?Number.parseInt(w.httpsPort,10):w.httpsPort,httpPort:typeof w.httpPort==="string"?Number.parseInt(w.httpPort,10):w.httpPort,hostname:w.hostname,productionCerts:w.certsDir?{certsDir:w.certsDir}:void 0,workers:w.workers===void 0?void 0:typeof w.workers==="string"?Number.parseInt(w.workers,10):w.workers,onDemandSites:$,verbose:w.verbose??!0})).done,P0.exit(0)}catch($){console.error(`Failed to start rpx daemon: ${$.message}`),P0.exit(1)}});c0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async(w)=>{let $=typeof w.timeout==="string"?Number.parseInt(w.timeout,10):w.timeout,Y=await m5({rpxDir:w.rpxDir,timeoutMs:$,forceAfterTimeout:w.force!==!1,verbose:w.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});c0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async(w)=>{let $=w.rpxDir??Aw(),Y=await D$($),A=await $J($),X=w.registryDir,J=await jB(X).catch(()=>[]);if(w.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:x$($),rpxDir:$,registryDir:X??o$(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${x$($)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${x$($)}`);if(console.log(`registry: ${X??o$()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let W=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} \u2192 ${U.from} (id=${U.id}${W})`)}});c0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async(w)=>{if(!w.id||!w.from||!w.to)console.error("rpx register requires --id, --from, and --to"),P0.exit(1);if(!WY(w.id))console.error(`invalid id: ${JSON.stringify(w.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),P0.exit(1);try{await n5({id:w.id,from:w.from,to:w.to,cwd:w.cwd,createdAt:new Date().toISOString(),cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin},w.registryDir,w.verbose)}catch($){console.error(`failed to write registry entry: ${$.message}`),P0.exit(1)}if(w.skipSpawn){console.log(`registered ${w.to} \u2192 ${w.from} (daemon spawn skipped)`);return}try{let $=await i5({rpxDir:w.rpxDir,verbose:w.verbose}),Y=$.spawned?"spawned":"attached to";console.log(`registered https://${w.to} \u2192 ${w.from} (${Y} daemon pid=${$.pid})`)}catch($){console.error(`registered entry but daemon spawn failed: ${$.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),P0.exit(1)}});c0.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(!WY(w))console.error(`invalid id: ${JSON.stringify(w)}`),P0.exit(1);let Y=await BB(w,$.registryDir,$.verbose);if(!Y){console.log(`no registry entry for id=${w}`);return}await p5(w,$.registryDir,$.verbose),console.log(`unregistered ${Y.to} (id=${w})`)});c0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async(w)=>{let $=w.rpxDir??Aw();if(await $J($)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await g5({rpxDir:$,verbose:w.verbose}),console.log("DNS reconcile complete")});c0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(w)=>{let $=await W6(w.roots),Y=W9($),A=await jB(w.registryDir).catch(()=>[]),X=new Set(A.map((W)=>W.to)),J=Y.map((W)=>({host:W.host,dir:W.dir,command:W.command,source:W.source,live:X.has(W.host)}));if(w.json){console.log(JSON.stringify(J,null,2));return}let U=$.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) \u2014 scanned ${U.join(", ")}:`);for(let W of J)console.log(` ${W.live?"\u25CF":"\u25CB"} https://${W.host} ${W.live?"(live)":"(idle)"}`),console.log(` ${W.command} ${W.dir}`)});c0.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=$.rpxDir??Aw(),J=A(X,"sites",`${rA(w.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${w} (it may not have been booted yet) \u2014 looked in ${J}`);return}let W=$.lines===void 0?void 0:typeof $.lines==="string"?Number.parseInt($.lines,10):$.lines,Q=U.split(`
339
- `);P0.stdout.write((W&&W>0?Q.slice(-W):Q).join(`
340
- `))});c0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(Q6)});c0.version(Q6);c0.help();c0.run();
335
+ `)),this._prevFrame=w;return}this.output.write(XJ.down())}if(this.output.write(w),this.state==="initial")this.state="active";this._prevFrame=w}}function v5(w,$){if(w===void 0)return 0;if($.length===0)return 0;let A=$.findIndex((X)=>X.value===w);return A!==-1?A:0}function c5(w,$){return($.label??String($.value)).toLowerCase().includes(w.toLowerCase())}function m5(w,$){if(!$)return;if(w)return $;return $[0]}class g5 extends BJ{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#w=0;#Y="";#A;#$;get cursor(){return this.#w}get userInputWithCursor(){if(!this.userInput)return tY.inverse(tY.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let w=this.userInput.slice(0,this._cursor),[$,...Y]=this.userInput.slice(this._cursor);return`${w}${tY.inverse($)}${Y.join("")}`}get options(){if(typeof this.#$==="function")return this.#$();return this.#$}constructor(w){super(w);this.#$=w.options;let $=this.options;this.filteredOptions=[...$],this.multiple=w.multiple===!0,this.#A=w.filter??c5;let Y;if(w.initialValue&&Array.isArray(w.initialValue))if(this.multiple)Y=w.initialValue;else Y=w.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let A of Y){let X=$.findIndex((J)=>J.value===A);if(X!==-1)this.toggleSelected(A),this.#w=X}this.focusedValue=this.options[this.#w]?.value,this.on("key",(A,X)=>this.#X(A,X)),this.on("userInput",(A)=>this.#J(A))}_isActionKey(w,$){return w==="\t"||this.multiple&&this.isNavigating&&$.name==="space"&&w!==void 0&&w!==""}#X(w,$){let Y=$.name==="up",A=$.name==="down",X=$.name==="return";if(Y||A){if(this.#w=Math.max(0,Math.min(this.#w+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=m5(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&($.name==="tab"||this.isNavigating&&$.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(w){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(w))this.selectedValues=this.selectedValues.filter(($)=>$!==w);else this.selectedValues=[...this.selectedValues,w];else this.selectedValues=[w]}#J(w){if(w!==this.#Y){this.#Y=w;let $=this.options;if(w)this.filteredOptions=$.filter((Y)=>this.#A(w,Y));else this.filteredOptions=[...$];if(this.#w=v5(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#w]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class d5 extends BJ{options;cursor=0;#w;getGroupItems(w){return this.options.filter(($)=>$.group===w)}isGroupSelected(w){let $=this.getGroupItems(w),Y=this.value;if(Y===void 0)return!1;return $.every((A)=>Y.includes(A.value))}toggleValue(){let w=this.options[this.cursor];if(this.value===void 0)this.value=[];if(w.group===!0){let $=String(w.value),Y=this.getGroupItems($);if(this.isGroupSelected($))this.value=this.value.filter((A)=>Y.findIndex((X)=>X.value===A)===-1);else this.value=[...this.value,...Y.map((A)=>A.value)];this.value=Array.from(new Set(this.value))}else{let $=this.value.includes(w.value);this.value=$?this.value.filter((Y)=>Y!==w.value):[...this.value,w.value]}}constructor(w){super(w,!1);let{options:$}=w;this.#w=w.selectableGroups!==!1,this.options=Object.entries($).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((X)=>({...X,group:Y}))]),this.value=[...w.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===w.cursorAt),this.#w?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let A=this.options[this.cursor]?.group===!0;if(!this.#w&&A)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let A=this.options[this.cursor]?.group===!0;if(!this.#w&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var n5=eG();var w0=(w,$)=>n5?w:$,UM=w0("◆","*"),WM=w0("■","x"),QM=w0("▲","x"),jM=w0("◇","o"),BM=w0("┌","T"),l5=w0("│","|"),fM=w0("└","—"),zM=w0("●",">"),GM=w0("○"," "),EM=w0("◻","[•]"),KM=w0("◼","[+]"),FM=w0("◻","[ ]"),TM=w0("▪","•"),qM=w0("─","-"),NM=w0("╮","+"),HM=w0("├","+"),RM=w0("╯","+"),MM=w0("●","•"),yM=w0("◆","*"),IM=w0("▲","!"),CM=w0("■","x");var VM={light:w0("─","-"),heavy:w0("━","="),block:w0("█","#")};function p5(){return`${tY.gray(l5)} `}var LM=p5();xA();JU();x8();k$();f0();import{spawn as HR}from"node:child_process";import*as c8 from"node:process";class m8{processes=new Map;isShuttingDown=!1;async startProcess(w,$,Y){if(this.processes.has(w)){E("start",`Process ${w} is already running`,Y);return}let[A,...X]=$.command.split(" "),J=$.cwd||c8.cwd();E("start",`Starting process ${w}:`,Y),E("start",` Command: ${A} ${X.join(" ")}`,Y),E("start",` Working directory: ${J}`,Y),E("start",` Environment variables: ${A$($.env)}`,Y);let U=HR(A,X,{cwd:J,env:{...c8.env,...$.env},shell:!0,stdio:"inherit"});return this.processes.set(w,{command:$.command,cwd:J,process:U,env:$.env}),new Promise((Q,W)=>{if(U.on("error",(j)=>{if(!this.isShuttingDown)E("start",`Process ${w} failed to start: ${j}`,Y),this.processes.delete(w),W(j)}),U.on("exit",(j)=>{if(!this.isShuttingDown&&j!==null&&j!==0)E("start",`Process ${w} exited with code ${j}; leaving the proxy running`,Y),this.processes.delete(w),W(Error(`Process ${w} exited with code ${j}`))}),Y)U.stdout?.on("data",(j)=>{E("process",`[${w}] ${j.toString().trim()}`,!0)}),U.stderr?.on("data",(j)=>{E("process",`[${w}] ERR: ${j.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete(w),W(Error(`Process ${w} was killed during startup`));else E("start",`Process ${w} started successfully`,Y),Q()},1000)})}async stopProcess(w,$){let Y=this.processes.get(w);if(!Y?.process){E("start",`No process found for ${w}`,$);return}return E("start",`Stopping process ${w}`,$),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete(w),E("start",`Process ${w} stopped`,$),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){E("start",`Force killing process ${w}`,$);try{Y.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){E("start",`Error stopping process ${w}: ${X}`,$),this.processes.delete(w),A()}})}async stopAll(w){if(this.isShuttingDown){E("start","Already shutting down, skipping duplicate stopAll call",w);return}this.isShuttingDown=!0,E("start","Stopping all processes",w);let $=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,w).catch((A)=>{H.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled($),this.processes.clear(),this.isShuttingDown=!1}isRunning(w){let $=this.processes.get(w);return!!$?.process&&!$.process.killed}}var g8=new m8;g$();k$();import{execSync as VR}from"node:child_process";import*as a8 from"node:http";import*as LG from"node:net";import*as SG from"node:os";import*as OG from"node:path";import*as t from"node:process";var d8=(w,$)=>(Y)=>`\x1B[${w}m${Y}\x1B[${$}m`,hw={bold:d8(1,22),dim:d8(2,22),green:d8(32,39),cyan:d8(36,39)};xA();x8();k$();g$();f0();import*as yG from"node:fs";import*as IG from"node:path";import*as _w from"node:process";function RR(w,$){let A=($&&$!=="/"?`${w}${$}`:w).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function cQ(w){if(w.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let $=w.verbose??!1,Y=w.registryDir,A=new Set,X=w.proxies.map((z)=>{let G=z.id??RR(z.to,z.path);if(!C$(G))throw Error(`invalid registry id "${G}" derived from to="${z.to}"`);if(A.has(G))throw Error(`duplicate registry id "${G}" — set an explicit \`id\` on one of the proxies`);return A.add(G),{...z,id:G}}),J=new Date().toISOString();for(let z of X)await v1({id:z.id,from:z.from,to:z.to,path:z.path,pid:w.persistent?void 0:_w.pid,cwd:_w.cwd(),createdAt:J,cleanUrls:z.cleanUrls,changeOrigin:z.changeOrigin,pathRewrites:z.pathRewrites,static:z.static,loadBalancer:z.loadBalancer},Y,$);let U=await v8({rpxDir:w.rpxDir,verbose:$,spawnCommand:w.spawnCommand,startupTimeoutMs:w.startupTimeoutMs,spawnEnv:w.spawnEnv});for(let z of X){let G=z.static?`static ${typeof z.static==="string"?z.static:z.static.dir}`:z.from;H.success(`https://${z.to} → ${G}`)}if(H.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),w.detached)return;let Q=!1,W=Y??$w(),j=X.map((z)=>z.id),B=async()=>{if(Q)return;Q=!0;for(let z of j)await m$(z,Y,$).catch((G)=>{E("runner",`removeEntry(${z}) failed: ${G}`,$)})},f=(z)=>{E("runner",`received ${z}, unregistering ${j.length} entries`,$),B().finally(()=>_w.exit(0))};_w.once("SIGINT",f),_w.once("SIGTERM",f),_w.once("exit",()=>{if(Q)return;for(let z of j)try{yG.unlinkSync(IG.join(W,`${z}.json`))}catch{}}),await new Promise(()=>{})}SQ();jQ();NQ();import{timingSafeEqual as MR}from"node:crypto";function yR(w,$){if(w==null)return!1;let Y=Buffer.from(w),A=Buffer.from($);if(Y.length!==A.length)return!1;return MR(Y,A)}function n8(w){return w.toLowerCase().replace(/\.$/,"")}var IR=["/.well-known/acme-challenge/"];function CR(w){let $=w.headers.get("host");if($)return n8($.split(":")[0]);try{return n8(new URL(w.url).hostname)}catch{return""}}function CG(w){let $=w.header.toLowerCase(),Y=new Set,A=[];for(let W of w.hosts){let j=n8(W);if(j.startsWith("*."))A.push(j);else Y.add(j)}let X=w.exemptPaths??IR,J=w.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
336
+ `,U=(W)=>{let j=n8(W);return Y.has(j)||A.some((B)=>$Y(j,B))},Q=(W)=>{let j=CR(W);if(!U(j))return;let B="/";try{B=new URL(W.url).pathname}catch{}if(X.some((f)=>B.startsWith(f)))return;if(yR(W.headers.get($),w.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return Q.protects=U,Q}zQ();GQ();K8();R8();FQ();TQ();N8();f0();var p8=new m8,LR="0.12.0",SR=new I8("0.0.0.0"),dY=new Set,t8=new Set,mQ=!1,l8=null,gQ=null;async function s8(w){if(mQ)return E("cleanup","Cleanup already in progress, skipping",w?.verbose),gQ||Promise.resolve();mQ=!0,E("cleanup","Starting cleanup process",w?.verbose),gQ=new Promise(($)=>{l8=$});try{await p8.stopAll(w?.verbose),H.info("Shutting down proxy servers...");let $=[],Y=Array.from(dY).map((A)=>new Promise((X)=>{let J=A;try{if(typeof J.stop==="function")J.stop(!0),E("cleanup","Bun server stopped",w?.verbose),X();else if(typeof J.close==="function")J.close(()=>{E("cleanup","Server closed successfully",w?.verbose),X()});else X()}catch(U){E("cleanup",`Error stopping server: ${U}`,w?.verbose),X()}}));$.push(...Y),dY.clear();for(let A of t8)b1(A);if(t8.clear(),w?.hosts&&w.domains?.length){E("cleanup","Cleaning up hosts file entries",w?.verbose),E("cleanup",`Original domains for cleanup: ${JSON.stringify(w.domains)}`,w?.verbose);let A=w.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(E("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,w?.verbose),A.length>0)H.info("Cleaning up hosts file entries..."),$.push(t2(A,w?.verbose).then(()=>{E("cleanup",`Removed hosts entries for ${A.join(", ")}`,w?.verbose)}).catch((X)=>{E("cleanup",`Failed to remove hosts entries: ${X}`,w?.verbose),H.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,X)}))}if(w?.certs&&w.domains?.length){E("cleanup","Cleaning up SSL certificates",w?.verbose),H.info("Cleaning up SSL certificates...");let A=w.domains.map(async(X)=>{try{await j2(X,w?.verbose),E("cleanup",`Removed certificates for ${X}`,w?.verbose)}catch(J){E("cleanup",`Failed to remove certificates for ${X}: ${J}`,w?.verbose),H.warn(`Failed to clean up certificates for ${X}:`,J)}});$.push(...A)}await Promise.allSettled($),E("cleanup","All cleanup tasks completed successfully",w?.verbose),H.success("All cleanup tasks completed successfully")}catch($){E("cleanup",`Error during cleanup: ${$}`,w?.verbose),H.error("Error during cleanup:",$)}finally{if(l8)l8();l8=null,mQ=!1;let $=w&&"vitePluginUsage"in w&&w.vitePluginUsage===!0;if(t.env.NODE_ENV!=="test"&&t.env.BUN_ENV!=="test"&&!$)t.exit(0)}return gQ}var dQ=!1;function hG(w){if(dQ){E("signal",`Received second ${w} signal, forcing exit`,!0),t.exit(1);return}dQ=!0,E("signal",`Received ${w} signal, initiating cleanup`,!0),s8().catch(($)=>{E("signal",`Cleanup failed after ${w}: ${$}`,!0),t.exit(1)}).finally(()=>{dQ=!1})}t.once("SIGINT",()=>hG("SIGINT"));t.once("SIGTERM",()=>hG("SIGTERM"));t.on("uncaughtException",(w)=>{H.error("Uncaught exception (continuing):",w)});t.on("unhandledRejection",(w)=>{H.error("Unhandled rejection (continuing):",w)});async function nY(w,$,Y,A=5){E("connection",`Testing connection to ${w}:${$} (retries left: ${A})`,Y);let X=15000,J=Date.now();if(t.env.RPX_BYPASS_CONNECTION_TEST==="true"){E("connection",`Bypassing connection test for ${w}:${$} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let U=()=>new Promise((Q,W)=>{let j=LG.connect({host:w,port:$,timeout:3000});j.once("connect",()=>{E("connection",`Successfully connected to ${w}:${$}`,Y),j.end(),Q()}),j.once("timeout",()=>{E("connection",`Connection to ${w}:${$} timed out`,Y),j.destroy(),W(Error("Connection timed out"))}),j.once("error",(B)=>{E("connection",`Failed to connect to ${w}:${$}: ${B}`,Y),j.destroy(),W(B)})});try{await U()}catch(Q){let W=Q;if(Date.now()-J>X){E("connection",`Connection test timed out after ${X}ms, but continuing anyway`,Y),H.warn(`Connection test to ${w}:${$} timed out, but RPX will try to proceed anyway.`);return}if(W.code==="ECONNREFUSED"&&A>0)return E("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((B)=>setTimeout(B,2000)),nY(w,$,Y,A-1);if(A>0)try{E("connection",`Trying HTTP request to ${w}:${$}`,Y),await new Promise((B,f)=>{let z=a8.request({hostname:w,port:$,path:"/",method:"HEAD",timeout:5000},(G)=>{E("connection",`Received HTTP response with status: ${G.statusCode}`,Y),B()});z.on("error",(G)=>f(G)),z.on("timeout",()=>{z.destroy(),f(Error("HTTP request timed out"))}),z.end()}),E("connection",`HTTP request to ${w}:${$} succeeded`,Y);return}catch(B){return E("connection",`HTTP request to ${w}:${$} failed: ${B}`,Y),E("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((f)=>setTimeout(f,2000)),nY(w,$,Y,A-1)}let j=`Failed to connect to ${w}:${$} after ${5-A} attempts: ${W.message}`;E("connection",`${j}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),H.warn(j),H.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function _G(w){E("server",`Starting server with options: ${A$(w)}`,w.verbose);let $=u$(w.from),Y=new URL($.startsWith("http")?$:`http://${$}`),A=new URL((w.to?.startsWith("http")?w.to:`http://${w.to}`)||"rpx.localhost"),X=Number.parseInt(Y.port)||(Y.protocol.includes("https:")?443:80),J=[A.hostname];if(nQ(w)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){E("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,w?.verbose);try{if(!(await uY(J,w.verbose))[0]){H.info(`Adding ${A.hostname} to hosts file...`),H.info("This may require sudo/administrator privileges");try{await bY(J,w.verbose)}catch(W){if(H.error("Failed to add hosts entry:",W.message),H.warn("You can manually add this entry to your hosts file:"),H.warn(`127.0.0.1 ${A.hostname}`),H.warn(`::1 ${A.hostname}`),t.platform==="win32")H.warn("On Windows:"),H.warn("1. Run notepad as administrator"),H.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else H.warn("On Unix systems:"),H.warn("sudo nano /etc/hosts")}}else E("hosts",`Host entry already exists for ${A.hostname}`,w.verbose)}catch(Q){H.error("Failed to check hosts file:",Q.message)}}try{await nY(Y.hostname,X,w.verbose)}catch(Q){E("server",`Connection test failed: ${Q}`,w.verbose),H.error(Q.message),H.warn("Continuing with proxy setup despite connection test failure..."),H.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let U=w._cachedSSLConfig||null;if(w.https)try{if(w.https===!0)w.https=RY({...w,to:A.hostname});if(U=await y$({...w,to:A.hostname,https:w.https}),!U){if(E("ssl",`Generating new certificates for ${A.hostname}`,w.verbose),await HY({...w,from:Y.toString(),to:A.hostname,https:w.https}),U=await y$({...w,to:A.hostname,https:w.https}),!U)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(Q){throw E("server",`SSL setup failed: ${Q}`,w.verbose),Q}E("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,w.verbose),await hR({...w,from:$,originalFrom:w.from||$,to:A.hostname,fromPort:X,sourceUrl:{hostname:Y.hostname,host:Y.host},ssl:U})}async function OR(w,$,Y,A,X,J,U,Q,W,j,B,f){E("proxy",`Creating proxy server ${w} -> ${$} with cleanUrls: ${Q}`,U);let z=MY(B??A.host,f);IY(z);let G=[{host:$,route:{sourceHost:A.host,upstreamPool:z,cleanUrls:Q||!1,changeOrigin:W||!1,basePath:"/",auth:j}}];if(!r8({routeEntries:G,listenPort:Y,sslConfig:X,originGuard:null,verbose:U??!1}))throw b1(z),Error(`Failed to start proxy server for ${$} on port ${Y}`);t8.add(z),DR({from:w,to:$,vitePluginUsage:J,listenPort:Y,ssl:!!X,cleanUrls:Q,verbose:U})}async function hR(w){E("setup",`Setting up reverse proxy: ${A$(w)}`,w.verbose);let{from:$,originalFrom:Y,to:A,sourceUrl:X,ssl:J,verbose:U,cleanup:Q,vitePluginUsage:W,changeOrigin:j,cleanUrls:B}=w,f=80,z=443,G="0.0.0.0",T=w.portManager||SR,K=nQ(w);try{if(K&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await uY([A],U))[0]){H.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await bY([A],U),H.success(`Added ${A} to your hosts file.`)}catch(V){H.error(`Failed to add ${A} to your hosts file: ${V}`),H.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(K&&t.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await uY([A],U))[0]){E("hosts",`${A} not found in hosts file, adding...`,U);try{await bY([A],U)}catch(V){E("hosts",`Failed to add ${A} to hosts file: ${V}`,U)}}}if(J&&!T.usedPorts.has(f)){if(!await I$(f,G,U))E("setup","Starting HTTP redirect server",U),DG(U),T.usedPorts.add(f);else if(E("setup","Port 80 is in use, skipping HTTP redirect",U),U)H.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let F=J?z:f,q=await I$(F,G,U),R;if(q){if(E("setup",`Port ${F} is already in use`,U),U)H.warn(`Port ${F} is already in use. This may be another instance of rpx or another service.`);if(F===443){if(R=await T.getNextAvailablePort(3443,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await T.getNextAvailablePort(F+1000,!0),E("setup",`Using port ${R} instead of ${F}`,U),U)H.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=F,T.usedPorts.add(R),E("setup",`Using standard ${F===443?"HTTPS":"HTTP"} port ${F} for ${A}`,U);await OR($,A,R,X,J,W,U,B,j,VY(w.auth),Y,w.loadBalancer)}catch(F){E("setup",`Setup failed: ${F}`,U),H.error(`Failed to setup reverse proxy: ${F.message}`),s8({domains:[A],hosts:typeof Q==="boolean"?Q:Q?.hosts,certs:typeof Q==="boolean"?Q:Q?.certs,verbose:U,vitePluginUsage:W})}}function DG(w,$=80,Y=443,A,X){E("redirect",`Starting HTTP redirect server on port ${$}`,w);let J=a8.createServer((U,Q)=>{let W=U.url?U.url.split("?",1)[0]:"";if(W.startsWith("/.well-known/acme-challenge/")){if(X){let z=X.challengeStore.handlePath(W);if(z!==void 0){E("redirect",`Serving on-demand ACME challenge ${W}`,w),Q.writeHead(200,{"content-type":"text/plain"}),Q.end(z);return}}if(A){let z=H8(A,W);if(z!=null){E("redirect",`Serving ACME challenge ${W}`,w),Q.writeHead(200,{"content-type":"text/plain"}),Q.end(z);return}}if(X){Q.writeHead(404,{"content-type":"text/plain"}),Q.end("challenge not found");return}}let j=U.headers.host||"",B=j.includes(":")?j.slice(0,j.indexOf(":")):j;if(X&&B&&!X.hasCert(B))X.ensureCert(B).catch(()=>{});let f=Y===443?B:`${B}:${Y}`;E("redirect",`Redirecting request from ${j}${U.url} to https://${f}`,w),Q.writeHead(301,{Location:`https://${f}${U.url}`}),Q.end()}).listen($);dY.add(J),E("redirect","HTTP redirect server started",w)}function kG(w){let $={...mw,...w};if(E("proxy",`Starting proxy with options: ${A$($)}`,$?.verbose),$.viaDaemon){if(!$.from||!$.to){H.error("viaDaemon mode requires both `from` and `to`");return}cQ({proxies:[{id:$.id,from:$.from,to:$.to,path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}],verbose:$.verbose}).catch((W)=>{H.error(`Failed to register with rpx daemon: ${W.message}`),t.exit(1)});return}let Y=$.to||"",A=Y.split(".").pop()?.toLowerCase()||"",X=t.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(A)&&$?.verbose)H.warn(`The .${A} TLD may not work reliably for local development`),H.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),H.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (gY(),Z8)).then(({setupDevelopmentDns:W})=>{W({domains:[Y],verbose:$.verbose}).then((j)=>{if(j)Promise.resolve().then(()=>{if($.verbose)if(U.includes(A))H.success(`DNS server started for .${A} domains`);else H.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else E("dns",`Could not start DNS server - ${Y} may not resolve in browser`,$.verbose)})}).catch((W)=>{E("dns",`Failed to start DNS server: ${W}`,$.verbose)});let Q={from:$.from,to:$.to,cleanUrls:$.cleanUrls,https:RY($),cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,changeOrigin:$.changeOrigin,verbose:$.verbose,regenerateUntrustedCerts:$.regenerateUntrustedCerts};E("proxy",`Server options: ${A$(Q)}`,$.verbose),_G(Q).catch((W)=>{E("proxy",`Failed to start proxy: ${W}`,$.verbose),H.error(`Failed to start proxy: ${W.message}`),s8({domains:[$.to],hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose})})}function _R(w){return w?.verbose||!1}function nQ(w){if(w?.hostsManagement===!1)return!1;let $=w?.cleanup;if($===!1)return!1;if($&&typeof $==="object"&&$.hosts===!1)return!1;return!0}async function ZG(w){let $={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if(w)$={...$,...w};let Y=_R($),A=nQ($);if(E("config",`Starting with config: ${A$($,2)}`,Y),E("config",`Is multi-proxy? ${"proxies"in $}`,Y),E("config",`Hosts management enabled? ${A}`,Y),$.viaDaemon){let M="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((C)=>({id:C.id,from:C.from,to:C.to,path:C.path,cleanUrls:C.cleanUrls??$.cleanUrls,changeOrigin:C.changeOrigin??$.changeOrigin,pathRewrites:C.pathRewrites})):[{id:$.id,from:$.from,to:$.to??"rpx.localhost",path:$.path,cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin,pathRewrites:$.pathRewrites}];await cQ({proxies:M,verbose:Y});return}if("proxies"in $&&Array.isArray($.proxies)){E("servers",`Found ${$.proxies.length} proxies in config`,Y);for(let N of $.proxies)if(N.start){let M=`${N.from}-${N.to}`;try{E("watch",`Starting command for ${M} with command: ${N.start.command}`,Y),H.info(`Starting command for ${M}...`),await p8.startProcess(M,N.start,Y);let C=u$(N.from),h=new URL(C.startsWith("http")?C:`http://${C}`),J0=h.hostname||"localhost",u0=Number(h.port)||80;try{await nY(J0,u0,Y),E("watch",`Dev server is ready at ${J0}:${u0}`,Y)}catch(Gw){E("watch",`Connection check failed, but continuing with proxy setup: ${Gw}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(C){throw E("watch",`Failed to start command for ${M}: ${C}`,Y),Error(`Failed to start command for ${M}: ${C}`)}}else E("watch",`No start command for proxy ${N.from} -> ${N.to}`,Y)}else if("start"in $&&$.start){E("watch","Found start command in single proxy config",Y);let N=`${$.from}-${$.to}`;try{if($.start)E("watch",`Starting command: ${$.start.command}`,Y),await p8.startProcess(N,$.start,Y);let M=u$($.from),C=new URL(M.startsWith("http")?M:`http://${M}`),h=C.hostname||"localhost",J0=Number(C.port)||80;try{await nY(h,J0,Y),E("watch",`Dev server is ready at ${h}:${J0}`,Y)}catch(u0){E("watch",`Connection check failed, but continuing with proxy setup: ${u0}`,Y),H.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(M){throw E("watch",`Failed to run start command: ${M}`,Y),Error(`Failed to run start command: ${M}`)}}else E("watch","No start command found in config",Y);let X="proxies"in $&&Array.isArray($.proxies)?$.proxies[0]?.to:("to"in $)?$.to:"rpx.localhost";if(t.platform!=="win32"&&($.https||A)){if(!T$())try{E("sudo","Pre-acquiring sudo credentials for privileged operations",Y),VR("sudo -v",{stdio:"inherit"})}catch{E("sudo","Could not pre-acquire sudo credentials",Y)}}let J=[];if($.productionCerts){if(J=await kY($.productionCerts,Y),J.length>0)E("ssl",`Using ${J.length} production SNI cert(s): ${J.map((N)=>N.serverName).join(", ")}`,Y)}if($.https){let N=J.length>0?null:await y$($);if(!N&&J.length===0){if(E("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,$.verbose),await HY($),N=await y$($),!N)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else E("ssl",`Using existing and trusted certificates for ${X}`,$.verbose);$._cachedSSLConfig=N}let U="proxies"in $&&Array.isArray($.proxies)?$.proxies.map((N)=>({...N,https:$.https,cleanup:$.cleanup,cleanUrls:N.cleanUrls??("cleanUrls"in $?$.cleanUrls:!1),vitePluginUsage:$.vitePluginUsage,changeOrigin:N.changeOrigin??$.changeOrigin,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig})):[{from:"from"in $?$.from:"localhost:5173",to:"to"in $?$.to:"rpx.localhost",cleanUrls:"cleanUrls"in $?$.cleanUrls:!1,https:$.https,cleanup:$.cleanup,vitePluginUsage:$.vitePluginUsage,start:"start"in $?$.start:void 0,changeOrigin:$.changeOrigin,auth:"auth"in $?$.auth:void 0,verbose:Y,_cachedSSLConfig:$._cachedSSLConfig}],Q=U.map((N)=>N.to||"rpx.localhost"),W=J.length>0?J:$._cachedSSLConfig??null,j=Q.filter((N)=>N&&!N.includes("localhost")&&!N.includes("127.0.0.1")),B=["dev","app","page","new","day","foo"],f=["test","localhost","local","example","invalid"],z=[...new Set(j.map((N)=>N.split(".").pop()?.toLowerCase()))],G=z.filter((N)=>!!N&&B.includes(N));if(G.length>0&&Y)H.warn(`The following TLDs may not work reliably for local development: ${G.map((N)=>`.${N}`).join(", ")}`),H.info(" These TLDs have HSTS preloading which can bypass local DNS"),H.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&t.platform==="darwin"&&j.length>0){let{setupDevelopmentDns:N}=await Promise.resolve().then(() => (gY(),Z8));if(await N({domains:j,verbose:Y})){if(Y)if(z.every((h)=>!!h&&f.includes(h)))H.success(`DNS server started for ${z.map((h)=>`.${h}`).join(", ")} domains`);else H.success(`DNS server started for ${z.map((h)=>`.${h}`).join(", ")} domains (hosts file entries also added)`)}else E("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{E("cleanup","Starting cleanup handler",$.verbose);try{let{tearDownDevelopmentDns:N}=await Promise.resolve().then(() => (gY(),Z8));await N({verbose:$.verbose})}catch(N){E("cleanup",`Error stopping DNS server: ${N}`,$.verbose)}try{await p8.stopAll($.verbose)}catch(N){E("cleanup",`Error stopping processes: ${N}`,$.verbose)}await s8({domains:Q,hosts:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.hosts,certs:typeof $.cleanup==="boolean"?$.cleanup:$.cleanup?.certs,verbose:$.verbose||!1})};t.on("SIGINT",T),t.on("SIGTERM",T);let K=$.singlePortMode===!0,F=$.httpsPort??443,q=$.httpPort??80,R=$.originGuard?CG($.originGuard):null,L=!!W&&(U.length>1||K||J.length>0),V=!W&&K&&U.length>0;if(L&&W){E("proxies",`Creating shared HTTPS server for ${U.length} domains on port ${F}`,Y);let N=await VG(U,A,Y),M=null,C=$.onDemandTls,h=C?.enabled?new u1({config:C,certsDir:C.certsDir??$.productionCerts?.certsDir??OG.join(SG.homedir(),".stacks","rpx","on-demand-certs"),initial:J,verbose:Y,onCertAdded:(Ew)=>{if(ZY()==="restart")E("on-demand","certificate installed; restarting supervised gateway to reload TLS",Y),setTimeout(()=>t.kill(t.pid,"SIGTERM"),10).unref();else Gw(Ew)}}):null,J0=null,u0=!1;async function Gw(Ew){if(J0=Ew,u0)return;u0=!0;try{while(J0){let Zw=J0;if(J0=null,E("proxies",`rebuilding :${F} with ${Zw.length} SNI cert(s)`,Y),M)dY.delete(M),M.stop(!1);let t0=!1;for(let _=0;!t0&&_<60;_++){let Cw=r8({routeEntries:N,listenPort:F,sslConfig:Zw,originGuard:R,verbose:Y});if(Cw){M=Cw,t0=!0;break}await new Promise((n1)=>setTimeout(n1,Math.min(25*2**Math.min(_,4),500)))}if(!t0)H.error(`rpx: CRITICAL — could not rebind :${F} after cert issuance; HTTPS unbound until the next cert event or a gateway restart`)}}finally{u0=!1}}if(!await I$(q,"0.0.0.0",Y))DG(Y,q,F,$.acmeChallengeWebroot,h);if(await I$(F,"0.0.0.0",Y)){if(E("proxies",`Port ${F} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${F} is in use. Shared HTTPS proxy cannot start.`);return}let kw=h&&h.sniEntries().length>0?h.sniEntries():W;if(M=r8({routeEntries:N,listenPort:F,sslConfig:kw,originGuard:R,verbose:Y}),!M){H.error(`Shared HTTPS proxy failed to bind :${F}; not exiting`);return}}else if(V){E("proxies",`Creating shared HTTP server for ${U.length} domains on port ${q}`,Y);let N=await VG(U,A,Y);if(await I$(q,"0.0.0.0",Y)){if(E("proxies",`Port ${q} is already in use, cannot start shared proxy`,Y),Y)H.warn(`Port ${q} is in use. Shared HTTP proxy cannot start.`);return}if(!r8({routeEntries:N,listenPort:q,sslConfig:null,originGuard:R,verbose:Y})){H.error(`Shared HTTP proxy failed to bind :${q}; not exiting`);return}}else for(let N of U)try{let M=N.to||"rpx.localhost";E("proxy",`Starting proxy for ${M} with SSL config: ${!!W}`,N.verbose),await _G({from:N.from||"localhost:5173",to:M,cleanUrls:N.cleanUrls||!1,https:N.https||!1,cleanup:N.cleanup||!1,vitePluginUsage:N.vitePluginUsage||!1,verbose:N.verbose||!1,_cachedSSLConfig:$._cachedSSLConfig,changeOrigin:N.changeOrigin||!1,loadBalancer:N.loadBalancer,auth:N.auth,path:N.path,pathRewrites:N.pathRewrites})}catch(M){E("proxies",`Failed to start proxy for ${N.to}: ${M}`,N.verbose),H.error(`Failed to start proxy for ${N.to}:`,M)}}async function VG(w,$,Y){let A=[],X=new Set;for(let J of w){let U=J.to||"rpx.localhost",Q=J.cleanUrls||!1,W=J.path,j=X$(W),B=VY(J.auth);if(J.redirect){let f=C2(J.redirect);A.push({host:U,path:W,route:{redirect:f,basePath:j,auth:B}}),E("proxies",`Route: ${U}${W??""} → redirect ${f.status} ${f.to}${B?" (auth)":""}`,Y)}else if(J.static)A.push({host:U,path:W,route:{static:q8(J.static,Q),cleanUrls:Q,basePath:j,auth:B}}),E("proxies",`Route: ${U}${W??""} → static ${typeof J.static==="string"?J.static:J.static.dir}${B?" (auth)":""}`,Y);else{let f=u$(J.from),z=new URL(f.startsWith("http")?f:`http://${f}`),G=MY(J.from??z.host,J.loadBalancer);IY(G),t8.add(G),A.push({host:U,path:W,route:{sourceHost:z.host,upstreamPool:G,cleanUrls:Q,changeOrigin:J.changeOrigin||!1,pathRewrites:J.pathRewrites,basePath:j,auth:B}}),E("proxies",`Route: ${U}${W??""} → ${z.host}${B?" (auth)":""}`,Y)}if(X.has(U))continue;if(X.add(U),$&&!Q1(U)&&!U.includes("localhost")&&!U.includes("127.0.0.1"))try{if(!(await uY([U],Y))[0])await bY([U],Y)}catch{E("hosts",`Could not add hosts entry for ${U}`,Y)}}return A}function r8(w){let{routeEntries:$,listenPort:Y,sslConfig:A,originGuard:X,verbose:J}=w,U=hY($),Q=SY((B,f)=>_Y(U,B,f),J),W=X?(B,f)=>X(B)??Q(B,f):Q,j=OY(J);try{let B=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:qY(),...A?{tls:c$(Array.isArray(A)?A.map((f)=>({serverName:f.serverName,key:f.key,cert:f.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1})}:{},fetch(f,z){return W(f,z)},websocket:j,error(f){return E("server",`Shared proxy server error: ${f}`,J),new Response(`Server Error: ${f.message}`,{status:500})}});return dY.add(B),E("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${U.size} domains`,J),B}catch(B){return E("proxies",`Failed to start shared proxy: ${B}`,J),console.error("Failed to start shared proxy:",B),null}}function DR(w){if(w?.vitePluginUsage||!w?.verbose)return;if(console.log(""),console.log(` ${hw.green(hw.bold("rpx"))} ${hw.green(`v${LR}`)}`),console.log(` ${hw.green("➜")} ${hw.dim(w?.from??"")} ${hw.dim("➜")} ${hw.cyan(w?.ssl?`https://${w?.to}`:`http://${w?.to}`)}`),w?.listenPort!==(w?.ssl?443:80))console.log(` ${hw.green("➜")} Listening on port ${w?.listenPort}`);if(w?.cleanUrls)console.log(` ${hw.green("➜")} Clean URLs enabled`)}f0();P0.chdir(ZR(kR(xR(import.meta.url)),".."));var b0=new jJ("rpx"),xG="0.12.0";b0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async(w)=>{if(!w?.from||!w.to)return ZG(mw);let $={from:w.from,to:w.to,https:{keyPath:w.keyPath,certPath:w.certPath,caCertPath:w.caCertPath},cleanup:{certs:w.certsCleanup||!1,hosts:w.hostsCleanup||!1},verbose:w.verbose||!1,changeOrigin:w.changeOrigin||!1,singlePortMode:w.singlePortMode||!1,httpPort:w.httpPort!==void 0?Number(w.httpPort):void 0,httpsPort:w.httpsPort!==void 0?Number(w.httpsPort):void 0,viaDaemon:w.viaDaemon||!1,id:w.id};if(w.startCommand){let Y={command:w.startCommand};if(w.startCwd)Y.cwd=w.startCwd;if(w.startEnv)try{Y.env=JSON.parse(w.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),P0.exit(1)}$.start=Y}return kG($)});b0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{let Y=B8(mw)?mw.proxies.find((A)=>A.to===w||`${A.from}-${A.to}`===w):mw.to===w?mw:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${w}`),P0.exit(1);try{await g8.startProcess(w,Y.start,$.verbose),console.log(`Started dev server for ${w}`)}catch(A){console.error(`Failed to start dev server for ${w}:`,A),P0.exit(1)}});b0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async(w,$)=>{try{await g8.stopProcess(w,$.verbose),console.log(`Stopped dev server for ${w}`)}catch(Y){console.error(`Failed to stop dev server for ${w}:`,Y),P0.exit(1)}});b0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async(w)=>{try{await g8.stopAll(w.verbose),console.log("Stopped all dev servers")}catch($){console.error("Failed to stop all dev servers:",$),P0.exit(1)}});async function PG(w){let Y={...(await xB().catch(()=>null))?.onDemand??{},enabled:!0};if(w){let A=w.split(",").map((X)=>X.trim()).filter(Boolean);if(A.length>0)Y.roots=A}return Y}b0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--on-demand","Lazily boot a project's dev server the first time its host is visited (reads config `onDemand`)").option("--roots <dirs>","Comma-separated roots scanned for on-demand sites (overrides config; default ~/Code)").option("--verbose","Enable verbose logging").example("rpx daemon:start --on-demand").example("rpx daemon:start --on-demand --roots ~/Code,~/work").action(async(w)=>{try{let $=w.onDemand?await PG(w.roots):void 0;await(await HG({rpxDir:w.rpxDir,registryDir:w.registryDir,httpsPort:typeof w.httpsPort==="string"?Number.parseInt(w.httpsPort,10):w.httpsPort,httpPort:typeof w.httpPort==="string"?Number.parseInt(w.httpPort,10):w.httpPort,hostname:w.hostname,productionCerts:w.certsDir?{certsDir:w.certsDir}:void 0,workers:w.workers===void 0?void 0:typeof w.workers==="string"?Number.parseInt(w.workers,10):w.workers,onDemandSites:$,verbose:w.verbose??!0})).done,P0.exit(0)}catch($){console.error(`Failed to start rpx daemon: ${$.message}`),P0.exit(1)}});b0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async(w)=>{let $=typeof w.timeout==="string"?Number.parseInt(w.timeout,10):w.timeout,Y=await RG({rpxDir:w.rpxDir,timeoutMs:$,forceAfterTimeout:w.force!==!1,verbose:w.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});b0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async(w)=>{let $=w.rpxDir??V0(),Y=await L$($),A=await u8($),X=w.registryDir,J=await zw(X).catch(()=>[]);if(w.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:S$($),rpxDir:$,registryDir:X??$w(),entries:J},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${S$($)} → pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${S$($)}`);if(console.log(`registry: ${X??$w()}`),J.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${J.length}):`);for(let U of J){let Q=U.pid!==void 0?`, pid=${U.pid}`:"";console.log(` https://${U.to} → ${U.from} (id=${U.id}${Q})`)}});b0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async(w)=>{if(!w.id||!w.from||!w.to)console.error("rpx register requires --id, --from, and --to"),P0.exit(1);if(!C$(w.id))console.error(`invalid id: ${JSON.stringify(w.id)} (must match /^[a-zA-Z0-9._-]+$/, ≤128 chars)`),P0.exit(1);try{await v1({id:w.id,from:w.from,to:w.to,cwd:w.cwd,createdAt:new Date().toISOString(),cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin},w.registryDir,w.verbose)}catch($){console.error(`failed to write registry entry: ${$.message}`),P0.exit(1)}if(w.skipSpawn){console.log(`registered ${w.to} → ${w.from} (daemon spawn skipped)`);return}try{let $=await v8({rpxDir:w.rpxDir,verbose:w.verbose}),Y=$.spawned?"spawned":"attached to";console.log(`registered https://${w.to} → ${w.from} (${Y} daemon pid=${$.pid})`)}catch($){console.error(`registered entry but daemon spawn failed: ${$.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),P0.exit(1)}});b0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async(w,$)=>{if(!C$(w))console.error(`invalid id: ${JSON.stringify(w)}`),P0.exit(1);let Y=await MQ(w,$.registryDir,$.verbose);if(!Y){console.log(`no registry entry for id=${w}`);return}await m$(w,$.registryDir,$.verbose),console.log(`unregistered ${Y.to} (id=${w})`)});b0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async(w)=>{let $=w.rpxDir??V0();if(await u8($)){console.log("rpx daemon is running — DNS overrides are managed by the daemon");return}await MG({rpxDir:$,verbose:w.verbose}),console.log("DNS reconcile complete")});b0.command("sites","List the on-demand sites rpx can boot (and which are currently live)").option("--roots <dirs>","Comma-separated roots to scan (overrides config; default ~/Code)").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--json","Emit machine-readable JSON").action(async(w)=>{let $=await PG(w.roots),Y=cB($),A=await zw(w.registryDir).catch(()=>[]),X=new Set(A.map((Q)=>Q.to)),J=Y.map((Q)=>({host:Q.host,dir:Q.dir,command:Q.command,source:Q.source,live:X.has(Q.host)}));if(w.json){console.log(JSON.stringify(J,null,2));return}let U=$.roots??["~/Code"];if(J.length===0){console.log("no on-demand sites found"),console.log(`scanned roots: ${U.join(", ")}`),console.log("start the daemon with `rpx daemon:start --on-demand` to serve them");return}console.log(`on-demand sites (${J.length}) — scanned ${U.join(", ")}:`);for(let Q of J)console.log(` ${Q.live?"●":"○"} https://${Q.host} ${Q.live?"(live)":"(idle)"}`),console.log(` ${Q.command} ${Q.dir}`)});b0.command("logs <host>","Show an on-demand site's boot log (e.g. rpx logs myapp.localhost)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--lines <n>","Show only the last N lines (default: all)").action(async(w,$)=>{let{readFile:Y}=await import("node:fs/promises"),{join:A}=await import("node:path"),X=$.rpxDir??V0(),J=A(X,"sites",`${PA(w.split(":")[0])}.log`),U;try{U=await Y(J,"utf8")}catch{console.log(`no log for ${w} (it may not have been booted yet) — looked in ${J}`);return}let Q=$.lines===void 0?void 0:typeof $.lines==="string"?Number.parseInt($.lines,10):$.lines,W=U.split(`
337
+ `);P0.stdout.write((Q&&Q>0?W.slice(-Q):W).join(`
338
+ `))});b0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(xG)});b0.version(xG);b0.help();b0.run();