@stacksjs/rpx 0.11.19 → 0.11.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/cli.js CHANGED
@@ -1,268 +1,270 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
3
  #!/usr/bin/env bun
4
- import{createRequire as SF}from"node:module";var LF=Object.defineProperty;var OF=($)=>$;function QF($,w){this[$]=OF.bind(null,w)}var BW=($,w)=>{for(var A in w)LF($,A,{get:w[A],enumerable:!0,configurable:!0,set:QF.bind(w,A)})};var F0=($,w)=>()=>($&&(w=$($=0)),w);var m=SF(import.meta.url);import{existsSync as hW,statSync as VW}from"fs";import{existsSync as xE,mkdirSync as _q,readdirSync as kq,readFileSync as PE,writeFileSync as Dq}from"fs";import{homedir as iw}from"os";import{dirname as Pq,resolve as J$}from"path";import HY from"process";import{existsSync as LW,statSync as OW}from"fs";import{existsSync as r8,mkdirSync as bE,readdirSync as uE,writeFileSync as iE}from"fs";import{homedir as cw}from"os";import{dirname as QW,resolve as i0}from"path";import Cw from"process";import{join as cE,relative as vE,resolve as SW}from"path";import XY from"process";import{existsSync as EB,mkdirSync as lq,readdirSync as pq,writeFileSync as tq}from"fs";import{homedir as S8}from"os";import{dirname as sq,resolve as u0}from"path";import l1 from"process";import{join as mE,relative as dE,resolve as _W}from"path";import JY from"process";import{existsSync as GB,mkdirSync as AM,readdirSync as YM,writeFileSync as XM}from"fs";import{dirname as UM,resolve as UY}from"path";import a8 from"process";import{Buffer as Jw}from"buffer";import{createCipheriv as gE,createDecipheriv as nE,randomBytes as _8}from"crypto";import{closeSync as k8,createReadStream as kW,createWriteStream as lE,existsSync as D8,fsyncSync as DW,openSync as ZW,writeFileSync as pE}from"fs";import{access as tE,constants as xW,mkdir as rE,readdir as uA,rename as PW,stat as vw,unlink as iA,writeFile as Z8}from"fs/promises";import{join as mw}from"path";import O0 from"process";import{pipeline as aE}from"stream/promises";import{createGzip as bW}from"zlib";import dw from"process";import k$ from"process";import{Buffer as Q$}from"buffer";import{createCipheriv as sE,createDecipheriv as oE,randomBytes as x8}from"crypto";import{closeSync as P8,createReadStream as uW,createWriteStream as eE,existsSync as cA,fsyncSync as iW,openSync as cW,writeFileSync as $5}from"fs";import{access as w5,constants as vW,mkdir as A5,readdir as vA,rename as mW,stat as gw,unlink as mA,writeFile as b8}from"fs/promises";import{isAbsolute as Y5,join as nw,resolve as X5}from"path";import k from"process";import{pipeline as J5}from"stream/promises";import{createGzip as dW}from"zlib";import lw from"process";import D$ from"process";import dA from"process";import{existsSync as gA}from"fs";import{resolve as u8}from"path";import{existsSync as U5}from"fs";import{existsSync as f5,readdirSync as W5}from"fs";import{extname as i8,resolve as gW}from"path";import B5 from"process";import{join as j5,relative as z5,resolve as nW}from"path";import fY from"process";import{Buffer as S$}from"buffer";import{createCipheriv as F5,createDecipheriv as E5,randomBytes as c8}from"crypto";import{closeSync as v8,createReadStream as lW,createWriteStream as G5,existsSync as nA,fsyncSync as pW,openSync as tW,writeFileSync as K5}from"fs";import{access as T5,constants as rW,mkdir as H5,readdir as lA,rename as aW,stat as pw,unlink as pA,writeFile as m8}from"fs/promises";import{isAbsolute as N5,join as tw,resolve as R5}from"path";import D from"process";import{pipeline as q5}from"stream/promises";import{createGzip as sW}from"zlib";import rw from"process";import Z$ from"process";import rA from"process";import{existsSync as aA}from"fs";import{resolve as t8}from"path";import{existsSync as cG}from"fs";class zB{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!hW($))return!0;return VW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=hW(A)?VW(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class FB{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function y5($,w){this[$]=I5.bind(null,w)}class WJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!LW($))return!0;return OW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=LW(A)?OW(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class BJ{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function V5($,w={}){let Y=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return Y?`${$}:${Y}`:$}function L5($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function O5($){return $.getStats().size*2}function jJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&o(w[0])&&"id"in w[0]&&w[0].id===3&&o(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(o(w)&&o($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(o($)&&"arr"in $&&Array.isArray($.arr)&&o(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&o(w[0])&&o($[0])){let Y=[...w];for(let X of $)if(o(X)&&"name"in X){if(!Y.find((U)=>o(U)&&("name"in U)&&U.name===X.name))Y.push(X)}else if(o(X)&&"path"in X){if(!Y.find((U)=>o(U)&&("path"in U)&&U.path===X.path))Y.push(X)}else if(!Y.some((J)=>WY(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!o(w)||!o($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(o(X)&&o(A[Y]))A[Y]=jJ(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&o(X[0])&&o(A[Y][0])){let J=[...X];for(let U of A[Y])if(o(U)&&"name"in U){if(!J.find((f)=>o(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(o(U)&&"path"in U){if(!J.find((f)=>o(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((W)=>WY(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function WY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!WY($[A],w[A]))return!1;return!0}if(o($)&&o(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!WY($[X],w[X]))return!1}return!0}return!1}function o($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function Q5($,w){if(!GB($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return jJ(w,Y)}catch{return null}}catch{return null}}async function S5({name:$="",cwd:w,defaultConfig:A}){let Y=w||a8.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let W of X){let f=UY(Y,`${U}${W}`),B=await Q5(f,A);if(B!==null)return B}try{let U=UY(Y,"package.json");if(GB(U)){let f=(await import(U))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return jJ(A,f)}catch{}}}catch{}return A}function _5($,w={}){let A=JY.cwd();while(A.includes("storage"))A=_W(A,"..");let Y=_W(A,$||"");if(w?.relative)return dE(JY.cwd(),Y);return Y}async function k5(){try{let $=await S5({name:"clarity",defaultConfig:eA,cwd:JY.cwd(),endpoint:"",headers:{}});return{...eA,...$}}catch{return eA}}function X0(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function D5(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof k$<"u"){let $=k$.type;if($==="renderer"||$==="worker")return!1;return!!(k$.versions&&(k$.versions.node||k$.versions.bun))}return!1}class TB{async format($){let w=await D5(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:dw.pid,hostname:w(),environment:dw.env.NODE_ENV||"development",platform:dw.platform,version:dw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:dw.env.NODE_ENV||dw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class BY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...o8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new TB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...$Y,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...$Y};return{...$Y,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:o8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await tE(this.config.logDirectory,xW.F_OK|xW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await rE(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Jw.from($);try{if(!D8(this.currentLogFile))await Z8(this.currentLogFile,"",{mode:420});if(X=ZW(this.currentLogFile,"a",420),pE(X,f,{flag:"a"}),DW(X),X!==void 0)k8(X),X=void 0;if((await vw(this.currentLogFile)).size===0){if(await Z8(this.currentLogFile,f,{flag:"w",mode:420}),(await vw(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 E=W*2**J;await new Promise((F)=>setTimeout(F,E)),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{k8(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 mw(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 mw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return mw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(X0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.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 _8(16).toString("hex")}generateKey(){return _8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=_8(16),Y=gE("aes-256-gcm",w,A),X=Jw.concat([Y.update($,"utf8"),Y.final()]),J=Y.getAuthTag();return{encrypted:Jw.concat([A,X,J]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=bW(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(Jw.from(Jw.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(X0())return;let $=await vw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await uA(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await vw(A).catch(()=>null))try{if(await PW(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await iA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await Z8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await vw(A).catch(()=>null))await PW(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await uA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await iA(mw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=kW($),Y=lE(w),X=bW();await aE(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),D8(this.currentLogFile))try{let $=ZW(this.currentLogFile,"r+");DW($),k8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!X0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await uA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await iA(mw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?t.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=O0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${t.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!X0()){let B=VB[$],j=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:t.gray(U),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:t.green(U),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z),W){let E=W.split(`
5
- `);for(let F of E)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:t.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!X0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let f=`${J} ${this.environment}.${$.toUpperCase()}: ${U}
4
+ import{createRequire as dF}from"node:module";var cF=Object.defineProperty;var vF=($)=>$;function mF($,w){this[$]=vF.bind(null,w)}var RW=($,w)=>{for(var Y in w)cF($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:mF.bind(w,Y)})};var j0=($,w)=>()=>($&&(w=$($=0)),w);var v=dF(import.meta.url);import{existsSync as PW,statSync as bW}from"fs";import{existsSync as t5,mkdirSync as eR,readdirSync as $M,readFileSync as r5,writeFileSync as wM}from"fs";import{homedir as uw}from"os";import{dirname as UM,resolve as w$}from"path";import RA from"process";import{existsSync as uW,statSync as iW}from"fs";import{existsSync as U8,mkdirSync as a5,readdirSync as s5,writeFileSync as o5}from"fs";import{homedir as iw}from"os";import{dirname as cW,resolve as u0}from"path";import Cw from"process";import{join as e5,relative as $G,resolve as vW}from"path";import fA from"process";import{existsSync as CB,mkdirSync as EM,readdirSync as KM,writeFileSync as TM}from"fs";import{homedir as iX}from"os";import{dirname as qM,resolve as b0}from"path";import a1 from"process";import{join as wG,relative as YG,resolve as mW}from"path";import WA from"process";import{existsSync as hB,mkdirSync as CM,readdirSync as hM,writeFileSync as VM}from"fs";import{dirname as QM,resolve as BA}from"path";import X8 from"process";import{Buffer as Xw}from"buffer";import{createCipheriv as AG,createDecipheriv as UG,randomBytes as cX}from"crypto";import{closeSync as vX,createReadStream as dW,createWriteStream as XG,existsSync as mX,fsyncSync as gW,openSync as lW,writeFileSync as JG}from"fs";import{access as fG,constants as nW,mkdir as WG,readdir as vY,rename as pW,stat as cw,unlink as mY,writeFile as dX}from"fs/promises";import{join as vw}from"path";import V0 from"process";import{pipeline as BG}from"stream/promises";import{createGzip as tW}from"zlib";import mw from"process";import k$ from"process";import{Buffer as O$}from"buffer";import{createCipheriv as jG,createDecipheriv as zG,randomBytes as gX}from"crypto";import{closeSync as lX,createReadStream as rW,createWriteStream as FG,existsSync as dY,fsyncSync as aW,openSync as sW,writeFileSync as GG}from"fs";import{access as EG,constants as oW,mkdir as KG,readdir as gY,rename as eW,stat as dw,unlink as lY,writeFile as nX}from"fs/promises";import{isAbsolute as TG,join as gw,resolve as HG}from"path";import _ from"process";import{pipeline as NG}from"stream/promises";import{createGzip as $B}from"zlib";import lw from"process";import D$ from"process";import nY from"process";import{existsSync as pY}from"fs";import{resolve as pX}from"path";import{existsSync as qG}from"fs";import{existsSync as RG,readdirSync as MG}from"fs";import{extname as tX,resolve as wB}from"path";import IG from"process";import{join as yG,relative as CG,resolve as YB}from"path";import jA from"process";import{Buffer as S$}from"buffer";import{createCipheriv as hG,createDecipheriv as VG,randomBytes as rX}from"crypto";import{closeSync as aX,createReadStream as AB,createWriteStream as LG,existsSync as tY,fsyncSync as UB,openSync as XB,writeFileSync as QG}from"fs";import{access as OG,constants as JB,mkdir as SG,readdir as rY,rename as fB,stat as nw,unlink as aY,writeFile as sX}from"fs/promises";import{isAbsolute as _G,join as pw,resolve as kG}from"path";import k from"process";import{pipeline as DG}from"stream/promises";import{createGzip as WB}from"zlib";import tw from"process";import Z$ from"process";import oY from"process";import{existsSync as eY}from"fs";import{resolve as A8}from"path";import{existsSync as e6}from"fs";class IB{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!PW($))return!0;return bW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=PW(Y)?bW(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class yB{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function PG($,w){this[$]=xG.bind(null,w)}class H8{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!uW($))return!0;return iW($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=uW(Y)?iW(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class N8{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function iG($,w={}){let A=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return A?`${$}:${A}`:$}function cG($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function vG($){return $.getStats().size*2}function q8($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&e(w[0])&&"id"in w[0]&&w[0].id===3&&e(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(e(w)&&e($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(e($)&&"arr"in $&&Array.isArray($.arr)&&e(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&e(w[0])&&e($[0])){let A=[...w];for(let U of $)if(e(U)&&"name"in U){if(!A.find((J)=>e(J)&&("name"in J)&&J.name===U.name))A.push(U)}else if(e(U)&&"path"in U){if(!A.find((J)=>e(J)&&("path"in J)&&J.path===U.path))A.push(U)}else if(!A.some((X)=>zA(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!e(w)||!e($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(e(U)&&e(Y[A]))Y[A]=q8(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&e(U[0])&&e(Y[A][0])){let X=[...U];for(let J of Y[A])if(e(J)&&"name"in J){if(!X.find((f)=>e(f)&&("name"in f)&&f.name===J.name))X.push(J)}else if(e(J)&&"path"in J){if(!X.find((f)=>e(f)&&("path"in f)&&f.path===J.path))X.push(J)}else if(!X.some((W)=>zA(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function zA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!zA($[Y],w[Y]))return!1;return!0}if(e($)&&e(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!zA($[U],w[U]))return!1}return!0}return!1}function e($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function mG($,w){if(!hB($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return q8(w,A)}catch{return null}}catch{return null}}async function dG({name:$="",cwd:w,defaultConfig:Y}){let A=w||X8.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let J of X)for(let W of U){let f=BA(A,`${J}${W}`),B=await mG(f,Y);if(B!==null)return B}try{let J=BA(A,"package.json");if(hB(J)){let f=(await import(J))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return q8(Y,f)}catch{}}}catch{}return Y}function gG($,w={}){let Y=WA.cwd();while(Y.includes("storage"))Y=mW(Y,"..");let A=mW(Y,$||"");if(w?.relative)return YG(WA.cwd(),A);return A}async function lG(){try{let $=await dG({name:"clarity",defaultConfig:YA,cwd:WA.cwd(),endpoint:"",headers:{}});return{...YA,...$}}catch{return YA}}function U0(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function nG(){if(k$.env.NODE_ENV==="test"||k$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof k$<"u"){let $=k$.type;if($==="renderer"||$==="worker")return!1;return!!(k$.versions&&(k$.versions.node||k$.versions.bun))}return!1}class LB{async format($){let w=await nG(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:mw.pid,hostname:w(),environment:mw.env.NODE_ENV||"development",platform:mw.platform,version:mw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:mw.env.NODE_ENV||mw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class FA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...f8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new LB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??V0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...AA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...AA};return{...AA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:f8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await fG(this.config.logDirectory,nW.F_OK|nW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await WG(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Xw.from($);try{if(!mX(this.currentLogFile))await dX(this.currentLogFile,"",{mode:420});if(U=lW(this.currentLogFile,"a",420),JG(U,f,{flag:"a"}),gW(U),U!==void 0)vX(U),U=void 0;if((await cw(this.currentLogFile)).size===0){if(await dX(this.currentLogFile,f,{flag:"w",mode:420}),(await cw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{vX(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return vw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return vw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return vw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return cX(16).toString("hex")}generateKey(){return cX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=cX(16),A=AG("aes-256-gcm",w,Y),U=Xw.concat([A.update($,"utf8"),A.final()]),X=A.getAuthTag();return{encrypted:Xw.concat([Y,U,X]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=tW(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(Xw.from(Xw.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(U0())return;let $=await cw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await vY(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await cw(Y).catch(()=>null))try{if(await pW(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await mY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await dX(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await cw(Y).catch(()=>null))await pW(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await vY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await mY(vw(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=dW($),A=XG(w),U=tW();await BG(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),mX(this.currentLogFile))try{let $=lW(this.currentLogFile,"r+");gW($),vX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await vY(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await mY(vw(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?r.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=V0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${r.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);if(this.fancy&&!U0()){let B=bB[$],j=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:r.gray(J),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:r.green(J),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z),W){let G=W.split(`
5
+ `);for(let F of G)if(F.trim()&&!F.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:r.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let f=`${X} ${this.environment}.${$.toUpperCase()}: ${J}
6
6
  `;if(W)f+=`${W}
7
- `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!X0()){let A=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:t.blue("◐"),tag:A,message:`${t.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),X=Math.round(Y-w),J=`${$} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
8
- `,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!X0()){let j=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:t.green("✓"),tag:j,message:`${J}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!X0())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new BY(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(X0())throw Error("createReadStream is not supported in browser environments");if(!D8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return kW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=Jw.isBuffer($)?$:Jw.from($,"base64"),X=Y.slice(0,16),J=Y.slice(-16),U=Y.slice(16,-16),W=nE("aes-256-gcm",A,X);return W.setAuthTag(J),Jw.concat([W.update(U),W.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return X0()}isServerMode(){return!X0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w);if(this.fancy&&!X0()){let J=$.split(`
9
- `),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,f=`└${"─".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:A,message:t.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:t.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:A,message:t.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:t.cyan(f),showTimestamp:!1}))}else if(!X0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let X=`${Y} ${this.environment}.INFO: [BOX] ${$}
10
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(X0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${t.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let X=Y.toString().trim().toLowerCase();O0.stdin.removeListener("data",A);try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!1)}catch{}O0.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!0)}catch{}O0.stdin.resume(),O0.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,W=0;if(A=$.replace(U,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)A+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!X0()){let U=this.options.showTags!==!1&&this.name?t.gray(this.formatTag(this.name)):"",W=t.blue("◐");console.error(`${W} ${U} ${t.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
11
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||X0()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),W!==void 0)this.activeProgressBar.message=W;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())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||X0())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||X0()||!O0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),X=$.barLength-Y,J=t.green("━".repeat(Y)),U=t.gray("━".repeat(X)),W=`[${J}${U}]`,f=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",j=w||A===100?t.green("✓"):t.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${t.gray(this.formatTag(this.name))}`:"",E=`\r${j}${z} ${W} ${f}${B}`,F=O0.stdout.columns||80,T=" ".repeat(Math.max(0,F-E.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${E}${T}`,O0.stdout.write($.lastRenderedLine),w)O0.stdout.write(`
12
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||X0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(X0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await uA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let J=mw(this.config.logDirectory,Y);if($.before)try{if((await vw(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await iA(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function oA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&d(w[0])&&"id"in w[0]&&w[0].id===3&&d(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(d(w)&&d($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(d($)&&"arr"in $&&Array.isArray($.arr)&&d(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&d(w[0])&&d($[0])){let Y=[...w];for(let X of $)if(d(X)&&"name"in X){if(!Y.find((U)=>d(U)&&("name"in U)&&U.name===X.name))Y.push(X)}else if(d(X)&&"path"in X){if(!Y.find((U)=>d(U)&&("path"in U)&&U.path===X.path))Y.push(X)}else if(!Y.some((J)=>jY(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!d(w)||!d($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(d(X)&&d(A[Y]))A[Y]=oA(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&d(X[0])&&d(A[Y][0])){let J=[...X];for(let U of A[Y])if(d(U)&&"name"in U){if(!J.find((f)=>d(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(d(U)&&"path"in U){if(!J.find((f)=>d(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((W)=>jY(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function zJ($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:oA($,w);if(Array.isArray($))return A==="replace"?w:oA($,w);if(!d(w)||!d($))return w;let Y={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[X],U=Y[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(A==="replace")Y[X]=J;else Y[X]=oA(U,J);else if(d(J)&&d(U))Y[X]=zJ(U,J,A);else Y[X]=J}return Y}function jY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!jY($[A],w[A]))return!1;return!0}if(d($)&&d(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!jY($[X],w[X]))return!1}return!0}return!1}function d($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function tA($,w,A="replace"){if(!EB($))return null;try{let Y=await import($),X=Y.default||Y;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return zJ(w,X,A)}catch{return null}}catch{return null}}function Z5($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${z.map(E).join("_")}`,T=`${Y}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(A)S0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=J(j,z);else{let K=l1.env[F]||l1.env[T];if(K!==void 0){if(A)S0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((N)=>N.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return J(X)}async function x5({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let f=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?Z5($,X,J):X,B=A||l1.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)S0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),E=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,u0(B,"config"),u0(B,".config"),Y?u0(B,Y):void 0].filter(Boolean)));for(let H of K){if(J)S0.info(`Searching for configuration in: ${H}`);let R=[u0(B,"config"),u0(B,".config")].concat(Y?[u0(B,Y)]:[]).includes(H)?[...z,...E,...F,...T]:[...E,...z,...T,...F];for(let M of R)for(let y of j){let I=u0(H,`${M}${y}`),C=await tA(I,f,W);if(C!==null){if(J)S0.success(`Configuration loaded from: ${I}`);return C}}}if($){let H=u0(S8(),".config",$),N=["config",`${$}.config`];if(w)N.push(`${w}.config`);if(J)S0.info(`Checking user config directory: ${H}`);for(let R of N)for(let M of j){let y=u0(H,`${R}${M}`),I=await tA(y,f,W);if(I!==null){if(J)S0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let H=u0(S8(),".config"),N=[`.${$}.config`];if(w)N.push(`.${w}.config`);if(J)S0.info(`Checking user config directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=u0(H,`${R}${M}`),I=await tA(y,f,W);if(I!==null){if(J)S0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let H=S8(),N=[`.${$}.config`,`.${$}`];if(w)N.push(`.${w}.config`),N.push(`.${w}`);if(J)S0.info(`Checking user home directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=u0(H,`${R}${M}`),I=await tA(y,f,W);if(I!==null){if(J)S0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let H=u0(B,"package.json");if(EB(H)){let N=await import(H),R=N[$];if(!R&&w){if(R=N[w],R&&J)S0.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)S0.success(`Configuration loaded from package.json: ${R===N[$]?$:w}`);return zJ(f,R,W)}catch(M){if(J)S0.warn("Failed to merge package.json config:",M)}}}catch(H){if(J)S0.warn("Failed to load package.json:",H)}if(J)S0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function P5($,w={}){let A=XY.cwd();while(A.includes("storage"))A=SW(A,"..");let Y=SW(A,$||"");if(w?.relative)return vE(XY.cwd(),Y);return Y}async function b5(){try{let $=await x5({name:"clarity",alias:"logging",defaultConfig:wY,cwd:XY.cwd()});return{...wY,...$||{}}}catch{return wY}}function G0(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function u5(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D$<"u"){let $=D$.type;if($==="renderer"||$==="worker")return!1;return!!(D$.versions&&(D$.versions.node||D$.versions.bun))}return!1}class HB{async format($){let w=await u5(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:lw.pid,hostname:w(),environment:lw.env.NODE_ENV||"development",platform:lw.platform,version:lw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lw.env.NODE_ENV||lw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class zY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...e8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new HB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...AY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...AY};return{...AY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:e8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!G0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await w5(this.config.logDirectory,vW.F_OK|vW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await A5(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Q$.from($);try{if(!cA(this.currentLogFile))await b8(this.currentLogFile,"",{mode:420});if(X=cW(this.currentLogFile,"a",420),$5(X,f,{flag:"a"}),iW(X),X!==void 0)P8(X),X=void 0;if((await gw(this.currentLogFile)).size===0){if(await b8(this.currentLogFile,f,{flag:"w",mode:420}),(await gw(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 E=W*2**J;await new Promise((F)=>setTimeout(F,E)),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{P8(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 nw(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 nw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return nw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(G0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.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 x8(16).toString("hex")}generateKey(){return x8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=x8(16),Y=sE("aes-256-gcm",w,A),X=Q$.isBuffer($)?$:Q$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=Q$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=dW(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(Q$.from(Q$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(G0())return;if(!this.shouldWriteToFile())return;let $=await gw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await vA(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await gw(A).catch(()=>null))try{if(await mW(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await mA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await b8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await gw(A).catch(()=>null))await mW(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await vA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await mA(nw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=uW($),Y=eE(w),X=dW();await J5(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),cA(this.currentLogFile))try{let $=cW(this.currentLogFile,"r+");iW($),P8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!G0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await vA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await mA(nw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||G0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=k.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${P.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=P.underline(P.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\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}),w=w.replace(/`([^`]+)`/g,(A,Y)=>P.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>P.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>P.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>P.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>P.strikethrough(Y)),w}supportsHyperlinks(){if(G0())return!1;let $=k.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=k.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Y5(w)||w.startsWith("./")||w.startsWith("../"))w=X5(w);else return null;return cA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":LB[$],E=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:P.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:P.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
13
- `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:P.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!G0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let j=`${J} ${this.environment}.${$.toUpperCase()}: ${B}
7
+ `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!U0()){let Y=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:r.blue("◐"),tag:Y,message:`${r.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
8
+ `,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){let j=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:r.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!U0())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new FA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(U0())throw Error("createReadStream is not supported in browser environments");if(!mX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return dW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Xw.isBuffer($)?$:Xw.from($,"base64"),U=A.slice(0,16),X=A.slice(-16),J=A.slice(16,-16),W=UG("aes-256-gcm",Y,U);return W.setAuthTag(X),Xw.concat([W.update(J),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U0()}isServerMode(){return!U0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!U0()){let X=$.split(`
9
+ `),J=Math.max(...X.map((j)=>j.length))+2,W=`┌${"─".repeat(J)}┐`,f=`└${"─".repeat(J)}┘`,B=X.map((j)=>{let z=" ".repeat(J-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:r.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:r.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:r.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:r.cyan(f),showTimestamp:!1}))}else if(!U0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let U=`${A} ${this.environment}.INFO: [BOX] ${$}
10
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(U0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${r.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();V0.stdin.removeListener("data",Y);try{if(typeof V0.stdin.setRawMode==="function")V0.stdin.setRawMode(!1)}catch{}V0.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof V0.stdin.setRawMode==="function")V0.stdin.setRawMode(!0)}catch{}V0.stdin.resume(),V0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,W=0;if(Y=$.replace(J,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)Y+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!U0()){let J=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",W=r.blue("◐");console.error(`${W} ${J} ${r.cyan(Y)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
11
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||U0()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),W!==void 0)this.activeProgressBar.message=W;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;V0.stdout.write(`${"\r".padEnd(V0.stdout.columns||80)}\r`),this.log(W,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||U0()||!V0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=r.green("━".repeat(A)),J=r.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=w||Y===100?r.green("✓"):r.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${r.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=V0.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,V0.stdout.write($.lastRenderedLine),w)V0.stdout.write(`
12
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||U0()||!V0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await vY(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=vw(this.config.logDirectory,A);if($.before)try{if((await cw(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await mY(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function wA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&m(w[0])&&"id"in w[0]&&w[0].id===3&&m(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(m(w)&&m($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(m($)&&"arr"in $&&Array.isArray($.arr)&&m(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&m(w[0])&&m($[0])){let A=[...w];for(let U of $)if(m(U)&&"name"in U){if(!A.find((J)=>m(J)&&("name"in J)&&J.name===U.name))A.push(U)}else if(m(U)&&"path"in U){if(!A.find((J)=>m(J)&&("path"in J)&&J.path===U.path))A.push(U)}else if(!A.some((X)=>GA(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!m(w)||!m($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(m(U)&&m(Y[A]))Y[A]=wA(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&m(U[0])&&m(Y[A][0])){let X=[...U];for(let J of Y[A])if(m(J)&&"name"in J){if(!X.find((f)=>m(f)&&("name"in f)&&f.name===J.name))X.push(J)}else if(m(J)&&"path"in J){if(!X.find((f)=>m(f)&&("path"in f)&&f.path===J.path))X.push(J)}else if(!X.some((W)=>GA(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function R8($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:wA($,w);if(Array.isArray($))return Y==="replace"?w:wA($,w);if(!m(w)||!m($))return w;let A={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let X=w[U],J=A[U];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(J))if(Y==="replace")A[U]=X;else A[U]=wA(J,X);else if(m(X)&&m(J))A[U]=R8(J,X,Y);else A[U]=X}return A}function GA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!GA($[Y],w[Y]))return!1;return!0}if(m($)&&m(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!GA($[U],w[U]))return!1}return!0}return!1}function m($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function sY($,w,Y="replace"){if(!CB($))return null;try{let A=await import($),U=A.default||A;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return R8(w,U,Y)}catch{return null}}catch{return null}}function pG($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),U={...w};function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${z.map(G).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)Q0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=X(j,z);else{let K=a1.env[F]||a1.env[T];if(K!==void 0){if(Y)Q0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((q)=>q.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return X(U)}async function tG({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:U,verbose:X=!1,checkEnv:J=!0,arrayStrategy:W="replace"}){let f=J&&typeof U==="object"&&U!==null&&!Array.isArray(U)?pG($,U,X):U,B=Y||a1.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(X)Q0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),G=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,b0(B,"config"),b0(B,".config"),A?b0(B,A):void 0].filter(Boolean)));for(let H of K){if(X)Q0.info(`Searching for configuration in: ${H}`);let M=[b0(B,"config"),b0(B,".config")].concat(A?[b0(B,A)]:[]).includes(H)?[...z,...G,...F,...T]:[...G,...z,...T,...F];for(let I of M)for(let h of j){let N=b0(H,`${I}${h}`),C=await sY(N,f,W);if(C!==null){if(X)Q0.success(`Configuration loaded from: ${N}`);return C}}}if($){let H=b0(iX(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(X)Q0.info(`Checking user config directory: ${H}`);for(let M of q)for(let I of j){let h=b0(H,`${M}${I}`),N=await sY(h,f,W);if(N!==null){if(X)Q0.success(`Configuration loaded from user config directory: ${h}`);return N}}}if($){let H=b0(iX(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(X)Q0.info(`Checking user config directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=b0(H,`${M}${I}`),N=await sY(h,f,W);if(N!==null){if(X)Q0.success(`Configuration loaded from user config directory dotfile: ${h}`);return N}}}if($){let H=iX(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(X)Q0.info(`Checking user home directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=b0(H,`${M}${I}`),N=await sY(h,f,W);if(N!==null){if(X)Q0.success(`Configuration loaded from user home directory: ${h}`);return N}}}try{let H=b0(B,"package.json");if(CB(H)){let q=await import(H),M=q[$];if(!M&&w){if(M=q[w],M&&X)Q0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(X)Q0.success(`Configuration loaded from package.json: ${M===q[$]?$:w}`);return R8(f,M,W)}catch(I){if(X)Q0.warn("Failed to merge package.json config:",I)}}}catch(H){if(X)Q0.warn("Failed to load package.json:",H)}if(X)Q0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function rG($,w={}){let Y=fA.cwd();while(Y.includes("storage"))Y=vW(Y,"..");let A=vW(Y,$||"");if(w?.relative)return $G(fA.cwd(),A);return A}async function aG(){try{let $=await tG({name:"clarity",alias:"logging",defaultConfig:UA,cwd:fA.cwd()});return{...UA,...$||{}}}catch{return UA}}function G0(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function sG(){if(D$.env.NODE_ENV==="test"||D$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof D$<"u"){let $=D$.type;if($==="renderer"||$==="worker")return!1;return!!(D$.versions&&(D$.versions.node||D$.versions.bun))}return!1}class QB{async format($){let w=await sG(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:lw.pid,hostname:w(),environment:lw.env.NODE_ENV||"development",platform:lw.platform,version:lw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:lw.env.NODE_ENV||lw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class EA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...W8},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new QB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...XA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...XA};return{...XA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:W8.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!G0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await EG(this.config.logDirectory,oW.F_OK|oW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await KG(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:O$.from($);try{if(!dY(this.currentLogFile))await nX(this.currentLogFile,"",{mode:420});if(U=sW(this.currentLogFile,"a",420),GG(U,f,{flag:"a"}),aW(U),U!==void 0)lX(U),U=void 0;if((await dw(this.currentLogFile)).size===0){if(await nX(this.currentLogFile,f,{flag:"w",mode:420}),(await dw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{lX(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return gw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return gw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return gw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(G0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return gX(16).toString("hex")}generateKey(){return gX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=gX(16),A=jG("aes-256-gcm",w,Y),U=O$.isBuffer($)?$:O$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=O$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=$B(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(O$.from(O$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(G0())return;if(!this.shouldWriteToFile())return;let $=await dw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await gY(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await dw(Y).catch(()=>null))try{if(await eW(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await lY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await nX(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await dw(Y).catch(()=>null))await eW(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await gY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await lY(gw(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=rW($),A=FG(w),U=$B();await NG(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),dY(this.currentLogFile))try{let $=sW(this.currentLogFile,"r+");aW($),lX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!G0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await gY(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await lY(gw(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?x.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||G0())return!1;let $=typeof _.env.NO_COLOR<"u",w=_.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof _.stderr<"u"&&_.stderr.isTTY||typeof _.stdout<"u"&&_.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=_.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${x.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=x.underline(x.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>x.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>x.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>x.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>x.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>x.strikethrough(A)),w}supportsHyperlinks(){if(G0())return!1;let $=_.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=_.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(TG(w)||w.startsWith("./")||w.startsWith("../"))w=HG(w);else return null;return dY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":uB[$],G=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:x.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:x.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
13
+ `);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:x.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!G0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
14
14
  `;if(W)j+=`${W}
15
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!G0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!G0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!G0()&&k.stdout.isTTY)k.stdout.write(`
16
- `);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!G0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":P.blue("◐"),tag:A,message:`${P.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),X=Math.round(Y-w),J=`${$} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
17
- `,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":P.green("✓"),tag:j,message:`${J}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!G0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new zY(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(G0())throw Error("createReadStream is not supported in browser environments");if(!cA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return uW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=Q$.isBuffer($)?$:Q$.from($,"base64"),X=Y.subarray(0,16),J=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=oE("aes-256-gcm",A,X);W.setAuthTag(J);let f=W.update(U),B=W.final(),j=f.length+B.length,z=Q$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return G0()}isServerMode(){return!G0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=X.split(`
18
- `),f=Math.max(...W.map((E)=>E.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((E)=>{return this.formatConsoleMessage({timestamp:A,message:P.cyan(E),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(B),showTimestamp:!1})),z.forEach((E)=>console.error(E)),console.error(this.formatConsoleMessage({timestamp:A,message:P.cyan(j),showTimestamp:!1}))}else if(!G0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${J}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${J}
19
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(G0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${P.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let X=Y.toString().trim().toLowerCase();k.stdin.removeListener("data",A);try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!1)}catch{}k.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!0)}catch{}k.stdin.resume(),k.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(A=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let E=w[B++];switch(z){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return j}}),B<w.length)A+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:Y,fileText:X}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${P.blue("◐")} `;console.error(`${B}${f} ${P.cyan(Y)}`)}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()||!k.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),X=$.barLength-Y,J=P.green("━".repeat(Y)),U=P.gray("━".repeat(X)),W=`[${J}${U}]`,f=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?P.green("✓"):P.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",E=`\r${j}${z} ${W} ${f}${B}`,F=k.stdout.columns||80,T=" ".repeat(Math.max(0,F-E.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${E}${T}`,k.stdout.write($.lastRenderedLine),w)k.stdout.write(`
21
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||G0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(G0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await vA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let J=nw(this.config.logDirectory,Y);if($.before)try{if((await gw(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await mA(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function NB($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(f){if(U=f instanceof Error?f:Error(String(f)),W===A||!X(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function RB($){return $ instanceof e0}function i5($){return $ instanceof FY}function c5($){if(RB($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((A)=>$.message.toLowerCase().includes(A.toLowerCase()))}class NY{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:f=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=Y||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return r1.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=U.map((j)=>this.formatEnvKey(j,Y.useCamelCase)),f=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,A,Y);else{let j=dA.env[f]||(B?dA.env[B]:void 0);if(j!==void 0){if(Y.verbose){let z=dA.env[f]?f:B}try{$[X]=this.parseEnvironmentValue(j,typeof J,f,Y.customParsers,Y.configName)}catch(z){if(z instanceof EY)throw z;throw Uw.envVar(f,j,typeof J,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,X){for(let[J,U]of Object.entries(Y))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Uw.envVar(A,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,X]of Object.entries(dA.env))if(Y.startsWith(A)&&X!==void 0)w[Y]=X;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(X){Y.push(`Cannot parse value "${w}" as ${A}: ${X}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:X="text"}=A,J=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=`${A}_${U.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,A,Y);else Y.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
15
+ `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!G0()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!G0()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!G0()&&_.stdout.isTTY)_.stdout.write(`
16
+ `);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!G0()&&_.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":x.blue("◐"),tag:Y,message:`${x.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
17
+ `,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":x.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!G0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new EA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(G0())throw Error("createReadStream is not supported in browser environments");if(!dY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return rW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=O$.isBuffer($)?$:O$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=zG("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=O$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return G0()}isServerMode(){return!G0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
18
+ `),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:x.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:x.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:x.cyan(j),showTimestamp:!1}))}else if(!G0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
19
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(G0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${x.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();_.stdin.removeListener("data",Y);try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!1)}catch{}_.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof _.stdin.setRawMode==="function")_.stdin.setRawMode(!0)}catch{}_.stdin.resume(),_.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(Y=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let G=w[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<w.length)Y+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?x.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${x.blue("◐")} `;console.error(`${B}${f} ${x.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
20
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!_.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=x.green("━".repeat(A)),J=x.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?x.green("✓"):x.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${x.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=_.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,_.stdout.write($.lastRenderedLine),w)_.stdout.write(`
21
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||G0()||!_.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(G0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await gY(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=gw(this.config.logDirectory,A);if($.before)try{if((await dw(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await lY(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function OB($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}function SB($){return $ instanceof a0}function oG($){return $ instanceof KA}function eG($){if(SB($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class MA{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return e1.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=nY.env[f]||(B?nY.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=nY.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof TA)throw z;throw Jw.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw Jw.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(nY.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
22
22
 
23
- `;for(let Y of $)A+=`${Y.key}
24
- `,A+=` Type: ${Y.type}
25
- `,A+=` Description: ${Y.description}
26
- `,A+=` Example: ${Y.example}
23
+ `;for(let A of $)Y+=`${A.key}
24
+ `,Y+=` Type: ${A.type}
25
+ `,Y+=` Description: ${A.description}
26
+ `,Y+=` Example: ${A.example}
27
27
 
28
- `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
28
+ `;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
29
29
 
30
- `;A+=`| Variable | Type | Description | Example |
31
- `,A+=`|----------|------|-------------|----------|
32
- `;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
33
- `;return A}}function v5($,w){let A=CB("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function qB($,w,A={}){return MB($,w,A,new WeakMap)}function MB($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return IB($,w,X,Y);if(!U$(w)||!U$($))return w;return n5($,w,A,Y)}function IB($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return m5($,w);case"smart":return d5($,w,Y);default:return w}return w}function m5($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>s8(X,Y)))A.push(Y);return A}function d5($,w,A){if(w.length===0)return $;if($.length===0)return w;if(U$(w[0])&&U$($[0]))return g5($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function g5($,w,A){let Y=[...w];for(let X of $){if(!U$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((B)=>U$(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function n5($,w,A,Y){let X=w;if(U$(X)&&Y.has(X))return Y.get(X);let J={...$};if(U$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(U$(W)&&U$(f))J[U]=MB(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=IB(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function FJ($,w,A="replace"){return qB($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function s8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!s8($[A],w[A]))return!1;return!0}if(U$($)&&U$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!s8($[X],w[X]))return!1}return!0}return!1}function U$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class RY{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=aw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!gA($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new p1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new p1($,Error("Configuration must export a valid object"),"unknown");let H={config:FJ(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)aw.setWithFileCheck("file",H,$,J);return H}catch(B){throw B instanceof Error?Uw.configLoad($,B):Uw.configLoad($,Error(String(B)))}};if(U)return r1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(u8(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return NB(async()=>{return gA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!gA($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=u8($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=u8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!gA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class EJ{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await r1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!U5(w))throw new t1(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new t1(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:QB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class GJ{fileLoader=new RY;envProcessor=new NY;validator=new EJ;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;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(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))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: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)H$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw H$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||Cw.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(i0(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw Uw.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?n1($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)H$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)H$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?n1($,A,X):A,W=[i0(cw(),".config",$),i0(cw(),".config"),cw()];for(let f of W){if(X)H$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)H$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?n1($,Y,J):Y;try{let f=i0(A,"package.json");if(!r8(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)H$.success(`Configuration loaded from package.json: ${z}`);return{config:FJ(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)H$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:n1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw Uw.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return aw.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);aw.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,i0($,"config"),i0($,".config"),w?i0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(i0(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[i0(cw(),".config",$),i0(cw(),".config"),cw()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function oW($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function l5($){return x$.loadConfig({...$,__strictErrorHandling:!0})}async function yB($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await x$.loadConfig($);else Y=await x$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let X=Y instanceof Error?Y.name:"UnknownError",J=Y instanceof Error?Y.message:String(Y);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)H$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await x$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function p5($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await x$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&oW(A)))return(await x$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await x$.loadConfig({...$,cwd:$.cwd||Cw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&oW(w)))return(await x$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function t5($,w,A="replace"){let Y=new RY;try{let X=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function n1($,w,A=!1){let Y=new NY,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=Cw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}function r5($){let w=i0(Cw.cwd(),$.configDir),A=i0(Cw.cwd(),$.generatedDir),Y=i0(A,"config-types.ts");if(!r8(QW(Y)))bE(QW(Y),{recursive:!0,mode:511});let X=r8(w)?uE(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${CG}
34
- export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
35
- `;iE(Y,J,{mode:438})}function a5($){let w=null,A=null,Y=()=>{if(!A)A=yB($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)H$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return A},X="defaultConfig"in $?$.defaultConfig:{};return w=X,Y(),new Proxy({},{get(J,U){if(w)return w[U];let W=X[U];return Y(),W},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,W){if(!w)w={...X};return w[U]=W,!0}})}function s5($){let w=gW(B5.cwd(),$?.configDir||"./config");function A(){if(!f5(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=W5(w).filter((f)=>X.has(i8(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),W=new Map;for(let{base:f,file:B}of U){let j=i8(B).toLowerCase(),z=W.get(f);if(!z){W.set(f,B);continue}let E=i8(z).toLowerCase();if(J.indexOf(j)<J.indexOf(E))W.set(f,B)}return Array.from(W.entries()).map(([f,B])=>({base:f,file:B})).sort((f,B)=>f.base.localeCompare(B.base))}function Y(){let X=A(),J=X.map((B)=>B.base),U=J.length?J.map((B)=>`'${B}'`).join(" | "):"string",W=X.length?`{
36
- ${X.map((B)=>{let j=gW(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
30
+ `;Y+=`| Variable | Type | Description | Example |
31
+ `,Y+=`|----------|------|-------------|----------|
32
+ `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
33
+ `;return Y}}function $6($,w){let Y=xB("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function _B($,w,Y={}){return kB($,w,Y,new WeakMap)}function kB($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return DB($,w,U,A);if(!Y$(w)||!Y$($))return w;return U6($,w,Y,A)}function DB($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return w6($,w);case"smart":return Y6($,w,A);default:return w}return w}function w6($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>J8(U,A)))Y.push(A);return Y}function Y6($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(Y$(w[0])&&Y$($[0]))return A6($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function A6($,w,Y){let A=[...w];for(let U of $){if(!Y$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((B)=>Y$(B)&&(W in B)&&B[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function U6($,w,Y,A){let U=w;if(Y$(U)&&A.has(U))return A.get(U);let X={...$};if(Y$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(Y$(W)&&Y$(f))X[J]=kB(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=DB(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function M8($,w,Y="replace"){return _B($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function J8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!J8($[Y],w[Y]))return!1;return!0}if(Y$($)&&Y$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!J8($[U],w[U]))return!1}return!0}return!1}function Y$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class IA{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=rw.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!pY($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new s1($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new s1($,Error("Configuration must export a valid object"),"unknown");let H={config:M8(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)rw.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?Jw.configLoad($,B):Jw.configLoad($,Error(String(B)))}};if(J)return e1.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(pX(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return OB(async()=>{return pY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!pY($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=pX($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=pX($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!pY($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class I8{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await e1.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!qG(w))throw new o1(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new o1(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:cB},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class y8{fileLoader=new IA;envProcessor=new MA;validator=new I8;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)F$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw F$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||Cw.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(u0(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw Jw.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?r1($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)F$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)F$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?r1($,Y,U):Y,W=[u0(iw(),".config",$),u0(iw(),".config"),iw()];for(let f of W){if(U)F$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)F$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?r1($,A,X):A;try{let f=u0(Y,"package.json");if(!U8(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)F$.success(`Configuration loaded from package.json: ${z}`);return{config:M8(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)F$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:r1($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw Jw.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return rw.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);rw.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,u0($,"config"),u0($,".config"),w?u0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(u0(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[u0(iw(),".config",$),u0(iw(),".config"),iw()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function BB($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function X6($){return x$.loadConfig({...$,__strictErrorHandling:!0})}async function ZB($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await x$.loadConfig($);else A=await x$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}catch(A){let U=A instanceof Error?A.name:"UnknownError",X=A instanceof Error?A.message:String(A);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||X.includes("config"))&&$.verbose)F$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await x$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function J6($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await x$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&BB(Y)))return(await x$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await x$.loadConfig({...$,cwd:$.cwd||Cw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&BB(w)))return(await x$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function f6($,w,Y="replace"){let A=new IA;try{let U=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function r1($,w,Y=!1){let A=new MA,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=Cw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}function W6($){let w=u0(Cw.cwd(),$.configDir),Y=u0(Cw.cwd(),$.generatedDir),A=u0(Y,"config-types.ts");if(!U8(cW(A)))a5(cW(A),{recursive:!0,mode:511});let U=U8(w)?s5(w).map((J)=>J.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${b6}
34
+ export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
35
+ `;o5(A,X,{mode:438})}function B6($){let w=null,Y=null,A=()=>{if(!Y)Y=ZB($).then((X)=>{return w=X,X},(X)=>{let J="defaultConfig"in $?$.defaultConfig:{};if(w=J,"verbose"in $&&$.verbose)F$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return J});return Y},U="defaultConfig"in $?$.defaultConfig:{};return w=U,A(),new Proxy({},{get(X,J){if(w)return w[J];let W=U[J];return A(),W},has(X,J){return J in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(X,J){return Object.getOwnPropertyDescriptor(w||U,J)},set(X,J,W){if(!w)w={...U};return w[J]=W,!0}})}function j6($){let w=wB(IG.cwd(),$?.configDir||"./config");function Y(){if(!RG(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],J=MG(w).filter((f)=>U.has(tX(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),W=new Map;for(let{base:f,file:B}of J){let j=tX(B).toLowerCase(),z=W.get(f);if(!z){W.set(f,B);continue}let G=tX(z).toLowerCase();if(X.indexOf(j)<X.indexOf(G))W.set(f,B)}return Array.from(W.entries()).map(([f,B])=>({base:f,file:B})).sort((f,B)=>f.base.localeCompare(B.base))}function A(){let U=Y(),X=U.map((B)=>B.base),J=X.length?X.map((B)=>`'${B}'`).join(" | "):"string",W=U.length?`{
36
+ ${U.map((B)=>{let j=wB(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
37
37
  `)}
38
- }`:"Record<string, any>";return`export type ConfigNames = ${U}
38
+ }`:"Record<string, any>";return`export type ConfigNames = ${J}
39
39
  export type ConfigByName = ${W}
40
40
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
41
41
  export type ConfigOf = Config
42
- `}return{name:"bunfig-plugin",setup(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:Y(),loader:"ts"}})}}}function VG($,w={}){let A=fY.cwd();while(A.includes("storage"))A=nW(A,"..");let Y=nW(A,$||"");if(w?.relative)return z5(fY.cwd(),Y);return Y}function T0(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function OG(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z$<"u"){let $=Z$.type;if($==="renderer"||$==="worker")return!1;return!!(Z$.versions&&(Z$.versions.node||Z$.versions.bun))}return!1}class DB{async format($){let w=await OG(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:rw.pid,hostname:w(),environment:rw.env.NODE_ENV||"development",platform:rw.platform,version:rw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:rw.env.NODE_ENV||rw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class qY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...GY},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new DB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...p8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...p8};return{...p8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:GY.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await T5(this.config.logDirectory,rW.F_OK|rW.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await H5(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:S$.from($);try{if(!nA(this.currentLogFile))await m8(this.currentLogFile,"",{mode:420});if(X=tW(this.currentLogFile,"a",420),K5(X,f,{flag:"a"}),pW(X),X!==void 0)v8(X),X=void 0;if((await pw(this.currentLogFile)).size===0){if(await m8(this.currentLogFile,f,{flag:"w",mode:420}),(await pw(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 E=W*2**J;await new Promise((F)=>setTimeout(F,E)),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{v8(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 tw(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 tw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return tw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.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 c8(16).toString("hex")}generateKey(){return c8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=c8(16),Y=F5("aes-256-gcm",w,A),X=S$.isBuffer($)?$:S$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=S$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=sW(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(S$.from(S$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let $=await pw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await lA(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await pw(A).catch(()=>null))try{if(await aW(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await pA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await m8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await pw(A).catch(()=>null))await aW(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await lA(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await pA(tw(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=lW($),Y=G5(w),X=sW();await q5(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),nA(this.currentLogFile))try{let $=tW(this.currentLogFile,"r+");pW($),v8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await lA(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await pA(tw(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=D.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${i.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=i.underline(i.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\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}),w=w.replace(/`([^`]+)`/g,(A,Y)=>i.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>i.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>i.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>i.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>i.strikethrough(Y)),w}supportsHyperlinks(){if(T0())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=D.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(N5(w)||w.startsWith("./")||w.startsWith("../"))w=R5(w);else return null;return nA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":DG[$],E=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:i.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:i.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
43
- `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:i.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}let j=`${J} ${this.environment}.${$.toUpperCase()}: ${B}
42
+ `}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function i6($,w={}){let Y=jA.cwd();while(Y.includes("storage"))Y=YB(Y,"..");let A=YB(Y,$||"");if(w?.relative)return CG(jA.cwd(),A);return A}function K0(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function v6(){if(Z$.env.NODE_ENV==="test"||Z$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof Z$<"u"){let $=Z$.type;if($==="renderer"||$==="worker")return!1;return!!(Z$.versions&&(Z$.versions.node||Z$.versions.bun))}return!1}class gB{async format($){let w=await v6(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:tw.pid,hostname:w(),environment:tw.env.NODE_ENV||"development",platform:tw.platform,version:tw.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:tw.env.NODE_ENV||tw.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class yA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...HA},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new gB,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Y8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Y8};return{...Y8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:HA.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!K0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await OG(this.config.logDirectory,JB.F_OK|JB.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await SG(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:S$.from($);try{if(!tY(this.currentLogFile))await sX(this.currentLogFile,"",{mode:420});if(U=XB(this.currentLogFile,"a",420),QG(U,f,{flag:"a"}),UB(U),U!==void 0)aX(U),U=void 0;if((await nw(this.currentLogFile)).size===0){if(await sX(this.currentLogFile,f,{flag:"w",mode:420}),(await nw(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{aX(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return pw(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return pw(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return pw(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(K0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return rX(16).toString("hex")}generateKey(){return rX(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=rX(16),A=hG("aes-256-gcm",w,Y),U=S$.isBuffer($)?$:S$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=S$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=WB(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(S$.from(S$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(K0())return;if(!this.shouldWriteToFile())return;let $=await nw(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await rY(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await nw(Y).catch(()=>null))try{if(await fB(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await aY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await sX(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await nw(Y).catch(()=>null))await fB(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await rY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await aY(pw(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=AB($),A=LG(w),U=WB();await DG(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),tY(this.currentLogFile))try{let $=XB(this.currentLogFile,"r+");UB($),aX($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!K0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await rY(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await aY(pw(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||K0())return!1;let $=typeof k.env.NO_COLOR<"u",w=k.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof k.stderr<"u"&&k.stderr.isTTY||typeof k.stdout<"u"&&k.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=k.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${u.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=u.underline(u.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>u.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>u.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>u.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>u.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>u.strikethrough(A)),w}supportsHyperlinks(){if(K0())return!1;let $=k.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=k.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(_G(w)||w.startsWith("./")||w.startsWith("../"))w=kG(w);else return null;return tY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":n6[$],G=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:u.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:u.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
43
+ `);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:u.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!K0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
44
44
  `;if(W)j+=`${W}
45
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!T0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!T0()&&D.stdout.isTTY)D.stdout.write(`
46
- `);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":i.blue("◐"),tag:A,message:`${i.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),X=Math.round(Y-w),J=`${$} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(A)B+=` ${JSON.stringify(A)}`;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}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!T0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new qY(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(T0())throw Error("createReadStream is not supported in browser environments");if(!nA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return lW(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=S$.isBuffer($)?$:S$.from($,"base64"),X=Y.subarray(0,16),J=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=E5("aes-256-gcm",A,X);W.setAuthTag(J);let f=W.update(U),B=W.final(),j=f.length+B.length,z=S$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T0()}isServerMode(){return!T0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=X.split(`
48
- `),f=Math.max(...W.map((E)=>E.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((E)=>{return this.formatConsoleMessage({timestamp:A,message:i.cyan(E),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:i.cyan(B),showTimestamp:!1})),z.forEach((E)=>console.error(E)),console.error(this.formatConsoleMessage({timestamp:A,message:i.cyan(j),showTimestamp:!1}))}else if(!T0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${J}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${J}
49
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(T0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${i.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let X=Y.toString().trim().toLowerCase();D.stdin.removeListener("data",A);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(A=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let E=w[B++];switch(z){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return j}}),B<w.length)A+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:Y,fileText:X}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${B}${f} ${i.cyan(Y)}`)}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 A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),X=$.barLength-Y,J=i.green("━".repeat(Y)),U=i.gray("━".repeat(X)),W=`[${J}${U}]`,f=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?i.green("✓"):i.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",E=`\r${j}${z} ${W} ${f}${B}`,F=D.stdout.columns||80,T=" ".repeat(Math.max(0,F-E.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${E}${T}`,D.stdout.write($.lastRenderedLine),w)D.stdout.write(`
51
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||T0()||!D.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await lA(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let J=tw(this.config.logDirectory,Y);if($.before)try{if((await pw(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await pA(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function ZG($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(f){if(U=f instanceof Error?f:Error(String(f)),W===A||!X(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class TJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:f=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=Y||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return fJ.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=U.map((j)=>this.formatEnvKey(j,Y.useCamelCase)),f=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,A,Y);else{let j=rA.env[f]||(B?rA.env[B]:void 0);if(j!==void 0){if(Y.verbose){let z=rA.env[f]?f:B}try{$[X]=this.parseEnvironmentValue(j,typeof J,f,Y.customParsers,Y.configName)}catch(z){if(z instanceof KJ)throw z;throw sw.envVar(f,j,typeof J,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,X){for(let[J,U]of Object.entries(Y))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw sw.envVar(A,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,X]of Object.entries(rA.env))if(Y.startsWith(A)&&X!==void 0)w[Y]=X;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(X){Y.push(`Cannot parse value "${w}" as ${A}: ${X}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:X="text"}=A,J=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=`${A}_${U.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,A,Y);else Y.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
45
+ `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!K0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!K0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!K0()&&k.stdout.isTTY)k.stdout.write(`
46
+ `);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!K0()&&k.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:Y,message:`${u.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
47
+ `,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":u.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!K0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new yA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(K0())throw Error("createReadStream is not supported in browser environments");if(!tY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return AB(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=S$.isBuffer($)?$:S$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=VG("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=S$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return K0()}isServerMode(){return!K0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
48
+ `),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:u.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:u.cyan(j),showTimestamp:!1}))}else if(!K0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
49
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(K0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${u.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();k.stdin.removeListener("data",Y);try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!1)}catch{}k.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof k.stdin.setRawMode==="function")k.stdin.setRawMode(!0)}catch{}k.stdin.resume(),k.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(Y=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let G=w[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<w.length)Y+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${B}${f} ${u.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
50
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!k.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=u.green("━".repeat(A)),J=u.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?u.green("✓"):u.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=k.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,k.stdout.write($.lastRenderedLine),w)k.stdout.write(`
51
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||K0()||!k.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(K0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await rY(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=pw(this.config.logDirectory,A);if($.before)try{if((await nw(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await aY(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function p6($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}class h8{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return T8.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=oY.env[f]||(B?oY.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=oY.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof C8)throw z;throw aw.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw aw.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(oY.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
52
52
 
53
- `;for(let Y of $)A+=`${Y.key}
54
- `,A+=` Type: ${Y.type}
55
- `,A+=` Description: ${Y.description}
56
- `,A+=` Example: ${Y.example}
53
+ `;for(let A of $)Y+=`${A.key}
54
+ `,Y+=` Type: ${A.type}
55
+ `,Y+=` Description: ${A.description}
56
+ `,Y+=` Example: ${A.example}
57
57
 
58
- `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
58
+ `;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
59
59
 
60
- `;A+=`| Variable | Type | Description | Example |
61
- `,A+=`|----------|------|-------------|----------|
62
- `;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
63
- `;return A}}function xG($,w,A={}){return vB($,w,A,new WeakMap)}function vB($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return mB($,w,X,Y);if(!f$(w)||!f$($))return w;return iG($,w,A,Y)}function mB($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return PG($,w);case"smart":return bG($,w,Y);default:return w}return w}function PG($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>UJ(X,Y)))A.push(Y);return A}function bG($,w,A){if(w.length===0)return $;if($.length===0)return w;if(f$(w[0])&&f$($[0]))return uG($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function uG($,w,A){let Y=[...w];for(let X of $){if(!f$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((B)=>f$(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function iG($,w,A,Y){let X=w;if(f$(X)&&Y.has(X))return Y.get(X);let J={...$};if(f$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(f$(W)&&f$(f))J[U]=vB(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=mB(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function dB($,w,A="replace"){return xG($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function UJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!UJ($[A],w[A]))return!1;return!0}if(f$($)&&f$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!UJ($[X],w[X]))return!1}return!0}return!1}function f$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class gB{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=YY.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!aA($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new KY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new KY($,Error("Configuration must export a valid object"),"unknown");let H={config:dB(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)YY.setWithFileCheck("file",H,$,J);return H}catch(B){throw B instanceof Error?sw.configLoad($,B):sw.configLoad($,Error(String(B)))}};if(U)return fJ.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(t8(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of Y){if(!J)continue;if(A.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)A.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return A.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return ZG(async()=>{return aA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!aA($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=t8($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=t8($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!aA($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class nB{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await fJ.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!cG(w))throw new TY(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new TY(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:vG},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function mG($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class lB{fileLoader=new gB;envProcessor=new TJ;validator=new nB;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;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(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))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: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)_$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let f=Date.now()-w;throw _$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||HY.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(J$(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw sw.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${mG(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?sA($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)_$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)_$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?sA($,A,X):A,W=[J$(iw(),".config",$),J$(iw(),".config"),iw()];for(let f of W){if(X)_$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)_$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?sA($,Y,J):Y;try{let f=J$(A,"package.json");if(!xE(f))return null;let B={};try{B=JSON.parse(PE(f,"utf8"))}catch(E){if(J)_$.warn("Failed to parse package.json:",[E instanceof Error?E:Error(String(E))]);return null}let j=B[$],z=$;if(!j&&w){let E=Array.isArray(w)?w:[w];for(let F of E){if(!F)continue;if(B[F]){j=B[F],z=F;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)_$.success(`Configuration loaded from package.json: ${z}`);return{config:dB(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)_$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:sA($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw sw.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return YY.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);YY.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,J$($,"config"),J$($,".config"),w?J$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(J$(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[J$(iw(),".config",$),J$(iw(),".config"),iw()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function sA($,w,A=!1){let Y=new TJ,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=HY.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}var YY,fJ,M5,I5=($)=>$,C5=($,w)=>{for(var A in w)M5($,A,{get:w[A],enumerable:!0,configurable:!0,set:y5.bind(w,A)})},h5=($,w)=>()=>($&&(w=$($=0)),w),KB,CB,aw,r1,hB,o5,e5,eW,eA,o8,Q0,t,$G,$B,wG,wB,AG,YG,d8,XG,AB,YB,g8,JG,UG,fG,WG,$Y,VB,BG,S0,jG,zG,XB,wY,e8,K0,P,FG,JB,EG,UB,GG,KG,n8,TG,fB,WB,HG,l8,NG,RG,qG,MG,IG,AY,LB,yG,CG="0.15.6",e0,FY,p1,$J,wJ,EY,AJ,YJ,t1,XJ,JJ,Uw,OB,QB,H$,x$,SB,_B,hG,LG,kB,GY,pM,C0,i,tM,QG,rM,SG,aM,sM,BB,oM,_G,kG,eM,jB,$I,wI,AI,YI,XI,p8,DG,JI,N$,ZB,KY,xB,PB,KJ,bB,uB,TY,iB,cB,sw,vG,_$,jI,zI,FI;var HJ=F0(()=>{YY=new zB,fJ=new FB,M5=Object.defineProperty;KB={};C5(KB,{withErrorRecovery:()=>NB,tryLoadConfig:()=>t5,loadConfigWithResult:()=>l5,loadConfig:()=>yB,isRetryableError:()=>c5,isConfigNotFoundError:()=>i5,isBunfigError:()=>RB,globalPerformanceMonitor:()=>r1,globalCache:()=>aw,getEnvOrDefault:()=>v5,generateConfigTypes:()=>r5,defaultGeneratedDir:()=>_B,defaultConfigDir:()=>SB,deepMergeWithArrayStrategy:()=>FJ,deepMerge:()=>qB,createLibraryConfig:()=>a5,config:()=>p5,bunfigPlugin:()=>s5,applyEnvVarsToConfig:()=>n1,TypeGenerationError:()=>YJ,SchemaValidationError:()=>t1,PluginError:()=>JJ,PerformanceMonitor:()=>BJ,FileSystemError:()=>AJ,ErrorFactory:()=>Uw,EnvVarError:()=>EY,EnvProcessor:()=>NY,ConfigValidator:()=>EJ,ConfigValidationError:()=>$J,ConfigNotFoundError:()=>FY,ConfigMergeError:()=>wJ,ConfigLoader:()=>GJ,ConfigLoadError:()=>p1,ConfigFileLoader:()=>RY,ConfigCache:()=>WJ,CacheUtils:()=>hB,BunfigError:()=>e0,BrowserConfigError:()=>XJ,ArrayMergeStrategies:()=>OB});hG=h5(async()=>{CB=import.meta.require,aw=new WJ,r1=new BJ,hB={createKey:V5,isEquivalent:L5,estimateMemoryUsage:O5},o5=UY(a8.cwd(),"config"),e5=UY(a8.cwd(),"src/generated"),eW=JY.env.CLARITY_LOG_DIR||mE(_5(),"logs"),eA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:eW,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},o8=await k5(),Q0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},t=Q0,$G=Q0.red,$B=Q0.green,wG=Q0.yellow,wB=Q0.blue,AG=Q0.magenta,YG=Q0.cyan,d8=Q0.white,XG=Q0.gray,AB=Q0.bgRed,YB=Q0.bgYellow,g8=Q0.bold,JG=Q0.dim,UG=Q0.italic,fG=Q0.underline,WG=Q0.reset,$Y={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},VB={debug:"\uD83D\uDD0D",info:wB("ℹ"),success:$B("✓"),warning:YB(d8(g8(" WARN "))),error:AB(d8(g8(" ERROR ")))},BG=new BY("stacks"),S0=new BY("bunfig",{showTags:!0}),jG=u0(l1.cwd(),"config"),zG=u0(l1.cwd(),"src/generated"),XB=XY.env.CLARITY_LOG_DIR||cE(P5(),"logs"),wY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:XB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},e8=await b5(),K0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=K0,FG=K0.red,JB=K0.green,EG=K0.yellow,UB=K0.blue,GG=K0.magenta,KG=K0.cyan,n8=K0.white,TG=K0.gray,fB=K0.bgRed,WB=K0.bgYellow,HG=K0.bgGray,l8=K0.bold,NG=K0.dim,RG=K0.italic,qG=K0.underline,MG=K0.strikethrough,IG=K0.reset,AY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},LB={debug:"\uD83D\uDD0D",info:UB("ℹ"),success:JB("✓"),warning:WB(n8(l8(" WARN "))),error:fB(n8(l8(" ERROR ")))},yG=new zY("stacks"),e0=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},FY=class extends e0{code="CONFIG_NOT_FOUND";constructor(w,A,Y){let X=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},p1=class extends e0{code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},$J=class extends e0{code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},wJ=class extends e0{code="CONFIG_MERGE_ERROR";constructor(w,A,Y,X){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},EY=class extends e0{code="ENV_VAR_ERROR";constructor(w,A,Y,X){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:X})}},AJ=class extends e0{code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},YJ=class extends e0{code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},t1=class extends e0{code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},XJ=class extends e0{code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,X){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:X})}},JJ=class extends e0{code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Uw={configNotFound($,w,A){return new FY($,w,A)},configLoad($,w,A){return new p1($,w,A)},configValidation($,w,A){return new $J($,w,A)},configMerge($,w,A,Y){return new wJ($,w,A,Y)},envVar($,w,A,Y){return new EY($,w,A,Y)},fileSystem($,w,A){return new AJ($,w,A)},typeGeneration($,w,A){return new YJ($,w,A)},schemaValidation($,w,A){return new t1($,w,A)},browserConfig($,w,A,Y){return new XJ($,w,A,Y)},plugin($,w,A){return new JJ($,w,A)}},OB={replace:"replace",concat:"concat",smart:"smart"},QB=/^https?:\/\//,H$=new zY("bunfig",{showTags:!0}),x$=new GJ,SB=i0(Cw.cwd(),"config"),_B=i0(Cw.cwd(),"src/generated")});LG=fY.env.CLARITY_LOG_DIR||j5(VG(),"logs"),kB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:LG,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},GY={...kB},pM=(async()=>{try{let{loadConfig:$}=await hG().then(()=>KB),w=await $({name:"clarity",alias:"logging",defaultConfig:kB,cwd:fY.cwd()});if(w)Object.assign(GY,w)}catch{}return GY})();C0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=C0,tM=C0.red,QG=C0.green,rM=C0.yellow,SG=C0.blue,aM=C0.magenta,sM=C0.cyan,BB=C0.white,oM=C0.gray,_G=C0.bgRed,kG=C0.bgYellow,eM=C0.bgGray,jB=C0.bold,$I=C0.dim,wI=C0.italic,AI=C0.underline,YI=C0.strikethrough,XI=C0.reset,p8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},DG={debug:"\uD83D\uDD0D",info:SG("ℹ"),success:QG("✓"),warning:kG(BB(jB(" WARN "))),error:_G(BB(jB(" ERROR ")))};JI=new qY("stacks");N$=class N$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};ZB=class ZB extends N${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],X="";if(Y.length===1)X=` or alias "${Y[0]}"`;else if(Y.length>1)X=` or aliases ${Y.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};KY=class KY extends N${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};xB=class xB extends N${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};PB=class PB extends N${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};KJ=class KJ extends N${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};bB=class bB extends N${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};uB=class uB extends N${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};TY=class TY extends N${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};iB=class iB extends N${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};cB=class cB extends N${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};sw={configNotFound($,w,A){return new ZB($,w,A)},configLoad($,w,A){return new KY($,w,A)},configValidation($,w,A){return new xB($,w,A)},configMerge($,w,A,Y){return new PB($,w,A,Y)},envVar($,w,A,Y){return new KJ($,w,A,Y)},fileSystem($,w,A){return new bB($,w,A)},typeGeneration($,w,A){return new uB($,w,A)},schemaValidation($,w,A){return new TY($,w,A)},browserConfig($,w,A,Y){return new iB($,w,A,Y)},plugin($,w,A){return new cB($,w,A)}};vG=/^https?:\/\//;_$=new qY("bunfig",{showTags:!0});jI=new lB;zI=J$(HY.cwd(),"config"),FI=J$(HY.cwd(),"src/generated")});var q;var fw=F0(()=>{q={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as nG}from"node:module";import{Resolver as qJ}from"node:dns/promises";import{createHash as pG,sign as tG}from"node:crypto";import{createHash as rG}from"node:crypto";import{sign as aG}from"node:crypto";import{generateKeyPairSync as ej,X509Certificate as J6}from"node:crypto";import MJ from"node:os";import IJ from"node:path";import{existsSync as tB,statSync as rB}from"fs";import{existsSync as f6,mkdirSync as SI,readdirSync as _I,readFileSync as W6,writeFileSync as kI}from"fs";import{homedir as ew}from"os";import{dirname as xI,resolve as B$}from"path";import UX from"process";import{existsSync as aB,statSync as sB}from"fs";import{existsSync as lJ,mkdirSync as B6,readdirSync as j6,writeFileSync as z6}from"fs";import{homedir as $1}from"os";import{dirname as oB,resolve as v0}from"path";import Vw from"process";import{join as F6,relative as E6,resolve as eB}from"path";import dY from"process";import{existsSync as $9,mkdirSync as nI,readdirSync as lI,writeFileSync as pI}from"fs";import{homedir as yJ}from"os";import{dirname as aI,resolve as c0}from"path";import $A from"process";import{join as G6,relative as K6,resolve as $j}from"path";import gY from"process";import{existsSync as w9,mkdirSync as w4,readdirSync as A4,writeFileSync as Y4}from"fs";import{dirname as J4,resolve as nY}from"path";import pJ from"process";import{Buffer as Ww}from"buffer";import{createCipheriv as T6,createDecipheriv as H6,randomBytes as CJ}from"crypto";import{closeSync as hJ,createReadStream as wj,createWriteStream as N6,existsSync as VJ,fsyncSync as Aj,openSync as Yj,writeFileSync as R6}from"fs";import{access as q6,constants as Xj,mkdir as M6,readdir as MY,rename as Jj,stat as w1,unlink as IY,writeFile as LJ}from"fs/promises";import{join as A1}from"path";import _0 from"process";import{pipeline as I6}from"stream/promises";import{createGzip as Uj}from"zlib";import Y1 from"process";import i$ from"process";import{Buffer as P$}from"buffer";import{createCipheriv as y6,createDecipheriv as C6,randomBytes as OJ}from"crypto";import{closeSync as QJ,createReadStream as fj,createWriteStream as h6,existsSync as yY,fsyncSync as Wj,openSync as Bj,writeFileSync as V6}from"fs";import{access as L6,constants as jj,mkdir as O6,readdir as CY,rename as zj,stat as X1,unlink as hY,writeFile as SJ}from"fs/promises";import{isAbsolute as Q6,join as J1,resolve as S6}from"path";import g from"process";import{pipeline as _6}from"stream/promises";import{createGzip as Fj}from"zlib";import U1 from"process";import c$ from"process";import VY from"process";import{existsSync as LY}from"fs";import{resolve as _J}from"path";import{existsSync as k6}from"fs";import{existsSync as D6,readdirSync as Z6}from"fs";import{extname as kJ,resolve as Ej}from"path";import x6 from"process";import{join as P6,relative as b6,resolve as Gj}from"path";import lY from"process";import{Buffer as b$}from"buffer";import{createCipheriv as u6,createDecipheriv as i6,randomBytes as DJ}from"crypto";import{closeSync as ZJ,createReadStream as Kj,createWriteStream as c6,existsSync as OY,fsyncSync as Tj,openSync as Hj,writeFileSync as v6}from"fs";import{access as m6,constants as Nj,mkdir as d6,readdir as QY,rename as Rj,stat as f1,unlink as SY,writeFile as xJ}from"fs/promises";import{isAbsolute as g6,join as W1,resolve as n6}from"path";import n from"process";import{pipeline as l6}from"stream/promises";import{createGzip as qj}from"zlib";import B1 from"process";import v$ from"process";import _Y from"process";import{existsSync as kY}from"fs";import{resolve as PJ}from"path";import{existsSync as p6}from"fs";import{exec as KT}from"node:child_process";import Zj from"node:fs";import TT from"node:os";import R$ from"node:path";import b9 from"node:process";import{promisify as HT}from"node:util";import E1 from"node:crypto";import m$ from"node:fs";import UU from"node:path";import{execSync as ij}from"node:child_process";import XX from"node:os";async function cj($,w,A={}){let Y=A.timeoutMs??120000,X=A.intervalMs??3000,J=$.split(".").slice(-2).join("."),U;try{let B=new qJ,j=await B.resolveNs(J),z=(await Promise.all(j.map((E)=>B.resolve4(E).catch(()=>[])))).flat();if(z.length>0)U=new qJ,U.setServers(z)}catch{}let W=Date.now()+Y,f=U??new qJ;for(;;){try{if((await f.resolveTxt($)).some((B)=>B.join("")===w))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,X))}}class e1{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(e1.PATH_PREFIX);if(w===-1)return;let A=$.slice(w+e1.PATH_PREFIX.length);return this.get(A)}}function xY($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function mJ($){return Buffer.from($,"base64url")}function vj($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function mj($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return pG("sha256").update(w).digest("base64url")}function dj($){let{protectedHeader:w,payload:A,privateKey:Y}=$,X=xY(JSON.stringify(w)),J=A===""?"":xY(JSON.stringify(A)),U=`${X}.${J}`,W=tG("sha256",Buffer.from(U),{key:Y,dsaEncoding:"ieee-p1363"});return{protected:X,payload:J,signature:xY(W)}}class mY{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=vj($.accountPublicKey),this.thumbprint=mj(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:A,useJwk:Y}=$,X={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(Y)X.jwk=this.jwk;else X.kid=this.requireKid();let J=dj({protectedHeader:X,payload:A,privateKey:this.accountKey}),U=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(J)}),W=U.headers.get("replay-nonce");if(W)this.nonce=W;let f=U.headers.get("content-type")??"",B;if(f.includes("application/pem-certificate-chain")||f.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 vY(`ACME request to ${w} 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($={}){let w=await this.directory(),A={termsOfServiceAgreed:!0};if($.email)A.contact=[`mailto:${$.email}`];let Y=await this.signedPost({url:w.newAccount,payload:A,useJwk:!0});if(!Y.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=Y.location,this.accountKid}async newOrder($){let w=await this.directory(),A={identifiers:$.map((X)=>({type:"dns",value:X}))},Y=await this.signedPost({url:w.newOrder,payload:A});if(!Y.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:Y.body,orderUrl:Y.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return rG("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,X=Date.now()+A;while(Date.now()<X){let J=await this.getAuthorization($);if(J.status==="valid")return;if(J.status==="invalid"){let U=J.challenges.find((W)=>W.status==="invalid");throw new vY(`Authorization for ${J.identifier.value} became invalid: ${U?.error?.detail??"unknown reason"}`,U?.error??{},0)}await pB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let A=w.timeoutMs??60000,Y=w.intervalMs??2000,X=Date.now()+A;while(Date.now()<X){let J=await this.getOrder($);if(J.status==="valid"){if(!J.certificate)throw Error("ACME order is valid but has no certificate URL");return J.certificate}if(J.status==="invalid")throw Error(`ACME order ${$} became invalid`);await pB(Y),Y=Math.min(Y*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let A=$.challenges.find((Y)=>Y.type===w);if(!A)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return A}}function lj($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],A=w[0];if(!A)return{certPem:`${$.trim()}
64
- `,chainPem:""};let Y=`${A.trim()}
65
- `,X=w.slice(1).map((J)=>J.trim()).join(`
66
- `);return{certPem:Y,chainPem:X?`${X}
67
- `:""}}function pj($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function pB($){return new Promise((w)=>setTimeout(w,$))}function sG($){if($<128)return Buffer.from([$]);let w=[],A=$;while(A>0)w.unshift(A&255),A>>=8;return Buffer.from([128|w.length,...w])}function zw($,w){return Buffer.concat([Buffer.from([$]),sG(w.length),w])}function tj($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=[],Y=$;while(Y>0)A.unshift(Y&255),Y>>=8;if(A[0]&128)A.unshift(0);w=Buffer.from(A)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return zw(2,w)}function hw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let A=[40*w[0]+w[1]];for(let Y=2;Y<w.length;Y++){let X=w[Y],J=[X&127];X=Math.floor(X/128);while(X>0)J.unshift(X&127|128),X=Math.floor(X/128);A.push(...J)}return zw(6,Buffer.from(A))}function W$(...$){return zw(48,Buffer.concat($))}function dJ(...$){return zw(49,Buffer.concat($))}function gJ($){return zw(3,Buffer.concat([Buffer.from([0]),$]))}function rj($){return zw(4,$)}function aj($){return zw(12,Buffer.from($,"utf8"))}function nJ($,w,A){let Y=128|(A?32:0)|$;return zw(Y,w)}function X6($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let A=mJ(w.x),Y=mJ(w.y);if(A.length!==32||Y.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${A.length} y=${Y.length}`);return Buffer.concat([Buffer.from([4]),A,Y])}function sj($){let{domains:w,publicKey:A,privateKey:Y}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let X=W$(dJ(W$(hw(w6),aj(w[0])))),J=W$(W$(hw(oG),hw(eG)),gJ(X6(A))),U=w.map((K)=>nJ(2,Buffer.from(K,"ascii"),!1)),W=W$(...U),f=W$(hw(Y6),rj(W)),B=W$(f),j=W$(hw(A6),dJ(B)),z=nJ(0,j,!0),E=W$(tj(0),X,J,z),F=aG("sha256",E,Y),T=W$(hw($6));return W$(E,T,gJ(F))}function oj($){return sj($).toString("base64url")}function U6($){if($){let{createPrivateKey:X,createPublicKey:J}=lG("node:crypto"),U=X($),W=J(U);return{privateKey:U,publicKey:W,pem:$}}let{privateKey:w,publicKey:A}=ej("ec",{namedCurve:"P-256"}),Y=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:A,pem:Y}}async function fU($){let{domains:w,method:A}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(A==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((z)=>z.startsWith("*."))&&A!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let Y=$.directoryUrl??($.staging===!1?nj:gj),X=U6($.accountKeyPem),J=new mY({directoryUrl:Y,accountKey:X.privateKey,accountPublicKey:X.publicKey});await J.newAccount({email:$.email});let{order:U,orderUrl:W}=await J.newOrder(w),f=$.http01Store??JX,B=[],j=[];try{for(let I of U.authorizations){let C=await J.getAuthorization(I);if(C.status==="valid")continue;let j0=mY.selectChallenge(C,A);if(A==="dns-01"){let Q=pj(C.identifier.value),_=J.dns01TxtValue(j0.token);await $.dnsProvider.setTxt(Q,_),B.push({name:Q,value:_}),await cj(Q,_,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else f.add(j0.token,J.keyAuthorization(j0.token)),j.push(j0.token);await J.notifyChallengeReady(j0.url),await J.pollAuthorization(I,{timeoutMs:$.timeoutMs})}let{privateKey:z,publicKey:E}=ej("ec",{namedCurve:"P-256"}),F=oj({domains:w,publicKey:E,privateKey:z});await J.finalizeOrder(U.finalize,F);let T=await J.pollOrder(W,{timeoutMs:$.timeoutMs}),K=await J.downloadCertificate(T),{certPem:H,chainPem:N}=lj(K),R=N?`${H}${N}`:H,M=z.export({format:"pem",type:"pkcs8"}).toString(),y=new Date(new J6(H).validTo);return{certPem:H,keyPem:M,chainPem:N,fullChainPem:R,accountKeyPem:X.pem,notAfter:y}}finally{for(let{name:z,value:E}of B)await $.dnsProvider?.removeTxt(z,E).catch(()=>{});for(let z of j)f.remove(z)}}class A9{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!tB($))return!0;return rB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=tB(A)?rB(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class Y9{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function a6($,w){this[$]=r6.bind(null,w)}class BU{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!aB($))return!0;return sB($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=aB(A)?sB(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class jU{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function e6($,w={}){let A=Object.keys(w).sort().map((Y)=>`${Y}:${w[Y]}`).join("|");return A?`${$}:${A}`:$}function $K($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function wK($){return $.getStats().size*2}function zU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&e(w[0])&&"id"in w[0]&&w[0].id===3&&e(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(e(w)&&e($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(e($)&&"arr"in $&&Array.isArray($.arr)&&e(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&e(w[0])&&e($[0])){let Y=[...w];for(let X of $)if(e(X)&&"name"in X){if(!Y.find((J)=>e(J)&&("name"in J)&&J.name===X.name))Y.push(X)}else if(e(X)&&"path"in X){if(!Y.find((J)=>e(J)&&("path"in J)&&J.path===X.path))Y.push(X)}else if(!Y.some((J)=>tY(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!e(w)||!e($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(e(X)&&e(A[Y]))A[Y]=zU(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&e(X[0])&&e(A[Y][0])){let J=[...X];for(let U of A[Y])if(e(U)&&"name"in U){if(!J.find((W)=>e(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(e(U)&&"path"in U){if(!J.find((W)=>e(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((W)=>tY(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function tY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!tY($[A],w[A]))return!1;return!0}if(e($)&&e(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!tY($[X],w[X]))return!1}return!0}return!1}function e($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function AK($,w){if(!w9($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return zU(w,Y)}catch{return null}}catch{return null}}async function YK({name:$="",cwd:w,defaultConfig:A}){let Y=w||pJ.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let W of X){let f=nY(Y,`${U}${W}`),B=await AK(f,A);if(B!==null)return B}try{let U=nY(Y,"package.json");if(w9(U)){let W=(await import(U))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return zU(A,W)}catch{}}}catch{}return A}function XK($,w={}){let A=gY.cwd();while(A.includes("storage"))A=$j(A,"..");let Y=$j(A,$||"");if(w?.relative)return K6(gY.cwd(),Y);return Y}async function JK(){try{let $=await YK({name:"clarity",defaultConfig:bY,cwd:gY.cwd(),endpoint:"",headers:{}});return{...bY,...$}}catch{return bY}}function J0(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function UK(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof i$<"u"){let $=i$.type;if($==="renderer"||$==="worker")return!1;return!!(i$.versions&&(i$.versions.node||i$.versions.bun))}return!1}class J9{async format($){let w=await UK(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Y1.pid,hostname:w(),environment:Y1.env.NODE_ENV||"development",platform:Y1.platform,version:Y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Y1.env.NODE_ENV||Y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class rY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...rJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new J9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??_0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...uY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...uY};return{...uY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:rJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let w=(async()=>{let Y,X=0,J=3,U=1000;while(X<J)try{try{try{await q6(this.config.logDirectory,Xj.F_OK|Xj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await M6(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Ww.from($);try{if(!VJ(this.currentLogFile))await LJ(this.currentLogFile,"",{mode:420});if(Y=Yj(this.currentLogFile,"a",420),R6(Y,W,{flag:"a"}),Aj(Y),Y!==void 0)hJ(Y),Y=void 0;if((await w1(this.currentLogFile)).size===0){if(await LJ(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(f){let B=f;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((E)=>setTimeout(E,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(Y!==void 0)try{hJ(Y)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}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 f=U*2**(X-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return A1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return A1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return A1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(J0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,X);if(Y.length>J)for(let[U]of Y.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return CJ(16).toString("hex")}generateKey(){return CJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=CJ(16),Y=T6("aes-256-gcm",w,A),X=Ww.concat([Y.update($,"utf8"),Y.final()]),J=Y.getAuthTag();return{encrypted:Ww.concat([A,X,J]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=Uj(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(Ww.from(Ww.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(J0())return;let $=await w1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await MY(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await w1(A).catch(()=>null))try{if(await Jj(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await IY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await LJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await w1(A).catch(()=>null))await Jj(A,J)}if(this.currentLogFile=Y,w.maxFiles){let X=(await MY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await IY(A1(this.config.logDirectory,J))}}}async compressLogFile($,w){let A=wj($),Y=N6(w),X=Uj();await I6(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),VJ(this.currentLogFile))try{let $=Yj(this.currentLogFile,"r+");Aj($),hJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!J0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await MY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await IY(A1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?r.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=_0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${r.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!J0()){let B=K9[$],j=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:r.gray(U),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:r.green(U),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z),W){let E=W.split(`
68
- `);for(let F of E)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:r.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!J0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let f=`${J} ${this.environment}.${$.toUpperCase()}: ${U}
60
+ `;Y+=`| Variable | Type | Description | Example |
61
+ `,Y+=`|----------|------|-------------|----------|
62
+ `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
63
+ `;return Y}}function t6($,w,Y={}){return oB($,w,Y,new WeakMap)}function oB($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return eB($,w,U,A);if(!A$(w)||!A$($))return w;return o6($,w,Y,A)}function eB($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return r6($,w);case"smart":return a6($,w,A);default:return w}return w}function r6($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>K8(U,A)))Y.push(A);return Y}function a6($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(A$(w[0])&&A$($[0]))return s6($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function s6($,w,Y){let A=[...w];for(let U of $){if(!A$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((B)=>A$(B)&&(W in B)&&B[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function o6($,w,Y,A){let U=w;if(A$(U)&&A.has(U))return A.get(U);let X={...$};if(A$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(A$(W)&&A$(f))X[J]=oB(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=eB(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function $j($,w,Y="replace"){return t6($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function K8($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!K8($[Y],w[Y]))return!1;return!0}if(A$($)&&A$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!K8($[U],w[U]))return!1}return!0}return!1}function A$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class wj{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=JA.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!eY($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new NA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new NA($,Error("Configuration must export a valid object"),"unknown");let H={config:$j(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)JA.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?aw.configLoad($,B):aw.configLoad($,Error(String(B)))}};if(J)return T8.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(A8(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of A){if(!X)continue;if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)Y.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let U=new Set;return Y.filter((X)=>{if(!X||U.has(X))return!1;return U.add(X),!0})}checkFileAccess($){return p6(async()=>{return eY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!eY($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=A8($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=A8($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!eY($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class Yj{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await T8.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!e6(w))throw new qA(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new qA(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:$E},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function wE($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class Aj{fileLoader=new wj;envProcessor=new h8;validator=new Yj;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)_$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let f=Date.now()-w;throw _$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||RA.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(w$(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw aw.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${wE(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?$A($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)_$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)_$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?$A($,Y,U):Y,W=[w$(uw(),".config",$),w$(uw(),".config"),uw()];for(let f of W){if(U)_$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)_$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?$A($,A,X):A;try{let f=w$(Y,"package.json");if(!t5(f))return null;let B={};try{B=JSON.parse(r5(f,"utf8"))}catch(G){if(X)_$.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let j=B[$],z=$;if(!j&&w){let G=Array.isArray(w)?w:[w];for(let F of G){if(!F)continue;if(B[F]){j=B[F],z=F;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)_$.success(`Configuration loaded from package.json: ${z}`);return{config:$j(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)_$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:$A($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw aw.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return JA.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);JA.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,w$($,"config"),w$($,".config"),w?w$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(w$(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[w$(uw(),".config",$),w$(uw(),".config"),uw()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function $A($,w,Y=!1){let A=new h8,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=RA.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}var JA,T8,ZG,xG=($)=>$,bG=($,w)=>{for(var Y in w)ZG($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:PG.bind(w,Y)})},uG=($,w)=>()=>($&&(w=$($=0)),w),VB,xB,rw,e1,PB,z6,F6,jB,YA,f8,L0,r,G6,zB,E6,FB,K6,T6,oX,H6,GB,EB,eX,N6,q6,R6,M6,AA,bB,I6,Q0,y6,C6,KB,UA,W8,E0,x,h6,TB,V6,HB,L6,Q6,$8,O6,NB,qB,S6,w8,_6,k6,D6,Z6,x6,XA,uB,P6,b6="0.15.6",a0,KA,s1,B8,j8,TA,z8,F8,o1,G8,E8,Jw,iB,cB,F$,x$,vB,mB,u6,c6,dB,HA,KI,I0,u,TI,m6,HI,d6,NI,qI,RB,RI,g6,l6,MI,MB,II,yI,CI,hI,VI,Y8,n6,LI,G$,lB,NA,nB,pB,C8,tB,rB,qA,aB,sB,aw,$E,_$,kI,DI,ZI;var V8=j0(()=>{JA=new IB,T8=new yB,ZG=Object.defineProperty;VB={};bG(VB,{withErrorRecovery:()=>OB,tryLoadConfig:()=>f6,loadConfigWithResult:()=>X6,loadConfig:()=>ZB,isRetryableError:()=>eG,isConfigNotFoundError:()=>oG,isBunfigError:()=>SB,globalPerformanceMonitor:()=>e1,globalCache:()=>rw,getEnvOrDefault:()=>$6,generateConfigTypes:()=>W6,defaultGeneratedDir:()=>mB,defaultConfigDir:()=>vB,deepMergeWithArrayStrategy:()=>M8,deepMerge:()=>_B,createLibraryConfig:()=>B6,config:()=>J6,bunfigPlugin:()=>j6,applyEnvVarsToConfig:()=>r1,TypeGenerationError:()=>F8,SchemaValidationError:()=>o1,PluginError:()=>E8,PerformanceMonitor:()=>N8,FileSystemError:()=>z8,ErrorFactory:()=>Jw,EnvVarError:()=>TA,EnvProcessor:()=>MA,ConfigValidator:()=>I8,ConfigValidationError:()=>B8,ConfigNotFoundError:()=>KA,ConfigMergeError:()=>j8,ConfigLoader:()=>y8,ConfigLoadError:()=>s1,ConfigFileLoader:()=>IA,ConfigCache:()=>H8,CacheUtils:()=>PB,BunfigError:()=>a0,BrowserConfigError:()=>G8,ArrayMergeStrategies:()=>iB});u6=uG(async()=>{xB=import.meta.require,rw=new H8,e1=new N8,PB={createKey:iG,isEquivalent:cG,estimateMemoryUsage:vG},z6=BA(X8.cwd(),"config"),F6=BA(X8.cwd(),"src/generated"),jB=WA.env.CLARITY_LOG_DIR||wG(gG(),"logs"),YA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:jB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},f8=await lG(),L0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},r=L0,G6=L0.red,zB=L0.green,E6=L0.yellow,FB=L0.blue,K6=L0.magenta,T6=L0.cyan,oX=L0.white,H6=L0.gray,GB=L0.bgRed,EB=L0.bgYellow,eX=L0.bold,N6=L0.dim,q6=L0.italic,R6=L0.underline,M6=L0.reset,AA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},bB={debug:"\uD83D\uDD0D",info:FB("ℹ"),success:zB("✓"),warning:EB(oX(eX(" WARN "))),error:GB(oX(eX(" ERROR ")))},I6=new FA("stacks"),Q0=new FA("bunfig",{showTags:!0}),y6=b0(a1.cwd(),"config"),C6=b0(a1.cwd(),"src/generated"),KB=fA.env.CLARITY_LOG_DIR||e5(rG(),"logs"),UA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:KB,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},W8=await aG(),E0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},x=E0,h6=E0.red,TB=E0.green,V6=E0.yellow,HB=E0.blue,L6=E0.magenta,Q6=E0.cyan,$8=E0.white,O6=E0.gray,NB=E0.bgRed,qB=E0.bgYellow,S6=E0.bgGray,w8=E0.bold,_6=E0.dim,k6=E0.italic,D6=E0.underline,Z6=E0.strikethrough,x6=E0.reset,XA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},uB={debug:"\uD83D\uDD0D",info:HB("ℹ"),success:TB("✓"),warning:qB($8(w8(" WARN "))),error:NB($8(w8(" ERROR ")))},P6=new EA("stacks"),a0=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},KA=class extends a0{code="CONFIG_NOT_FOUND";constructor(w,Y,A){let U=A?` or alias "${A}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},s1=class extends a0{code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},B8=class extends a0{code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},j8=class extends a0{code="CONFIG_MERGE_ERROR";constructor(w,Y,A,U){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:U,originalError:A.name,originalMessage:A.message});this.cause=A}},TA=class extends a0{code="ENV_VAR_ERROR";constructor(w,Y,A,U){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:U})}},z8=class extends a0{code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},F8=class extends a0{code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},o1=class extends a0{code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},G8=class extends a0{code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,U){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:U})}},E8=class extends a0{code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Jw={configNotFound($,w,Y){return new KA($,w,Y)},configLoad($,w,Y){return new s1($,w,Y)},configValidation($,w,Y){return new B8($,w,Y)},configMerge($,w,Y,A){return new j8($,w,Y,A)},envVar($,w,Y,A){return new TA($,w,Y,A)},fileSystem($,w,Y){return new z8($,w,Y)},typeGeneration($,w,Y){return new F8($,w,Y)},schemaValidation($,w,Y){return new o1($,w,Y)},browserConfig($,w,Y,A){return new G8($,w,Y,A)},plugin($,w,Y){return new E8($,w,Y)}},iB={replace:"replace",concat:"concat",smart:"smart"},cB=/^https?:\/\//,F$=new EA("bunfig",{showTags:!0}),x$=new y8,vB=u0(Cw.cwd(),"config"),mB=u0(Cw.cwd(),"src/generated")});c6=jA.env.CLARITY_LOG_DIR||yG(i6(),"logs"),dB={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:c6,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},HA={...dB},KI=(async()=>{try{let{loadConfig:$}=await u6().then(()=>VB),w=await $({name:"clarity",alias:"logging",defaultConfig:dB,cwd:jA.cwd()});if(w)Object.assign(HA,w)}catch{}return HA})();I0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},u=I0,TI=I0.red,m6=I0.green,HI=I0.yellow,d6=I0.blue,NI=I0.magenta,qI=I0.cyan,RB=I0.white,RI=I0.gray,g6=I0.bgRed,l6=I0.bgYellow,MI=I0.bgGray,MB=I0.bold,II=I0.dim,yI=I0.italic,CI=I0.underline,hI=I0.strikethrough,VI=I0.reset,Y8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},n6={debug:"\uD83D\uDD0D",info:d6("ℹ"),success:m6("✓"),warning:l6(RB(MB(" WARN "))),error:g6(RB(MB(" ERROR ")))};LI=new yA("stacks");G$=class G$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};lB=class lB extends G${code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],U="";if(A.length===1)U=` or alias "${A[0]}"`;else if(A.length>1)U=` or aliases ${A.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${U} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};NA=class NA extends G${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};nB=class nB extends G${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};pB=class pB extends G${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};C8=class C8 extends G${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};tB=class tB extends G${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};rB=class rB extends G${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};qA=class qA extends G${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};aB=class aB extends G${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};sB=class sB extends G${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};aw={configNotFound($,w,Y){return new lB($,w,Y)},configLoad($,w,Y){return new NA($,w,Y)},configValidation($,w,Y){return new nB($,w,Y)},configMerge($,w,Y,A){return new pB($,w,Y,A)},envVar($,w,Y,A){return new C8($,w,Y,A)},fileSystem($,w,Y){return new tB($,w,Y)},typeGeneration($,w,Y){return new rB($,w,Y)},schemaValidation($,w,Y){return new qA($,w,Y)},browserConfig($,w,Y,A){return new aB($,w,Y,A)},plugin($,w,Y){return new sB($,w,Y)}};$E=/^https?:\/\//;_$=new yA("bunfig",{showTags:!0});kI=new Aj;DI=w$(RA.cwd(),"config"),ZI=w$(RA.cwd(),"src/generated")});var R;var fw=j0(()=>{R={info:(...$)=>console.log("[info]",...$),success:(...$)=>console.log("[success]",...$),warn:(...$)=>console.warn("[warn]",...$),error:(...$)=>console.error("[error]",...$),debug:(...$)=>console.debug("[debug]",...$),log:(...$)=>console.log(...$),start:(...$)=>console.log("[start]",...$),box:(...$)=>console.log("[box]",...$)}});import{createRequire as UE}from"node:module";import{Resolver as O8}from"node:dns/promises";import{createHash as JE,sign as fE}from"node:crypto";import{createHash as WE}from"node:crypto";import{sign as BE}from"node:crypto";import{generateKeyPairSync as Wz,X509Certificate as NE}from"node:crypto";import S8 from"node:os";import _8 from"node:path";import{existsSync as Xj,statSync as Jj}from"fs";import{existsSync as RE,mkdirSync as oI,readdirSync as eI,readFileSync as ME,writeFileSync as $4}from"fs";import{homedir as ow}from"os";import{dirname as A4,resolve as X$}from"path";import BU from"process";import{existsSync as fj,statSync as Wj}from"fs";import{existsSync as wJ,mkdirSync as IE,readdirSync as yE,writeFileSync as CE}from"fs";import{homedir as ew}from"os";import{dirname as Bj,resolve as c0}from"path";import Vw from"process";import{join as hE,relative as VE,resolve as jj}from"path";import nA from"process";import{existsSync as Bz,mkdirSync as G4,readdirSync as E4,writeFileSync as K4}from"fs";import{homedir as k8}from"os";import{dirname as N4,resolve as i0}from"path";import UY from"process";import{join as LE,relative as QE,resolve as zj}from"path";import pA from"process";import{existsSync as jz,mkdirSync as y4,readdirSync as C4,writeFileSync as h4}from"fs";import{dirname as L4,resolve as tA}from"path";import YJ from"process";import{Buffer as Ww}from"buffer";import{createCipheriv as OE,createDecipheriv as SE,randomBytes as D8}from"crypto";import{closeSync as Z8,createReadStream as Fj,createWriteStream as _E,existsSync as x8,fsyncSync as Gj,openSync as Ej,writeFileSync as kE}from"fs";import{access as DE,constants as Kj,mkdir as ZE,readdir as CA,rename as Tj,stat as $1,unlink as hA,writeFile as P8}from"fs/promises";import{join as w1}from"path";import O0 from"process";import{pipeline as xE}from"stream/promises";import{createGzip as Hj}from"zlib";import Y1 from"process";import i$ from"process";import{Buffer as P$}from"buffer";import{createCipheriv as PE,createDecipheriv as bE,randomBytes as b8}from"crypto";import{closeSync as u8,createReadStream as Nj,createWriteStream as uE,existsSync as VA,fsyncSync as qj,openSync as Rj,writeFileSync as iE}from"fs";import{access as cE,constants as Mj,mkdir as vE,readdir as LA,rename as Ij,stat as A1,unlink as QA,writeFile as i8}from"fs/promises";import{isAbsolute as mE,join as U1,resolve as dE}from"path";import d from"process";import{pipeline as gE}from"stream/promises";import{createGzip as yj}from"zlib";import X1 from"process";import c$ from"process";import OA from"process";import{existsSync as SA}from"fs";import{resolve as c8}from"path";import{existsSync as lE}from"fs";import{existsSync as nE,readdirSync as pE}from"fs";import{extname as v8,resolve as Cj}from"path";import tE from"process";import{join as rE,relative as aE,resolve as hj}from"path";import rA from"process";import{Buffer as b$}from"buffer";import{createCipheriv as sE,createDecipheriv as oE,randomBytes as m8}from"crypto";import{closeSync as d8,createReadStream as Vj,createWriteStream as eE,existsSync as _A,fsyncSync as Lj,openSync as Qj,writeFileSync as $K}from"fs";import{access as wK,constants as Oj,mkdir as YK,readdir as kA,rename as Sj,stat as J1,unlink as DA,writeFile as g8}from"fs/promises";import{isAbsolute as AK,join as f1,resolve as UK}from"path";import g from"process";import{pipeline as XK}from"stream/promises";import{createGzip as _j}from"zlib";import W1 from"process";import v$ from"process";import ZA from"process";import{existsSync as xA}from"fs";import{resolve as l8}from"path";import{existsSync as JK}from"fs";import{exec as Q7}from"node:child_process";import GJ from"node:fs";import O7 from"node:os";import E$ from"node:path";import nz from"node:process";import{promisify as S7}from"node:util";import F1 from"node:crypto";import m$ from"node:fs";import TJ from"node:path";import e7 from"node:crypto";import{execSync as YT}from"node:child_process";import fU from"node:os";async function rj($,w,Y={}){let A=Y.timeoutMs??120000,U=Y.intervalMs??3000,X=$.split(".").slice(-2).join("."),J;try{let B=new O8,j=await B.resolveNs(X),z=(await Promise.all(j.map((G)=>B.resolve4(G).catch(()=>[])))).flat();if(z.length>0)J=new O8,J.setServers(z)}catch{}let W=Date.now()+A,f=J??new O8;for(;;){try{if((await f.resolveTxt($)).some((B)=>B.join("")===w))return!0}catch{}if(Date.now()>=W)return!1;await new Promise((B)=>setTimeout(B,U))}}class AY{tokens=new Map;add($,w){this.tokens.set($,w)}get($){return this.tokens.get($)}remove($){this.tokens.delete($)}static PATH_PREFIX="/.well-known/acme-challenge/";handlePath($){let w=$.indexOf(AY.PATH_PREFIX);if(w===-1)return;let Y=$.slice(w+AY.PATH_PREFIX.length);return this.get(Y)}}function uA($){return(typeof $==="string"?Buffer.from($,"utf8"):Buffer.from($)).toString("base64url")}function s8($){return Buffer.from($,"base64url")}function aj($){let w=$.export({format:"jwk"});if(w.kty!=="EC"||w.crv!=="P-256"||!w.x||!w.y)throw Error(`Expected a P-256 EC public key, got kty=${w.kty} crv=${w.crv}`);return{crv:"P-256",kty:"EC",x:w.x,y:w.y}}function sj($){let w=`{"crv":"${$.crv}","kty":"${$.kty}","x":"${$.x}","y":"${$.y}"}`;return JE("sha256").update(w).digest("base64url")}function oj($){let{protectedHeader:w,payload:Y,privateKey:A}=$,U=uA(JSON.stringify(w)),X=Y===""?"":uA(JSON.stringify(Y)),J=`${U}.${X}`,W=fE("sha256",Buffer.from(J),{key:A,dsaEncoding:"ieee-p1363"});return{protected:U,payload:X,signature:uA(W)}}class lA{directoryUrl;accountKey;jwk;thumbprint;directoryCache;nonce;accountKid;constructor($){this.directoryUrl=$.directoryUrl,this.accountKey=$.accountKey,this.jwk=aj($.accountPublicKey),this.thumbprint=sj(this.jwk)}get keyThumbprint(){return this.thumbprint}get kid(){return this.accountKid}async directory(){if(this.directoryCache)return this.directoryCache;let $=await fetch(this.directoryUrl);if(!$.ok)throw Error(`Failed to fetch ACME directory: HTTP ${$.status}`);return this.directoryCache=await $.json(),this.directoryCache}async newNonce(){let $=await this.directory(),w=(await fetch($.newNonce,{method:"HEAD"})).headers.get("replay-nonce");if(!w)throw Error("ACME server did not return a Replay-Nonce");return this.nonce=w,w}async ensureNonce(){if(this.nonce){let $=this.nonce;return this.nonce=void 0,$}return this.newNonce()}async signedPost($){let{url:w,payload:Y,useJwk:A}=$,U={alg:"ES256",nonce:await this.ensureNonce(),url:w};if(A)U.jwk=this.jwk;else U.kid=this.requireKid();let X=oj({protectedHeader:U,payload:Y,privateKey:this.accountKey}),J=await fetch(w,{method:"POST",headers:{"content-type":"application/jose+json"},body:JSON.stringify(X)}),W=J.headers.get("replay-nonce");if(W)this.nonce=W;let f=J.headers.get("content-type")??"",B;if(f.includes("application/pem-certificate-chain")||f.startsWith("text/"))B=await J.text();else{let j=await J.text();B=j?JSON.parse(j):{}}if(J.status>=400){let j=B??{};throw new gA(`ACME request to ${w} failed (HTTP ${J.status}): ${j.type??""} ${j.detail??""}`.trim(),j,J.status)}return{status:J.status,headers:J.headers,body:B,location:J.headers.get("location")??void 0}}requireKid(){if(!this.accountKid)throw Error("No ACME account; call newAccount() first");return this.accountKid}async newAccount($={}){let w=await this.directory(),Y={termsOfServiceAgreed:!0};if($.email)Y.contact=[`mailto:${$.email}`];let A=await this.signedPost({url:w.newAccount,payload:Y,useJwk:!0});if(!A.location)throw Error("ACME newAccount did not return an account URL (Location header)");return this.accountKid=A.location,this.accountKid}async newOrder($){let w=await this.directory(),Y={identifiers:$.map((U)=>({type:"dns",value:U}))},A=await this.signedPost({url:w.newOrder,payload:Y});if(!A.location)throw Error("ACME newOrder did not return an order URL (Location header)");return{order:A.body,orderUrl:A.location}}async getAuthorization($){return(await this.signedPost({url:$,payload:""})).body}keyAuthorization($){return`${$}.${this.thumbprint}`}dns01TxtValue($){return WE("sha256").update(this.keyAuthorization($)).digest("base64url")}async notifyChallengeReady($){await this.signedPost({url:$,payload:{}})}async pollAuthorization($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,U=Date.now()+Y;while(Date.now()<U){let X=await this.getAuthorization($);if(X.status==="valid")return;if(X.status==="invalid"){let J=X.challenges.find((W)=>W.status==="invalid");throw new gA(`Authorization for ${X.identifier.value} became invalid: ${J?.error?.detail??"unknown reason"}`,J?.error??{},0)}await Uj(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for authorization ${$} to become valid`)}async finalizeOrder($,w){return(await this.signedPost({url:$,payload:{csr:w}})).body}async getOrder($){return(await this.signedPost({url:$,payload:""})).body}async pollOrder($,w={}){let Y=w.timeoutMs??60000,A=w.intervalMs??2000,U=Date.now()+Y;while(Date.now()<U){let X=await this.getOrder($);if(X.status==="valid"){if(!X.certificate)throw Error("ACME order is valid but has no certificate URL");return X.certificate}if(X.status==="invalid")throw Error(`ACME order ${$} became invalid`);await Uj(A),A=Math.min(A*1.5,1e4)}throw Error(`Timed out waiting for order ${$} to become valid`)}async downloadCertificate($){let w=await this.signedPost({url:$,payload:""});return typeof w.body==="string"?w.body:String(w.body)}static selectChallenge($,w){let Y=$.challenges.find((A)=>A.type===w);if(!Y)throw Error(`No ${w} challenge available for ${$.identifier.value}`);return Y}}function wz($){let w=$.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----\n?/g)??[],Y=w[0];if(!Y)return{certPem:`${$.trim()}
64
+ `,chainPem:""};let A=`${Y.trim()}
65
+ `,U=w.slice(1).map((X)=>X.trim()).join(`
66
+ `);return{certPem:A,chainPem:U?`${U}
67
+ `:""}}function Yz($){return`_acme-challenge.${$.startsWith("*.")?$.slice(2):$}`}function Uj($){return new Promise((w)=>setTimeout(w,$))}function jE($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function zw($,w){return Buffer.concat([Buffer.from([$]),jE(w.length),w])}function Az($){let w;if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=[],A=$;while(A>0)Y.unshift(A&255),A>>=8;if(Y[0]&128)Y.unshift(0);w=Buffer.from(Y)}else if(w=$.length===0?Buffer.from([0]):$,w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return zw(2,w)}function hw($){let w=$.split(".").map(Number);if(w.length<2)throw Error(`Invalid OID: ${$}`);let Y=[40*w[0]+w[1]];for(let A=2;A<w.length;A++){let U=w[A],X=[U&127];U=Math.floor(U/128);while(U>0)X.unshift(U&127|128),U=Math.floor(U/128);Y.push(...X)}return zw(6,Buffer.from(Y))}function U$(...$){return zw(48,Buffer.concat($))}function o8(...$){return zw(49,Buffer.concat($))}function e8($){return zw(3,Buffer.concat([Buffer.from([0]),$]))}function Uz($){return zw(4,$)}function Xz($){return zw(12,Buffer.from($,"utf8"))}function $J($,w,Y){let A=128|(Y?32:0)|$;return zw(A,w)}function HE($){let w=$.export({format:"jwk"});if(!w.x||!w.y)throw Error("Public key JWK is missing x/y coordinates");let Y=s8(w.x),A=s8(w.y);if(Y.length!==32||A.length!==32)throw Error(`Expected 32-byte P-256 coordinates, got x=${Y.length} y=${A.length}`);return Buffer.concat([Buffer.from([4]),Y,A])}function Jz($){let{domains:w,publicKey:Y,privateKey:A}=$;if(w.length===0)throw Error("At least one domain is required to build a CSR");let U=U$(o8(U$(hw(EE),Xz(w[0])))),X=U$(U$(hw(zE),hw(FE)),e8(HE(Y))),J=w.map((K)=>$J(2,Buffer.from(K,"ascii"),!1)),W=U$(...J),f=U$(hw(TE),Uz(W)),B=U$(f),j=U$(hw(KE),o8(B)),z=$J(0,j,!0),G=U$(Az(0),U,X,z),F=BE("sha256",G,A),T=U$(hw(GE));return U$(G,T,e8(F))}function fz($){return Jz($).toString("base64url")}function qE($){if($){let{createPrivateKey:U,createPublicKey:X}=XE("node:crypto"),J=U($),W=X(J);return{privateKey:J,publicKey:W,pem:$}}let{privateKey:w,publicKey:Y}=Wz("ec",{namedCurve:"P-256"}),A=w.export({format:"pem",type:"pkcs8"}).toString();return{privateKey:w,publicKey:Y,pem:A}}async function HJ($){let{domains:w,method:Y}=$;if(w.length===0)throw Error("obtainCertificate requires at least one domain");if(Y==="dns-01"&&!$.dnsProvider)throw Error("dns-01 requires a dnsProvider to publish _acme-challenge TXT records");if(w.some((z)=>z.startsWith("*."))&&Y!=="dns-01")throw Error("Wildcard certificates require the dns-01 challenge method");let A=$.directoryUrl??($.staging===!1?$z:ej),U=qE($.accountKeyPem),X=new lA({directoryUrl:A,accountKey:U.privateKey,accountPublicKey:U.publicKey});await X.newAccount({email:$.email});let{order:J,orderUrl:W}=await X.newOrder(w),f=$.http01Store??WU,B=[],j=[];try{for(let N of J.authorizations){let C=await X.getAuthorization(N);if(C.status==="valid")continue;let O=lA.selectChallenge(C,Y);if(Y==="dns-01"){let p=Yz(C.identifier.value),x0=X.dns01TxtValue(O.token);await $.dnsProvider.setTxt(p,x0),B.push({name:p,value:x0}),await rj(p,x0,{timeoutMs:$.dnsPropagationTimeoutMs??120000})}else f.add(O.token,X.keyAuthorization(O.token)),j.push(O.token);await X.notifyChallengeReady(O.url),await X.pollAuthorization(N,{timeoutMs:$.timeoutMs})}let{privateKey:z,publicKey:G}=Wz("ec",{namedCurve:"P-256"}),F=fz({domains:w,publicKey:G,privateKey:z});await X.finalizeOrder(J.finalize,F);let T=await X.pollOrder(W,{timeoutMs:$.timeoutMs}),K=await X.downloadCertificate(T),{certPem:H,chainPem:q}=wz(K),M=q?`${H}${q}`:H,I=z.export({format:"pem",type:"pkcs8"}).toString(),h=new Date(new NE(H).validTo);return{certPem:H,keyPem:I,chainPem:q,fullChainPem:M,accountKeyPem:U.pem,notAfter:h}}finally{for(let{name:z,value:G}of B)await $.dnsProvider?.removeTxt(z,G).catch(()=>{});for(let z of j)f.remove(z)}}class zz{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!Xj($))return!0;return Jj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=Xj(Y)?Jj(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Fz{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function BK($,w){this[$]=WK.bind(null,w)}class qJ{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!fj($))return!0;return Wj($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=fj(Y)?Wj(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class RJ{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function FK($,w={}){let Y=Object.keys(w).sort().map((A)=>`${A}:${w[A]}`).join("|");return Y?`${$}:${Y}`:$}function GK($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function EK($){return $.getStats().size*2}function MJ($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let A=[...w];for(let U of $)if($0(U)&&"name"in U){if(!A.find((X)=>$0(X)&&("name"in X)&&X.name===U.name))A.push(U)}else if($0(U)&&"path"in U){if(!A.find((X)=>$0(X)&&("path"in X)&&X.path===U.path))A.push(U)}else if(!A.some((X)=>sA(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!$0(w)||!$0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if($0(U)&&$0(Y[A]))Y[A]=MJ(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&$0(U[0])&&$0(Y[A][0])){let X=[...U];for(let J of Y[A])if($0(J)&&"name"in J){if(!X.find((W)=>$0(W)&&("name"in W)&&W.name===J.name))X.push(J)}else if($0(J)&&"path"in J){if(!X.find((W)=>$0(W)&&("path"in W)&&W.path===J.path))X.push(J)}else if(!X.some((W)=>sA(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function sA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!sA($[Y],w[Y]))return!1;return!0}if($0($)&&$0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!sA($[U],w[U]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function KK($,w){if(!jz($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return MJ(w,A)}catch{return null}}catch{return null}}async function TK({name:$="",cwd:w,defaultConfig:Y}){let A=w||YJ.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let J of X)for(let W of U){let f=tA(A,`${J}${W}`),B=await KK(f,Y);if(B!==null)return B}try{let J=tA(A,"package.json");if(jz(J)){let W=(await import(J))[$];if(W&&typeof W==="object"&&!Array.isArray(W))try{return MJ(Y,W)}catch{}}}catch{}return Y}function HK($,w={}){let Y=pA.cwd();while(Y.includes("storage"))Y=zj(Y,"..");let A=zj(Y,$||"");if(w?.relative)return QE(pA.cwd(),A);return A}async function NK(){try{let $=await TK({name:"clarity",defaultConfig:cA,cwd:pA.cwd(),endpoint:"",headers:{}});return{...cA,...$}}catch{return cA}}function X0(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function qK(){if(i$.env.NODE_ENV==="test"||i$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof i$<"u"){let $=i$.type;if($==="renderer"||$==="worker")return!1;return!!(i$.versions&&(i$.versions.node||i$.versions.bun))}return!1}class Ez{async format($){let w=await qK(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:Y1.pid,hostname:w(),environment:Y1.env.NODE_ENV||"development",platform:Y1.platform,version:Y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:Y1.env.NODE_ENV||Y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class oA{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...UJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Ez,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??O0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...vA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...vA};return{...vA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:UJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let w=(async()=>{let A,U=0,X=3,J=1000;while(U<X)try{try{try{await DE(this.config.logDirectory,Kj.F_OK|Kj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await ZE(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Ww.from($);try{if(!x8(this.currentLogFile))await P8(this.currentLogFile,"",{mode:420});if(A=Ej(this.currentLogFile,"a",420),kE(A,W,{flag:"a"}),Gj(A),A!==void 0)Z8(A),A=void 0;if((await $1(this.currentLogFile)).size===0){if(await P8(this.currentLogFile,W,{flag:"w",mode:420}),(await $1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<X-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${X}:`,j);let z=J*2**U;await new Promise((G)=>setTimeout(G,z)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{Z8(A)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(W){if(U===X-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}U++;let f=J*2**(U-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return w1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return w1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return w1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(X0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,J],[,W])=>W.createdAt.getTime()-J.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,U);if(A.length>X)for(let[J]of A.slice(X))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return D8(16).toString("hex")}generateKey(){return D8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=D8(16),A=OE("aes-256-gcm",w,Y),U=Ww.concat([A.update($,"utf8"),A.final()]),X=A.getAuthTag();return{encrypted:Ww.concat([Y,U,X]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=Hj(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(Ww.from(Ww.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(X0())return;let $=await $1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await CA(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await $1(Y).catch(()=>null))try{if(await Tj(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await hA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await P8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await $1(Y).catch(()=>null))await Tj(Y,X)}if(this.currentLogFile=A,w.maxFiles){let U=(await CA(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,J)=>J.localeCompare(X));for(let X of U.slice(w.maxFiles))await hA(w1(this.config.logDirectory,X))}}}async compressLogFile($,w){let Y=Fj($),A=_E(w),U=Hj();await xE(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),x8(this.currentLogFile))try{let $=Ej(this.currentLogFile,"r+");Gj($),Z8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!X0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await CA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await hA(w1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?a.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=O0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${a.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);if(this.fancy&&!X0()){let B=Cz[$],j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:a.gray(J),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:a.green(J),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z),W){let G=W.split(`
68
+ `);for(let F of G)if(F.trim()&&!F.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:a.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!X0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let f=`${X} ${this.environment}.${$.toUpperCase()}: ${J}
69
69
  `;if(W)f+=`${W}
70
- `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!J0()){let A=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:r.blue("◐"),tag:A,message:`${r.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),X=Math.round(Y-w),J=`${$} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),f=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(A)f+=` ${JSON.stringify(A)}`;if(f+=`
71
- `,f=f.replace(this.ANSI_PATTERN,""),this.fancy&&!J0()){let B=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:r.green("✓"),tag:B,message:`${J}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!J0())console.error(f.trim());await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new rY(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(J0())throw Error("createReadStream is not supported in browser environments");if(!VJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return wj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=Ww.isBuffer($)?$:Ww.from($,"base64"),X=Y.slice(0,16),J=Y.slice(-16),U=Y.slice(16,-16),W=H6("aes-256-gcm",A,X);return W.setAuthTag(J),Ww.concat([W.update(U),W.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return J0()}isServerMode(){return!J0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w);if(this.fancy&&!J0()){let J=$.split(`
72
- `),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,f=`└${"─".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:A,message:r.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:r.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:A,message:r.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:r.cyan(f),showTimestamp:!1}))}else if(!J0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let X=`${Y} ${this.environment}.INFO: [BOX] ${$}
73
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(J0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${r.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let X=Y.toString().trim().toLowerCase();_0.stdin.removeListener("data",A);try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!1)}catch{}_0.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof _0.stdin.setRawMode==="function")_0.stdin.setRawMode(!0)}catch{}_0.stdin.resume(),_0.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let X=/%([sdijfo%])/g,J=0;if(A=$.replace(X,(U,W)=>{if(W==="%")return"%";if(J>=w.length)return U;let f=w[J++];switch(W){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return U}}),J<w.length)A+=` ${w.slice(J).map((U)=>typeof U==="object"?JSON.stringify(U,null,2):String(U)).join(" ")}`}if(this.fancy&&!J0()){let X=this.options.showTags!==!1&&this.name?r.gray(this.formatTag(this.name)):"",J=r.blue("◐");console.error(`${J} ${X} ${r.cyan(A)}`)}let Y=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
74
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(Y)}progress($,w=""){if(!this.enabled||!this.fancy||J0()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(Y,X)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,Y)),X!==void 0)this.activeProgressBar.message=X;let J=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,J)},finish:(Y)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,Y!==void 0)this.activeProgressBar.message=Y;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(Y,X="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J0())return;_0.stdout.write(`${"\r".padEnd(_0.stdout.columns||80)}\r`),this.log(X,Y),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||J0()||!_0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),X=$.barLength-Y,J=r.green("━".repeat(Y)),U=r.gray("━".repeat(X)),W=`[${J}${U}]`,f=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",j=w||A===100?r.green("✓"):r.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${r.gray(this.formatTag(this.name))}`:"",E=`\r${j}${z} ${W} ${f}${B}`,F=_0.stdout.columns||80,T=" ".repeat(Math.max(0,F-E.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${E}${T}`,_0.stdout.write($.lastRenderedLine),w)_0.stdout.write(`
75
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||J0()||!_0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(J0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await MY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=A1(this.config.logDirectory,Y);if($.before)try{if((await w1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await IY(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function PY($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&l(w[0])&&"id"in w[0]&&w[0].id===3&&l(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(l(w)&&l($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(l($)&&"arr"in $&&Array.isArray($.arr)&&l(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&l(w[0])&&l($[0])){let Y=[...w];for(let X of $)if(l(X)&&"name"in X){if(!Y.find((J)=>l(J)&&("name"in J)&&J.name===X.name))Y.push(X)}else if(l(X)&&"path"in X){if(!Y.find((J)=>l(J)&&("path"in J)&&J.path===X.path))Y.push(X)}else if(!Y.some((J)=>aY(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!l(w)||!l($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(l(X)&&l(A[Y]))A[Y]=PY(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&l(X[0])&&l(A[Y][0])){let J=[...X];for(let U of A[Y])if(l(U)&&"name"in U){if(!J.find((W)=>l(W)&&("name"in W)&&W.name===U.name))J.push(U)}else if(l(U)&&"path"in U){if(!J.find((W)=>l(W)&&("path"in W)&&W.path===U.path))J.push(U)}else if(!J.some((W)=>aY(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function FU($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:PY($,w);if(Array.isArray($))return A==="replace"?w:PY($,w);if(!l(w)||!l($))return w;let Y={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[X],U=Y[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(A==="replace")Y[X]=J;else Y[X]=PY(U,J);else if(l(J)&&l(U))Y[X]=FU(U,J,A);else Y[X]=J}return Y}function aY($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!aY($[A],w[A]))return!1;return!0}if(l($)&&l(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!aY($[X],w[X]))return!1}return!0}return!1}function l($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function DY($,w,A="replace"){if(!$9($))return null;try{let Y=await import($),X=Y.default||Y;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return FU(w,X,A)}catch{return null}}catch{return null}}function fK($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${z.map(E).join("_")}`,T=`${Y}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(A)D0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=J(j,z);else{let K=$A.env[F]||$A.env[T];if(K!==void 0){if(A)D0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((N)=>N.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return J(X)}async function WK({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let f=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?fK($,X,J):X,B=A||$A.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)D0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),E=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,c0(B,"config"),c0(B,".config"),Y?c0(B,Y):void 0].filter(Boolean)));for(let H of K){if(J)D0.info(`Searching for configuration in: ${H}`);let N=[c0(B,"config"),c0(B,".config")].concat(Y?[c0(B,Y)]:[]).includes(H)?[...z,...E,...F,...T]:[...E,...z,...T,...F];for(let R of N)for(let M of j){let y=c0(H,`${R}${M}`),I=await DY(y,f,W);if(I!==null){if(J)D0.success(`Configuration loaded from: ${y}`);return I}}}if($){let H=c0(yJ(),".config",$),N=["config",`${$}.config`];if(w)N.push(`${w}.config`);if(J)D0.info(`Checking user config directory: ${H}`);for(let R of N)for(let M of j){let y=c0(H,`${R}${M}`),I=await DY(y,f,W);if(I!==null){if(J)D0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let H=c0(yJ(),".config"),N=[`.${$}.config`];if(w)N.push(`.${w}.config`);if(J)D0.info(`Checking user config directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=c0(H,`${R}${M}`),I=await DY(y,f,W);if(I!==null){if(J)D0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let H=yJ(),N=[`.${$}.config`,`.${$}`];if(w)N.push(`.${w}.config`),N.push(`.${w}`);if(J)D0.info(`Checking user home directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=c0(H,`${R}${M}`),I=await DY(y,f,W);if(I!==null){if(J)D0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let H=c0(B,"package.json");if($9(H)){let N=await import(H),R=N[$];if(!R&&w){if(R=N[w],R&&J)D0.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)D0.success(`Configuration loaded from package.json: ${R===N[$]?$:w}`);return FU(f,R,W)}catch(M){if(J)D0.warn("Failed to merge package.json config:",M)}}}catch(H){if(J)D0.warn("Failed to load package.json:",H)}if(J)D0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function BK($,w={}){let A=dY.cwd();while(A.includes("storage"))A=eB(A,"..");let Y=eB(A,$||"");if(w?.relative)return E6(dY.cwd(),Y);return Y}async function jK(){try{let $=await WK({name:"clarity",alias:"logging",defaultConfig:iY,cwd:dY.cwd()});return{...iY,...$||{}}}catch{return iY}}function H0(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function zK(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c$<"u"){let $=c$.type;if($==="renderer"||$==="worker")return!1;return!!(c$.versions&&(c$.versions.node||c$.versions.bun))}return!1}class U9{async format($){let w=await zK(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:U1.pid,hostname:w(),environment:U1.env.NODE_ENV||"development",platform:U1.platform,version:U1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:U1.env.NODE_ENV||U1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class sY{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...aJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new U9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...cY,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...cY};return{...cY,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:aJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!H0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,X=0,J=3,U=1000;while(X<J)try{try{try{await L6(this.config.logDirectory,jj.F_OK|jj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await O6(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P$.from($);try{if(!yY(this.currentLogFile))await SJ(this.currentLogFile,"",{mode:420});if(Y=Bj(this.currentLogFile,"a",420),V6(Y,W,{flag:"a"}),Wj(Y),Y!==void 0)QJ(Y),Y=void 0;if((await X1(this.currentLogFile)).size===0){if(await SJ(this.currentLogFile,W,{flag:"w",mode:420}),(await X1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(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((E)=>setTimeout(E,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(Y!==void 0)try{QJ(Y)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}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 f=U*2**(X-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return 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 $=new Date().toISOString().split("T")[0];return J1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(H0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,X);if(Y.length>J)for(let[U]of Y.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return OJ(16).toString("hex")}generateKey(){return OJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=OJ(16),Y=y6("aes-256-gcm",w,A),X=P$.isBuffer($)?$:P$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=P$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=Fj(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(P$.from(P$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(H0())return;if(!this.shouldWriteToFile())return;let $=await X1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await CY(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await X1(A).catch(()=>null))try{if(await zj(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await hY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await SJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await X1(A).catch(()=>null))await zj(A,J)}if(this.currentLogFile=Y,w.maxFiles){let X=(await CY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await hY(J1(this.config.logDirectory,J))}}}async compressLogFile($,w){let A=fj($),Y=h6(w),X=Fj();await _6(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),yY(this.currentLogFile))try{let $=Bj(this.currentLogFile,"r+");Wj($),QJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!H0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await CY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await hY(J1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||H0())return!1;let $=typeof g.env.NO_COLOR<"u",w=g.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=g.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${b.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=b.underline(b.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\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}),w=w.replace(/`([^`]+)`/g,(A,Y)=>b.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>b.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>b.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>b.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>b.strikethrough(Y)),w}supportsHyperlinks(){if(H0())return!1;let $=g.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=g.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(Q6(w)||w.startsWith("./")||w.startsWith("../"))w=S6(w);else return null;return yY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":T9[$],E=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:b.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:b.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
76
- `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:b.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!H0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let j=`${J} ${this.environment}.${$.toUpperCase()}: ${B}
70
+ `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!X0()){let Y=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:a.blue("◐"),tag:Y,message:`${a.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),f=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)f+=` ${JSON.stringify(Y)}`;if(f+=`
71
+ `,f=f.replace(this.ANSI_PATTERN,""),this.fancy&&!X0()){let B=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:a.green("✓"),tag:B,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!X0())console.error(f.trim());await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new oA(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(X0())throw Error("createReadStream is not supported in browser environments");if(!x8(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Fj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Ww.isBuffer($)?$:Ww.from($,"base64"),U=A.slice(0,16),X=A.slice(-16),J=A.slice(16,-16),W=SE("aes-256-gcm",Y,U);return W.setAuthTag(X),Ww.concat([W.update(J),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return X0()}isServerMode(){return!X0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!X0()){let X=$.split(`
72
+ `),J=Math.max(...X.map((j)=>j.length))+2,W=`┌${"─".repeat(J)}┐`,f=`└${"─".repeat(J)}┘`,B=X.map((j)=>{let z=" ".repeat(J-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:a.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:a.cyan(f),showTimestamp:!1}))}else if(!X0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let U=`${A} ${this.environment}.INFO: [BOX] ${$}
73
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(X0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${a.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();O0.stdin.removeListener("data",Y);try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!1)}catch{}O0.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof O0.stdin.setRawMode==="function")O0.stdin.setRawMode(!0)}catch{}O0.stdin.resume(),O0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,X=0;if(Y=$.replace(U,(J,W)=>{if(W==="%")return"%";if(X>=w.length)return J;let f=w[X++];switch(W){case"s":return String(f);case"d":case"i":return Number(f).toString();case"j":case"o":return JSON.stringify(f,null,2);default:return J}}),X<w.length)Y+=` ${w.slice(X).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`}if(this.fancy&&!X0()){let U=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",X=a.blue("◐");console.error(`${X} ${U} ${a.cyan(Y)}`)}let A=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
74
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(A)}progress($,w=""){if(!this.enabled||!this.fancy||X0()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(A,U)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,A)),U!==void 0)this.activeProgressBar.message=U;let X=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,X)},finish:(A)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,A!==void 0)this.activeProgressBar.message=A;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(A,U="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||X0())return;O0.stdout.write(`${"\r".padEnd(O0.stdout.columns||80)}\r`),this.log(U,A),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||X0()||!O0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=a.green("━".repeat(A)),J=a.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=w||Y===100?a.green("✓"):a.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=O0.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,O0.stdout.write($.lastRenderedLine),w)O0.stdout.write(`
75
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||X0()||!O0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(X0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await CA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let U=w1(this.config.logDirectory,A);if($.before)try{if((await $1(U)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${U}:`,X);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await hA(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function iA($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&l(w[0])&&"id"in w[0]&&w[0].id===3&&l(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(l(w)&&l($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(l($)&&"arr"in $&&Array.isArray($.arr)&&l(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&l(w[0])&&l($[0])){let A=[...w];for(let U of $)if(l(U)&&"name"in U){if(!A.find((X)=>l(X)&&("name"in X)&&X.name===U.name))A.push(U)}else if(l(U)&&"path"in U){if(!A.find((X)=>l(X)&&("path"in X)&&X.path===U.path))A.push(U)}else if(!A.some((X)=>eA(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!l(w)||!l($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(l(U)&&l(Y[A]))Y[A]=iA(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&l(U[0])&&l(Y[A][0])){let X=[...U];for(let J of Y[A])if(l(J)&&"name"in J){if(!X.find((W)=>l(W)&&("name"in W)&&W.name===J.name))X.push(J)}else if(l(J)&&"path"in J){if(!X.find((W)=>l(W)&&("path"in W)&&W.path===J.path))X.push(J)}else if(!X.some((W)=>eA(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function IJ($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:iA($,w);if(Array.isArray($))return Y==="replace"?w:iA($,w);if(!l(w)||!l($))return w;let A={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let X=w[U],J=A[U];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(J))if(Y==="replace")A[U]=X;else A[U]=iA(J,X);else if(l(X)&&l(J))A[U]=IJ(J,X,Y);else A[U]=X}return A}function eA($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!eA($[Y],w[Y]))return!1;return!0}if(l($)&&l(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!eA($[U],w[U]))return!1}return!0}return!1}function l($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function PA($,w,Y="replace"){if(!Bz($))return null;try{let A=await import($),U=A.default||A;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return IJ(w,U,Y)}catch{return null}}catch{return null}}function RK($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),U={...w};function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${z.map(G).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)_0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=X(j,z);else{let K=UY.env[F]||UY.env[T];if(K!==void 0){if(Y)_0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((q)=>q.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return X(U)}async function MK({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:U,verbose:X=!1,checkEnv:J=!0,arrayStrategy:W="replace"}){let f=J&&typeof U==="object"&&U!==null&&!Array.isArray(U)?RK($,U,X):U,B=Y||UY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(X)_0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),G=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,i0(B,"config"),i0(B,".config"),A?i0(B,A):void 0].filter(Boolean)));for(let H of K){if(X)_0.info(`Searching for configuration in: ${H}`);let q=[i0(B,"config"),i0(B,".config")].concat(A?[i0(B,A)]:[]).includes(H)?[...z,...G,...F,...T]:[...G,...z,...T,...F];for(let M of q)for(let I of j){let h=i0(H,`${M}${I}`),N=await PA(h,f,W);if(N!==null){if(X)_0.success(`Configuration loaded from: ${h}`);return N}}}if($){let H=i0(k8(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(X)_0.info(`Checking user config directory: ${H}`);for(let M of q)for(let I of j){let h=i0(H,`${M}${I}`),N=await PA(h,f,W);if(N!==null){if(X)_0.success(`Configuration loaded from user config directory: ${h}`);return N}}}if($){let H=i0(k8(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(X)_0.info(`Checking user config directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=i0(H,`${M}${I}`),N=await PA(h,f,W);if(N!==null){if(X)_0.success(`Configuration loaded from user config directory dotfile: ${h}`);return N}}}if($){let H=k8(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(X)_0.info(`Checking user home directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=i0(H,`${M}${I}`),N=await PA(h,f,W);if(N!==null){if(X)_0.success(`Configuration loaded from user home directory: ${h}`);return N}}}try{let H=i0(B,"package.json");if(Bz(H)){let q=await import(H),M=q[$];if(!M&&w){if(M=q[w],M&&X)_0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(X)_0.success(`Configuration loaded from package.json: ${M===q[$]?$:w}`);return IJ(f,M,W)}catch(I){if(X)_0.warn("Failed to merge package.json config:",I)}}}catch(H){if(X)_0.warn("Failed to load package.json:",H)}if(X)_0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function IK($,w={}){let Y=nA.cwd();while(Y.includes("storage"))Y=jj(Y,"..");let A=jj(Y,$||"");if(w?.relative)return VE(nA.cwd(),A);return A}async function yK(){try{let $=await MK({name:"clarity",alias:"logging",defaultConfig:mA,cwd:nA.cwd()});return{...mA,...$||{}}}catch{return mA}}function T0(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function CK(){if(c$.env.NODE_ENV==="test"||c$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof c$<"u"){let $=c$.type;if($==="renderer"||$==="worker")return!1;return!!(c$.versions&&(c$.versions.node||c$.versions.bun))}return!1}class Kz{async format($){let w=await CK(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:X1.pid,hostname:w(),environment:X1.env.NODE_ENV||"development",platform:X1.platform,version:X1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:X1.env.NODE_ENV||X1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class $U{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...XJ},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Kz,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??d.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...dA,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...dA};return{...dA,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:XJ.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!T0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,U=0,X=3,J=1000;while(U<X)try{try{try{await cE(this.config.logDirectory,Mj.F_OK|Mj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await vE(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:P$.from($);try{if(!VA(this.currentLogFile))await i8(this.currentLogFile,"",{mode:420});if(A=Rj(this.currentLogFile,"a",420),iE(A,W,{flag:"a"}),qj(A),A!==void 0)u8(A),A=void 0;if((await A1(this.currentLogFile)).size===0){if(await i8(this.currentLogFile,W,{flag:"w",mode:420}),(await A1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<X-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${X}:`,j);let z=J*2**U;await new Promise((G)=>setTimeout(G,z)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{u8(A)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(W){if(U===X-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}U++;let f=J*2**(U-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return U1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return U1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return U1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(T0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,J],[,W])=>W.createdAt.getTime()-J.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,U);if(A.length>X)for(let[J]of A.slice(X))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return b8(16).toString("hex")}generateKey(){return b8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=b8(16),A=PE("aes-256-gcm",w,Y),U=P$.isBuffer($)?$:P$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=P$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=yj(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(P$.from(P$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(T0())return;if(!this.shouldWriteToFile())return;let $=await A1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await LA(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await A1(Y).catch(()=>null))try{if(await Ij(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await QA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await i8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await A1(Y).catch(()=>null))await Ij(Y,X)}if(this.currentLogFile=A,w.maxFiles){let U=(await LA(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,J)=>J.localeCompare(X));for(let X of U.slice(w.maxFiles))await QA(U1(this.config.logDirectory,X))}}}async compressLogFile($,w){let Y=Nj($),A=uE(w),U=yj();await gE(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),VA(this.currentLogFile))try{let $=Rj(this.currentLogFile,"r+");qj($),u8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!T0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await LA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await QA(U1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?P.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||T0())return!1;let $=typeof d.env.NO_COLOR<"u",w=d.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof d.stderr<"u"&&d.stderr.isTTY||typeof d.stdout<"u"&&d.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=d.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${P.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=P.underline(P.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>P.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>P.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>P.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>P.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>P.strikethrough(A)),w}supportsHyperlinks(){if(T0())return!1;let $=d.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=d.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(mE(w)||w.startsWith("./")||w.startsWith("../"))w=dE(w);else return null;return VA(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":hz[$],G=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:P.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:P.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
76
+ `);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:P.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!T0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
77
77
  `;if(W)j+=`${W}
78
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!H0()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(X,J)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,X),this.activeProgressBar.total),J!==void 0)this.activeProgressBar.message=J;if(this.shouldStyleConsole()&&!H0()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!H0()&&g.stdout.isTTY)g.stdout.write(`
79
- `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!H0()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":b.blue("◐"),tag:A,message:`${b.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),X=Math.round(Y-w),J=`${$} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),f=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(A)f+=` ${JSON.stringify(A)}`;if(f+=`
80
- `,f=f.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:W,icon:this.options.showIcons===!1?"":b.green("✓"),tag:B,message:`${J}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!H0())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new sY(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(H0())throw Error("createReadStream is not supported in browser environments");if(!yY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return fj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=P$.isBuffer($)?$:P$.from($,"base64"),X=Y.subarray(0,16),J=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=C6("aes-256-gcm",A,X);W.setAuthTag(J);let f=W.update(U),B=W.final(),j=f.length+B.length,z=P$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return H0()}isServerMode(){return!H0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=X.split(`
81
- `),f=Math.max(...W.map((E)=>E.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((E)=>{return this.formatConsoleMessage({timestamp:A,message:b.cyan(E),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(B),showTimestamp:!1})),z.forEach((E)=>console.error(E)),console.error(this.formatConsoleMessage({timestamp:A,message:b.cyan(j),showTimestamp:!1}))}else if(!H0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${J}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${J}
82
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(H0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${b.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let X=Y.toString().trim().toLowerCase();g.stdin.removeListener("data",A);try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!1)}catch{}g.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!0)}catch{}g.stdin.resume(),g.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,W=0;if(A=$.replace(U,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)A+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:Y,fileText:X}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let U=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${W}${U} ${b.cyan(Y)}`)}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()||!g.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),X=$.barLength-Y,J=b.green("━".repeat(Y)),U=b.gray("━".repeat(X)),W=`[${J}${U}]`,f=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?b.green("✓"):b.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",E=`\r${j}${z} ${W} ${f}${B}`,F=g.stdout.columns||80,T=" ".repeat(Math.max(0,F-E.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${E}${T}`,g.stdout.write($.lastRenderedLine),w)g.stdout.write(`
84
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||H0()||!g.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(H0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await CY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=J1(this.config.logDirectory,Y);if($.before)try{if((await X1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await hY(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function f9($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(f){if(U=f instanceof Error?f:Error(String(f)),W===A||!X(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function W9($){return $ instanceof $$}function FK($){return $ instanceof oY}function EK($){if(W9($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}class fX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:f=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=Y||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return XA.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=U.map((j)=>this.formatEnvKey(j,Y.useCamelCase)),f=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,A,Y);else{let j=VY.env[f]||(B?VY.env[B]:void 0);if(j!==void 0){if(Y.verbose){let z=VY.env[f]?f:B}try{$[X]=this.parseEnvironmentValue(j,typeof J,f,Y.customParsers,Y.configName)}catch(z){if(z instanceof eY)throw z;throw jw.envVar(f,j,typeof J,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,X){for(let[J,U]of Object.entries(Y))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw jw.envVar(A,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,X]of Object.entries(VY.env))if(Y.startsWith(A)&&X!==void 0)w[Y]=X;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(X){Y.push(`Cannot parse value "${w}" as ${A}: ${X}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:X="text"}=A,J=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=`${A}_${U.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,A,Y);else Y.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
78
+ `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(U,X)=>{},finish:(U)=>{},interrupt:(U,X)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!T0()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,X)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),X!==void 0)this.activeProgressBar.message=X;if(this.shouldStyleConsole()&&!T0()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,X="info")=>{if(!T0()&&d.stdout.isTTY)d.stdout.write(`
79
+ `);if(this[X==="warning"?"warn":X](U),this.activeProgressBar&&this.shouldStyleConsole()&&!T0()&&d.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":P.blue("◐"),tag:Y,message:`${P.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),f=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)f+=` ${JSON.stringify(Y)}`;if(f+=`
80
+ `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":P.green("✓"),tag:B,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!T0())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new $U(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(T0())throw Error("createReadStream is not supported in browser environments");if(!VA(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Nj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=P$.isBuffer($)?$:P$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=bE("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=P$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return T0()}isServerMode(){return!T0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
81
+ `),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:P.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:P.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:P.cyan(j),showTimestamp:!1}))}else if(!T0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
82
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(T0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${P.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();d.stdin.removeListener("data",Y);try{if(typeof d.stdin.setRawMode==="function")d.stdin.setRawMode(!1)}catch{}d.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof d.stdin.setRawMode==="function")d.stdin.setRawMode(!0)}catch{}d.stdin.resume(),d.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,W=0;if(Y=$.replace(J,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)Y+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?P.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${P.blue("◐")} `;console.error(`${W}${J} ${P.cyan(A)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
83
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!d.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=P.green("━".repeat(A)),J=P.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?P.green("✓"):P.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${P.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=d.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,d.stdout.write($.lastRenderedLine),w)d.stdout.write(`
84
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||T0()||!d.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(T0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await LA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let U=U1(this.config.logDirectory,A);if($.before)try{if((await A1(U)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${U}:`,X);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await QA(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function Tz($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}function Hz($){return $ instanceof s0}function hK($){return $ instanceof wU}function VK($){if(Hz($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((w)=>$.message.toLowerCase().includes(w.toLowerCase()))}class jU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return WY.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=OA.env[f]||(B?OA.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=OA.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof YU)throw z;throw jw.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw jw.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(OA.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
85
85
 
86
- `;for(let Y of $)A+=`${Y.key}
87
- `,A+=` Type: ${Y.type}
88
- `,A+=` Description: ${Y.description}
89
- `,A+=` Example: ${Y.example}
86
+ `;for(let A of $)Y+=`${A.key}
87
+ `,Y+=` Type: ${A.type}
88
+ `,Y+=` Description: ${A.description}
89
+ `,Y+=` Example: ${A.example}
90
90
 
91
- `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
91
+ `;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
92
92
 
93
- `;A+=`| Variable | Type | Description | Example |
94
- `,A+=`|----------|------|-------------|----------|
95
- `;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
96
- `;return A}}function GK($,w){let A=E9("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function B9($,w,A={}){return j9($,w,A,new WeakMap)}function j9($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return z9($,w,X,Y);if(!j$(w)||!j$($))return w;return NK($,w,A,Y)}function z9($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return KK($,w);case"smart":return TK($,w,Y);default:return w}return w}function KK($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>tJ(X,Y)))A.push(Y);return A}function TK($,w,A){if(w.length===0)return $;if($.length===0)return w;if(j$(w[0])&&j$($[0]))return HK($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function HK($,w,A){let Y=[...w];for(let X of $){if(!j$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((f)=>j$(f)&&(W in f)&&f[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function NK($,w,A,Y){let X=w;if(j$(X)&&Y.has(X))return Y.get(X);let J={...$};if(j$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(j$(W)&&j$(f))J[U]=j9(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=z9(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function EU($,w,A="replace"){return B9($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function tJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!tJ($[A],w[A]))return!1;return!0}if(j$($)&&j$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!tJ($[X],w[X]))return!1}return!0}return!1}function j$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class WX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=z1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!LY($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new wA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new wA($,Error("Configuration must export a valid object"),"unknown");let T={config:EU(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)z1.setWithFileCheck("file",T,$,J);return T}catch(B){throw B instanceof Error?jw.configLoad($,B):jw.configLoad($,Error(String(B)))}};if(U)return XA.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(_J(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return f9(async()=>{return LY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!LY($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=_J($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=_J($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!LY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class GU{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await XA.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!k6(w))throw new AA(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new AA(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:N9},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class KU{fileLoader=new WX;envProcessor=new fX;validator=new GU;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;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(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))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: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)q$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw q$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||Vw.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(v0(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw jw.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?s1($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)q$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)q$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?s1($,A,X):A,W=[v0($1(),".config",$),v0($1(),".config"),$1()];for(let f of W){if(X)q$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)q$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?s1($,Y,J):Y;try{let f=v0(A,"package.json");if(!lJ(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)q$.success(`Configuration loaded from package.json: ${z}`);return{config:EU(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)q$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:s1($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw jw.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return z1.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);z1.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,v0($,"config"),v0($,".config"),w?v0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(v0(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[v0($1(),".config",$),v0($1(),".config"),$1()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function Mj($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||A}async function RK($){return d$.loadConfig({...$,__strictErrorHandling:!0})}async function F9($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await d$.loadConfig($);else Y=await d$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let X=Y instanceof Error?Y.name:"UnknownError",J=Y instanceof Error?Y.message:String(Y);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)q$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let U=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await d$.applyEnvironmentVariables(U.name||"",w,!0,U.verbose||!1))?.config??w;return w}}async function qK($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await d$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&Mj(A)))return(await d$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await d$.loadConfig({...$,cwd:$.cwd||Vw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&Mj(w)))return(await d$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function MK($,w,A="replace"){let Y=new WX;try{let X=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function s1($,w,A=!1){let Y=new fX,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=Vw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}function IK($){let w=v0(Vw.cwd(),$.configDir),A=v0(Vw.cwd(),$.generatedDir),Y=v0(A,"config-types.ts");if(!lJ(oB(Y)))B6(oB(Y),{recursive:!0,mode:511});let X=lJ(w)?j6(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${sK}
97
- export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
98
- `;z6(Y,J,{mode:438})}function yK($){let w=null,A=null,Y=()=>{if(!A)A=F9($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)q$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return A},X="defaultConfig"in $?$.defaultConfig:{};return w=X,Y(),new Proxy({},{get(J,U){if(w)return w[U];let W=X[U];return Y(),W},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,W){if(!w)w={...X};return w[U]=W,!0}})}function CK($){let w=Ej(x6.cwd(),$?.configDir||"./config");function A(){if(!D6(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=Z6(w).filter((f)=>X.has(kJ(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),W=new Map;for(let{base:f,file:B}of U){let j=kJ(B).toLowerCase(),z=W.get(f);if(!z){W.set(f,B);continue}let E=kJ(z).toLowerCase();if(J.indexOf(j)<J.indexOf(E))W.set(f,B)}return Array.from(W.entries()).map(([f,B])=>({base:f,file:B})).sort((f,B)=>f.base.localeCompare(B.base))}function Y(){let X=A(),J=X.map((f)=>f.base),U=J.length?J.map((f)=>`'${f}'`).join(" | "):"string",W=X.length?`{
99
- ${X.map((f)=>{let B=Ej(w,f.file).replace(/\\/g,"/");return` '${f.base}': typeof import('${B}').default`}).join(`,
93
+ `;Y+=`| Variable | Type | Description | Example |
94
+ `,Y+=`|----------|------|-------------|----------|
95
+ `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
96
+ `;return Y}}function LK($,w){let Y=Iz("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function Nz($,w,Y={}){return qz($,w,Y,new WeakMap)}function qz($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return Rz($,w,U,A);if(!J$(w)||!J$($))return w;return _K($,w,Y,A)}function Rz($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return QK($,w);case"smart":return OK($,w,A);default:return w}return w}function QK($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>AJ(U,A)))Y.push(A);return Y}function OK($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(J$(w[0])&&J$($[0]))return SK($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function SK($,w,Y){let A=[...w];for(let U of $){if(!J$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((f)=>J$(f)&&(W in f)&&f[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function _K($,w,Y,A){let U=w;if(J$(U)&&A.has(U))return A.get(U);let X={...$};if(J$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(J$(W)&&J$(f))X[J]=qz(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=Rz(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function yJ($,w,Y="replace"){return Nz($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function AJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!AJ($[Y],w[Y]))return!1;return!0}if(J$($)&&J$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!AJ($[U],w[U]))return!1}return!0}return!1}function J$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class zU{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=j1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!SA($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new XY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new XY($,Error("Configuration must export a valid object"),"unknown");let T={config:yJ(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)j1.setWithFileCheck("file",T,$,X);return T}catch(B){throw B instanceof Error?jw.configLoad($,B):jw.configLoad($,Error(String(B)))}};if(J)return WY.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(c8(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return Tz(async()=>{return SA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!SA($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=c8($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=c8($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!SA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class CJ{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await WY.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!lE(w))throw new JY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new JY(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:Lz},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class hJ{fileLoader=new zU;envProcessor=new jU;validator=new CJ;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)K$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw K$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||Vw.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(c0(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw jw.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?wY($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)K$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)K$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?wY($,Y,U):Y,W=[c0(ew(),".config",$),c0(ew(),".config"),ew()];for(let f of W){if(U)K$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)K$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?wY($,A,X):A;try{let f=c0(Y,"package.json");if(!wJ(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)K$.success(`Configuration loaded from package.json: ${z}`);return{config:yJ(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)K$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:wY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw jw.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return j1.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);j1.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,c0($,"config"),c0($,".config"),w?c0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(c0(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[c0(ew(),".config",$),c0(ew(),".config"),ew()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function kj($){let w=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return w||Y}async function kK($){return d$.loadConfig({...$,__strictErrorHandling:!0})}async function Mz($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await d$.loadConfig($);else A=await d$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}catch(A){let U=A instanceof Error?A.name:"UnknownError",X=A instanceof Error?A.message:String(A);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||X.includes("config"))&&$.verbose)K$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let J=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await d$.applyEnvironmentVariables(J.name||"",w,!0,J.verbose||!1))?.config??w;return w}}async function DK($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await d$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&kj(Y)))return(await d$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await d$.loadConfig({...$,cwd:$.cwd||Vw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&kj(w)))return(await d$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function ZK($,w,Y="replace"){let A=new zU;try{let U=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function wY($,w,Y=!1){let A=new jU,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=Vw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}function xK($){let w=c0(Vw.cwd(),$.configDir),Y=c0(Vw.cwd(),$.generatedDir),A=c0(Y,"config-types.ts");if(!wJ(Bj(A)))IE(Bj(A),{recursive:!0,mode:511});let U=wJ(w)?yE(w).map((J)=>J.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${j7}
97
+ export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
98
+ `;CE(A,X,{mode:438})}function PK($){let w=null,Y=null,A=()=>{if(!Y)Y=Mz($).then((X)=>{return w=X,X},(X)=>{let J="defaultConfig"in $?$.defaultConfig:{};if(w=J,"verbose"in $&&$.verbose)K$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return J});return Y},U="defaultConfig"in $?$.defaultConfig:{};return w=U,A(),new Proxy({},{get(X,J){if(w)return w[J];let W=U[J];return A(),W},has(X,J){return J in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(X,J){return Object.getOwnPropertyDescriptor(w||U,J)},set(X,J,W){if(!w)w={...U};return w[J]=W,!0}})}function bK($){let w=Cj(tE.cwd(),$?.configDir||"./config");function Y(){if(!nE(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],J=pE(w).filter((f)=>U.has(v8(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),W=new Map;for(let{base:f,file:B}of J){let j=v8(B).toLowerCase(),z=W.get(f);if(!z){W.set(f,B);continue}let G=v8(z).toLowerCase();if(X.indexOf(j)<X.indexOf(G))W.set(f,B)}return Array.from(W.entries()).map(([f,B])=>({base:f,file:B})).sort((f,B)=>f.base.localeCompare(B.base))}function A(){let U=Y(),X=U.map((f)=>f.base),J=X.length?X.map((f)=>`'${f}'`).join(" | "):"string",W=U.length?`{
99
+ ${U.map((f)=>{let B=Cj(w,f.file).replace(/\\/g,"/");return` '${f.base}': typeof import('${B}').default`}).join(`,
100
100
  `)}
101
- }`:"Record<string, any>";return`export type ConfigNames = ${U}
101
+ }`:"Record<string, any>";return`export type ConfigNames = ${J}
102
102
  export type ConfigByName = ${W}
103
103
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
104
104
  export type ConfigOf = Config
105
- `}return{name:"bunfig-plugin",setup(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:Y(),loader:"ts"}})}}}function eK($,w={}){let A=lY.cwd();while(A.includes("storage"))A=Gj(A,"..");let Y=Gj(A,$||"");if(w?.relative)return b6(lY.cwd(),Y);return Y}function R0(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wT(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof v$<"u"){let $=v$.type;if($==="renderer"||$==="worker")return!1;return!!(v$.versions&&(v$.versions.node||v$.versions.bun))}return!1}class I9{async format($){let w=await wT(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:B1.pid,hostname:w(),environment:B1.env.NODE_ENV||"development",platform:B1.platform,version:B1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:B1.env.NODE_ENV||B1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class BX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...$X},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new I9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??n.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...vJ,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...vJ};return{...vJ,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:$X.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!R0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let Y,X=0,J=3,U=1000;while(X<J)try{try{try{await m6(this.config.logDirectory,Nj.F_OK|Nj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await d6(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:b$.from($);try{if(!OY(this.currentLogFile))await xJ(this.currentLogFile,"",{mode:420});if(Y=Hj(this.currentLogFile,"a",420),v6(Y,W,{flag:"a"}),Tj(Y),Y!==void 0)ZJ(Y),Y=void 0;if((await f1(this.currentLogFile)).size===0){if(await xJ(this.currentLogFile,W,{flag:"w",mode:420}),(await f1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;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((E)=>setTimeout(E,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(Y!==void 0)try{ZJ(Y)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}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 f=U*2**(X-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let A=this.pendingOperations.length-1;try{await w}catch(Y){throw console.error("Debug: [writeToFile] Error in operation:",Y),Y}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return W1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return W1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return W1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(R0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,A=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((Y)=>{console.error("Error rotating keys:",Y)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),A=this.generateKey();this.currentKeyId=w,this.keys.set(w,A),this.encryptionKeys.set(w,{key:A,createdAt:new Date});let Y=Array.from(this.encryptionKeys.entries()).sort(([,U],[,W])=>W.createdAt.getTime()-U.createdAt.getTime()),X=typeof $.maxKeys==="number"?$.maxKeys:1,J=Math.max(1,X);if(Y.length>J)for(let[U]of Y.slice(J))this.encryptionKeys.delete(U),this.keys.delete(U)}generateKeyId(){return DJ(16).toString("hex")}generateKey(){return DJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=DJ(16),Y=u6("aes-256-gcm",w,A),X=b$.isBuffer($)?$:b$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=b$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=qj(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(b$.from(b$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(R0())return;if(!this.shouldWriteToFile())return;let $=await f1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await QY(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await f1(A).catch(()=>null))try{if(await Rj(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await SY(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await xJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await f1(A).catch(()=>null))await Rj(A,J)}if(this.currentLogFile=Y,w.maxFiles){let X=(await QY(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,U)=>U.localeCompare(J));for(let J of X.slice(w.maxFiles))await SY(W1(this.config.logDirectory,J))}}}async compressLogFile($,w){let A=Kj($),Y=c6(w),X=qj();await l6(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),OY(this.currentLogFile))try{let $=Hj(this.currentLogFile,"r+");Tj($),ZJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!R0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await QY(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await SY(W1(this.config.logDirectory,w))}catch(A){console.error(`Failed to delete temp file ${w}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||R0())return!1;let $=typeof n.env.NO_COLOR<"u",w=n.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof n.stderr<"u"&&n.stderr.isTTY||typeof n.stdout<"u"&&n.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=n.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${c.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=c.underline(c.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\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}),w=w.replace(/`([^`]+)`/g,(A,Y)=>c.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>c.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>c.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>c.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>c.strikethrough(Y)),w}supportsHyperlinks(){if(R0())return!1;let $=n.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=n.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(g6(w)||w.startsWith("./")||w.startsWith("../"))w=n6(w);else return null;return OY(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":UT[$],E=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:c.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:c.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
106
- `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:c.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!R0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}let j=`${J} ${this.environment}.${$.toUpperCase()}: ${B}
105
+ `}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function F7($,w={}){let Y=rA.cwd();while(Y.includes("storage"))Y=hj(Y,"..");let A=hj(Y,$||"");if(w?.relative)return aE(rA.cwd(),A);return A}function N0(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function E7(){if(v$.env.NODE_ENV==="test"||v$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof v$<"u"){let $=v$.type;if($==="renderer"||$==="worker")return!1;return!!(v$.versions&&(v$.versions.node||v$.versions.bun))}return!1}class _z{async format($){let w=await E7(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:W1.pid,hostname:w(),environment:W1.env.NODE_ENV||"development",platform:W1.platform,version:W1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:W1.env.NODE_ENV||W1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class FU{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...AU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new _z,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...a8,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...a8};return{...a8,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:AU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!N0()&&this.config.writeToFile===!0}async writeToFile($){let w=(async()=>{let A,U=0,X=3,J=1000;while(U<X)try{try{try{await wK(this.config.logDirectory,Oj.F_OK|Oj.W_OK)}catch(f){if(f instanceof Error&&"code"in f)if(f.code==="ENOENT")await YK(this.config.logDirectory,{recursive:!0,mode:493});else if(f.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw f;else throw f}}catch(f){throw console.error("Debug: [writeToFile] Failed to create log directory:",f),f}let W=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:b$.from($);try{if(!_A(this.currentLogFile))await g8(this.currentLogFile,"",{mode:420});if(A=Qj(this.currentLogFile,"a",420),$K(A,W,{flag:"a"}),Lj(A),A!==void 0)d8(A),A=void 0;if((await J1(this.currentLogFile)).size===0){if(await g8(this.currentLogFile,W,{flag:"w",mode:420}),(await J1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(f){let B=f;if(B.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(B.code)){if(U<X-1){let j=typeof B.message==="string"?B.message:"Unknown error";console.error(`Network error during write attempt ${U+1}/${X}:`,j);let z=J*2**U;await new Promise((G)=>setTimeout(G,z)),U++;continue}}if(B?.code&&["ENOSPC","EDQUOT"].includes(B.code))throw Error(`Disk quota exceeded or no space left on device: ${B.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",B),B}finally{if(A!==void 0)try{d8(A)}catch(f){console.error("Debug: [writeToFile] Error closing file descriptor:",f)}}}catch(W){if(U===X-1){let B=W,j=typeof B.message==="string"?B.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",j),W}U++;let f=J*2**(U-1);await new Promise((B)=>setTimeout(B,f))}})();this.pendingOperations.push(w);let Y=this.pendingOperations.length-1;try{await w}catch(A){throw console.error("Debug: [writeToFile] Error in operation:",A),A}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return f1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return f1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return f1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(N0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let $=this.config.rotation.keyRotation;if(!$?.enabled)return;let w=typeof $.interval==="number"?$.interval:60,Y=Math.max(w,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((A)=>{console.error("Error rotating keys:",A)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let $=this.config.rotation.keyRotation,w=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=w,this.keys.set(w,Y),this.encryptionKeys.set(w,{key:Y,createdAt:new Date});let A=Array.from(this.encryptionKeys.entries()).sort(([,J],[,W])=>W.createdAt.getTime()-J.createdAt.getTime()),U=typeof $.maxKeys==="number"?$.maxKeys:1,X=Math.max(1,U);if(A.length>X)for(let[J]of A.slice(X))this.encryptionKeys.delete(J),this.keys.delete(J)}generateKeyId(){return m8(16).toString("hex")}generateKey(){return m8(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=m8(16),A=sE("aes-256-gcm",w,Y),U=b$.isBuffer($)?$:b$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=b$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=_j(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(b$.from(b$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(N0())return;if(!this.shouldWriteToFile())return;let $=await J1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await kA(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await J1(Y).catch(()=>null))try{if(await Sj(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await DA(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await g8(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await J1(Y).catch(()=>null))await Sj(Y,X)}if(this.currentLogFile=A,w.maxFiles){let U=(await kA(this.config.logDirectory)).filter((X)=>X.startsWith(this.name)).sort((X,J)=>J.localeCompare(X));for(let X of U.slice(w.maxFiles))await DA(f1(this.config.logDirectory,X))}}}async compressLogFile($,w){let Y=Vj($),A=eE(w),U=_j();await XK(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),_A(this.currentLogFile))try{let $=Qj(this.currentLogFile,"r+");Lj($),d8($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!N0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let $=(await kA(this.config.logDirectory)).filter((w)=>(w.includes("temp")||w.includes(".tmp"))&&w.includes(this.name));for(let w of $)try{await DA(f1(this.config.logDirectory,w))}catch(Y){console.error(`Failed to delete temp file ${w}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?i.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||N0())return!1;let $=typeof g.env.NO_COLOR<"u",w=g.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=g.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${i.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=i.underline(i.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>i.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>i.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>i.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>i.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>i.strikethrough(A)),w}supportsHyperlinks(){if(N0())return!1;let $=g.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=g.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(AK(w)||w.startsWith("./")||w.startsWith("../"))w=UK(w);else return null;return _A(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":q7[$],G=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:i.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:i.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
106
+ `);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:i.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!N0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
107
107
  `;if(W)j+=`${W}
108
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(X,J)=>{},finish:(X)=>{},interrupt:(X,J)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!R0()&&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()&&!R0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(X)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,X)},interrupt:(X,J="info")=>{if(!R0()&&n.stdout.isTTY)n.stdout.write(`
109
- `);if(this[J==="warning"?"warn":J](X),this.activeProgressBar&&this.shouldStyleConsole()&&!R0()&&n.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":c.blue("◐"),tag:A,message:`${c.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),X=Math.round(Y-w),J=`${$} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),f=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(A)f+=` ${JSON.stringify(A)}`;if(f+=`
110
- `,f=f.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}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!R0())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new BX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(R0())throw Error("createReadStream is not supported in browser environments");if(!OY(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Kj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=b$.isBuffer($)?$:b$.from($,"base64"),X=Y.subarray(0,16),J=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=i6("aes-256-gcm",A,X);W.setAuthTag(J);let f=W.update(U),B=W.final(),j=f.length+B.length,z=b$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return R0()}isServerMode(){return!R0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=X.split(`
111
- `),f=Math.max(...W.map((E)=>E.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((E)=>{return this.formatConsoleMessage({timestamp:A,message:c.cyan(E),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:c.cyan(B),showTimestamp:!1})),z.forEach((E)=>console.error(E)),console.error(this.formatConsoleMessage({timestamp:A,message:c.cyan(j),showTimestamp:!1}))}else if(!R0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${J}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${J}
112
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(R0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${c.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let X=Y.toString().trim().toLowerCase();n.stdin.removeListener("data",A);try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!1)}catch{}n.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof n.stdin.setRawMode==="function")n.stdin.setRawMode(!0)}catch{}n.stdin.resume(),n.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,W=0;if(A=$.replace(U,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)A+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:Y,fileText:X}=this.buildOutputTexts(A);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(Y)}`)}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 A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),X=$.barLength-Y,J=c.green("━".repeat(Y)),U=c.gray("━".repeat(X)),W=`[${J}${U}]`,f=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?c.green("✓"):c.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",E=`\r${j}${z} ${W} ${f}${B}`,F=n.stdout.columns||80,T=" ".repeat(Math.max(0,F-E.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${E}${T}`,n.stdout.write($.lastRenderedLine),w)n.stdout.write(`
114
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||R0()||!n.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(R0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await QY(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let X=W1(this.config.logDirectory,Y);if($.before)try{if((await f1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}A.push(X)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await SY(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function fT($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(f){if(U=f instanceof Error?f:Error(String(f)),W===A||!X(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}class HU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:f=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=Y||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return WU.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=U.map((j)=>this.formatEnvKey(j,Y.useCamelCase)),f=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,A,Y);else{let j=_Y.env[f]||(B?_Y.env[B]:void 0);if(j!==void 0){if(Y.verbose){let z=_Y.env[f]?f:B}try{$[X]=this.parseEnvironmentValue(j,typeof J,f,Y.customParsers,Y.configName)}catch(z){if(z instanceof TU)throw z;throw F1.envVar(f,j,typeof J,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,X){for(let[J,U]of Object.entries(Y))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw F1.envVar(A,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,X]of Object.entries(_Y.env))if(Y.startsWith(A)&&X!==void 0)w[Y]=X;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(X){Y.push(`Cannot parse value "${w}" as ${A}: ${X}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:X="text"}=A,J=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=`${A}_${U.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,A,Y);else Y.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
108
+ `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(U,X)=>{},finish:(U)=>{},interrupt:(U,X)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!N0()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(U,X)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,U),this.activeProgressBar.total),X!==void 0)this.activeProgressBar.message=X;if(this.shouldStyleConsole()&&!N0()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(U)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,U)},interrupt:(U,X="info")=>{if(!N0()&&g.stdout.isTTY)g.stdout.write(`
109
+ `);if(this[X==="warning"?"warn":X](U),this.activeProgressBar&&this.shouldStyleConsole()&&!N0()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":i.blue("◐"),tag:Y,message:`${i.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),f=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)f+=` ${JSON.stringify(Y)}`;if(f+=`
110
+ `,f=f.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let B=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":i.green("✓"),tag:B,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!N0())console.error(f.trim());if(this.shouldWriteToFile())await this.writeToFile(f)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new FU(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(N0())throw Error("createReadStream is not supported in browser environments");if(!_A(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Vj(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=b$.isBuffer($)?$:b$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=oE("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=b$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return N0()}isServerMode(){return!N0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
111
+ `),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:i.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:i.cyan(j),showTimestamp:!1}))}else if(!N0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
112
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(N0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${i.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();g.stdin.removeListener("data",Y);try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!1)}catch{}g.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof g.stdin.setRawMode==="function")g.stdin.setRawMode(!0)}catch{}g.stdin.resume(),g.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,W=0;if(Y=$.replace(J,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)Y+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let J=this.options.showTags!==!1&&this.name?i.gray(this.formatTag(this.name)):"",W=this.options.showIcons===!1?"":`${i.blue("◐")} `;console.error(`${W}${J} ${i.cyan(A)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
113
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(X)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!g.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=i.green("━".repeat(A)),J=i.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?i.green("✓"):i.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${i.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=g.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,g.stdout.write($.lastRenderedLine),w)g.stdout.write(`
114
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||N0()||!g.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(N0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await kA(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let U=f1(this.config.logDirectory,A);if($.before)try{if((await J1(U)).mtime>=$.before)continue}catch(X){console.error(`Failed to get stats for file ${U}:`,X);continue}Y.push(U)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await DA(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function R7($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}class LJ{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return NJ.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=ZA.env[f]||(B?ZA.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=ZA.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof VJ)throw z;throw z1.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw z1.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(ZA.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
115
115
 
116
- `;for(let Y of $)A+=`${Y.key}
117
- `,A+=` Type: ${Y.type}
118
- `,A+=` Description: ${Y.description}
119
- `,A+=` Example: ${Y.example}
116
+ `;for(let A of $)Y+=`${A.key}
117
+ `,Y+=` Type: ${A.type}
118
+ `,Y+=` Description: ${A.description}
119
+ `,Y+=` Example: ${A.example}
120
120
 
121
- `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
121
+ `;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
122
122
 
123
- `;A+=`| Variable | Type | Description | Example |
124
- `,A+=`|----------|------|-------------|----------|
125
- `;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
126
- `;return A}}function WT($,w,A={}){return S9($,w,A,new WeakMap)}function S9($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return _9($,w,X,Y);if(!z$(w)||!z$($))return w;return FT($,w,A,Y)}function _9($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return BT($,w);case"smart":return jT($,w,Y);default:return w}return w}function BT($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>YU(X,Y)))A.push(Y);return A}function jT($,w,A){if(w.length===0)return $;if($.length===0)return w;if(z$(w[0])&&z$($[0]))return zT($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function zT($,w,A){let Y=[...w];for(let X of $){if(!z$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((f)=>z$(f)&&(W in f)&&f[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function FT($,w,A,Y){let X=w;if(z$(X)&&Y.has(X))return Y.get(X);let J={...$};if(z$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(z$(W)&&z$(f))J[U]=S9(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=_9(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function k9($,w,A="replace"){return WT($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function YU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!YU($[A],w[A]))return!1;return!0}if(z$($)&&z$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!YU($[X],w[X]))return!1}return!0}return!1}function z$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class D9{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=pY.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!kY($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new wX($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new wX($,Error("Configuration must export a valid object"),"unknown");let T={config:k9(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)pY.setWithFileCheck("file",T,$,J);return T}catch(B){throw B instanceof Error?F1.configLoad($,B):F1.configLoad($,Error(String(B)))}};if(U)return WU.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(PJ(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);let Y=w===void 0?[]:Array.isArray(w)?w:[w];for(let J of Y){if(!J)continue;if(A.push(J,`.${J}.config`,`${J}.config`,`.${J}`),$)A.push(`${$}.${J}.config`,`.${$}.${J}.config`)}let X=new Set;return A.filter((J)=>{if(!J||X.has(J))return!1;return X.add(J),!0})}checkFileAccess($){return fT(async()=>{return kY($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!kY($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=PJ($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=PJ($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!kY($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class Z9{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await WU.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!p6(w))throw new AX(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new AX(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:ET},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function GT($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((A)=>`"${A}"`).join(", ")}`}class x9{fileLoader=new D9;envProcessor=new HU;validator=new Z9;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;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(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))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: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)u$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let f=Date.now()-w;throw u$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||UX.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(B$(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw F1.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${GT(X)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?ZY($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)u$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)u$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?ZY($,A,X):A,W=[B$(ew(),".config",$),B$(ew(),".config"),ew()];for(let f of W){if(X)u$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)u$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?ZY($,Y,J):Y;try{let f=B$(A,"package.json");if(!f6(f))return null;let B={};try{B=JSON.parse(W6(f,"utf8"))}catch(E){if(J)u$.warn("Failed to parse package.json:",[E instanceof Error?E:Error(String(E))]);return null}let j=B[$],z=$;if(!j&&w){let E=Array.isArray(w)?w:[w];for(let F of E){if(!F)continue;if(B[F]){j=B[F],z=F;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)u$.success(`Configuration loaded from package.json: ${z}`);return{config:k9(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)u$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:ZY($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw F1.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return pY.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);pY.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias){let Y=Array.isArray(w.alias)?w.alias.join(","):w.alias;A.push(`alias:${Y}`)}if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,B$($,"config"),B$($,".config"),w?B$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(B$(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[B$(ew(),".config",$),B$(ew(),".config"),ew()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function ZY($,w,A=!1){let Y=new HU,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=UX.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}function XU($,w){let A=[];function Y(X){let J;try{J=Zj.readdirSync(X)}catch{return}for(let U of J){let W=R$.join(X,U);try{if(Zj.statSync(W).isDirectory())Y(W);else if(U===w)A.push(X)}catch{continue}}}return Y($),A}function V($,w,A){if(A||B0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function u9(){return b9.env.SUDO_PASSWORD}function MT($){let w=$.toLowerCase();return RT.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function YX($){if(Array.isArray($))return $.map((A)=>YX(A));if(typeof $==="string")return qT.test($)?xj:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(MT(A)){w[A]=xj;continue}w[A]=YX(Y)}return w}function jX($){return JSON.stringify(YX($))}function IT($){let w=u9();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let A=w.replace(/'/g,"'\\''"),Y=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${A}' | ${Y}`}async function Bw($,w={}){let A=IT($);try{let{stdout:Y,stderr:X}=await NT(A,{cwd:w.cwd||b9.cwd(),timeout:w.timeout||30000});return{stdout:Y.trim(),stderr:X.trim()}}catch(Y){let X=Error(`Failed to execute command: ${$}
127
- Error: ${Y.message}`);throw X.stack=Y.stack,X}}function i9($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function NU($){let w=R$.join(TT.homedir(),".stacks","ssl"),A=$.basePath&&$.basePath.trim()!==""?$.basePath:B0.basePath&&B0.basePath.trim()!==""?B0.basePath:w,Y=$.certPath?R$.isAbsolute($.certPath)?$.certPath:R$.join(A,$.certPath):R$.join(A,B0.certPath),X=$.keyPath?R$.isAbsolute($.keyPath)?$.keyPath:R$.join(A,$.keyPath):R$.join(A,B0.keyPath),J=$.caCertPath?R$.isAbsolute($.caCertPath)?$.caCertPath:R$.join(A,$.caCertPath):R$.join(A,B0.caCertPath);return{certPath:Y,keyPath:X,caCertPath:J,basePath:A}}function c9($){let w=[],A=new Set;if($.domain)A.add($.domain);if($.domains?.length)$.domains.forEach((Y)=>A.add(Y));for(let Y of A)w.push({type:2,value:Y});if($.altNameIPs?.length)for(let Y of $.altNameIPs)w.push({type:7,ip:Y});if($.altNameURIs?.length)for(let Y of $.altNameURIs)w.push({type:6,value:Y});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return V(O.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function RU($){let w=$.notBeforeDays??M$.DEFAULT_NOT_BEFORE_DAYS,A=$.validityDays??($.validityYears?$.validityYears*365:M$.DEFAULT_VALIDITY_DAYS);V(O.CERT,"Calculating certificate validity dates",$.verbose);let Y=new Date(Date.now()-86400*w*1000),X=new Date(Y.getTime()+A*24*60*60*1000);return Y.setUTCHours(0,0,0,0),X.setUTCHours(23,59,59,999),V(O.CERT,`Validity period: ${Y.toISOString()} to ${X.toISOString()}`,$.verbose),{notBefore:Y,notAfter:X}}function o1($){if($<128)return Buffer.from([$]);let w=[],A=$;while(A>0)w.unshift(A&255),A>>=8;return Buffer.from([128|w.length,...w])}function A$($,w){let A=o1(w.length);return Buffer.concat([Buffer.from([$]),A,w])}function YA($){let w=$.split(".").map(Number),A=[];A.push(40*w[0]+w[1]);for(let Y=2;Y<w.length;Y++){let X=w[Y],J=[];J.unshift(X&127),X>>=7;while(X>0)J.unshift(X&127|128),X>>=7;A.push(...J)}return A$(I$.OID,Buffer.from(A))}function JU($){let w;if(typeof $==="bigint"){let A=$.toString(16).padStart(2,"0");w=Buffer.from(A.length%2?`0${A}`:A,"hex")}else if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let A=$.toString(16).padStart(2,"0");w=Buffer.from(A.length%2?`0${A}`:A,"hex")}else w=$;if(w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return A$(I$.INTEGER,w)}function v9($,w=0){return A$(I$.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function m9($){return A$(I$.OCTET_STRING,$)}function w$(...$){return A$(I$.SEQUENCE,Buffer.concat($))}function yT(...$){return A$(I$.SET,Buffer.concat($))}function CT($){return A$(I$.PRINTABLE_STRING,Buffer.from($,"ascii"))}function hT($){return A$(I$.UTF8_STRING,Buffer.from($,"utf8"))}function VT(){return Buffer.from([I$.NULL,0])}function Pj($,w,A=!0){let Y=160|$|(A?0:0),X=o1(w.length);return Buffer.concat([Buffer.from([Y]),X,w])}function bj($){let w=$.getUTCFullYear();if(w>=2050){let A=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return A$(I$.GENERALIZED_TIME,Buffer.from(A,"ascii"))}else{let A=(w%100).toString().padStart(2,"0"),Y=($.getUTCMonth()+1).toString().padStart(2,"0"),X=$.getUTCDate().toString().padStart(2,"0"),J=$.getUTCHours().toString().padStart(2,"0"),U=$.getUTCMinutes().toString().padStart(2,"0"),W=$.getUTCSeconds().toString().padStart(2,"0"),f=`${A}${Y}${X}${J}${U}${W}Z`;return A$(I$.UTC_TIME,Buffer.from(f,"ascii"))}}function LT($,w){return w$(bj($),bj(w))}function uj($){let w=[];for(let A of $){let Y;switch(A.shortName){case"CN":Y=m0.COMMON_NAME;break;case"C":Y=m0.COUNTRY;break;case"L":Y=m0.LOCALITY;break;case"ST":Y=m0.STATE;break;case"O":Y=m0.ORGANIZATION;break;case"OU":Y=m0.ORGANIZATIONAL_UNIT;break;default:continue}let X=A.shortName==="C"?CT(A.value):hT(A.value),J=w$(YA(Y),X);w.push(yT(J))}return w$(...w)}function d9($){return w$(YA($),VT())}function OT($){return $.export({type:"spki",format:"der"})}function QT($){if($.includes(":")){let w=$;if($.includes("::")){let X=$.split("::"),J=X[0]?X[0].split(":"):[],U=X[1]?X[1].split(":"):[],W=8-J.length-U.length,f=Array.from({length:W},()=>"0");w=[...J,...f,...U].join(":")}let A=w.split(":"),Y=Buffer.alloc(16);for(let X=0;X<8;X++){let J=Number.parseInt(A[X]||"0",16);Y.writeUInt16BE(J,X*2)}return Y}else{let w=$.split(".").map((A)=>Number.parseInt(A,10));return Buffer.from(w)}}function ST($){let w=[];for(let A of $)if(A.type===2&&A.value){let Y=o1(A.value.length);w.push(Buffer.concat([Buffer.from([130]),Y,Buffer.from(A.value,"ascii")]))}else if(A.type===7&&A.ip){let Y=QT(A.ip),X=o1(Y.length);w.push(Buffer.concat([Buffer.from([135]),X,Y]))}else if(A.type===6&&A.value){let Y=o1(A.value.length);w.push(Buffer.concat([Buffer.from([134]),Y,Buffer.from(A.value,"ascii")]))}return w$(...w)}function _T($,w){if($){if(w!==void 0)return w$(A$(1,Buffer.from([255])),JU(w));return w$(A$(1,Buffer.from([255])))}return w$()}function kT($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let A=0,Y=w;while(Y>0&&(Y&1)===0)A++,Y>>=1;if(w===0)A=7;return v9(Buffer.from([w]),A)}function DT($){let w=[];if($.serverAuth)w.push(YA(m0.SERVER_AUTH));if($.clientAuth)w.push(YA(m0.CLIENT_AUTH));return w$(...w)}function a1($,w,A){let Y=[YA($)];if(w)Y.push(A$(1,Buffer.from([255])));return Y.push(m9(A)),w$(...Y)}function ZT($){let w=[];if(w.push(Pj(0,JU(2))),w.push(JU($.serialNumber)),w.push(d9(m0.SHA256_WITH_RSA)),w.push(uj($.issuer)),w.push(LT($.notBefore,$.notAfter)),w.push(uj($.subject)),w.push(OT($.publicKey)),$.extensions){let A=[];if($.extensions.basicConstraints)A.push(a1(m0.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,_T($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)A.push(a1(m0.KEY_USAGE,$.extensions.keyUsage.critical??!0,kT($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)A.push(a1(m0.EXTENDED_KEY_USAGE,!1,DT($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)A.push(a1(m0.SUBJECT_ALT_NAME,!1,ST($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)A.push(a1(m0.SUBJECT_KEY_IDENTIFIER,!1,m9($.extensions.subjectKeyIdentifier)));if(A.length>0)w.push(Pj(3,w$(...A)))}return w$(...w)}function xT($,w){let A=E1.createSign("SHA256");A.update($);let Y=A.sign(w);return w$($,d9(m0.SHA256_WITH_RSA),v9(Y))}function PT($,w){let A=$.toString("base64"),Y=[];for(let X=0;X<A.length;X+=64)Y.push(A.slice(X,X+64));return`-----BEGIN ${w}-----
128
- ${Y.join(`
123
+ `;Y+=`| Variable | Type | Description | Example |
124
+ `,Y+=`|----------|------|-------------|----------|
125
+ `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
126
+ `;return Y}}function M7($,w,Y={}){return iz($,w,Y,new WeakMap)}function iz($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return cz($,w,U,A);if(!f$(w)||!f$($))return w;return h7($,w,Y,A)}function cz($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return I7($,w);case"smart":return y7($,w,A);default:return w}return w}function I7($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>FJ(U,A)))Y.push(A);return Y}function y7($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(f$(w[0])&&f$($[0]))return C7($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function C7($,w,Y){let A=[...w];for(let U of $){if(!f$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((f)=>f$(f)&&(W in f)&&f[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function h7($,w,Y,A){let U=w;if(f$(U)&&A.has(U))return A.get(U);let X={...$};if(f$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(f$(W)&&f$(f))X[J]=iz(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=cz(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function vz($,w,Y="replace"){return M7($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function FJ($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!FJ($[Y],w[Y]))return!1;return!0}if(f$($)&&f$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!FJ($[U],w[U]))return!1}return!0}return!1}function f$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class mz{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=aA.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!xA($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new UU($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new UU($,Error("Configuration must export a valid object"),"unknown");let T={config:vz(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)aA.setWithFileCheck("file",T,$,X);return T}catch(B){throw B instanceof Error?z1.configLoad($,B):z1.configLoad($,Error(String(B)))}};if(J)return NJ.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(l8(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);let A=w===void 0?[]:Array.isArray(w)?w:[w];for(let X of A){if(!X)continue;if(Y.push(X,`.${X}.config`,`${X}.config`,`.${X}`),$)Y.push(`${$}.${X}.config`,`.${$}.${X}.config`)}let U=new Set;return Y.filter((X)=>{if(!X||U.has(X))return!1;return U.add(X),!0})}checkFileAccess($){return R7(async()=>{return xA($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!xA($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=l8($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=l8($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((w)=>w.test($))}async validateConfigFile($){let w=[];try{if(!xA($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class dz{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await NJ.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!JK(w))throw new XU(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new XU(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:V7},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}function L7($){if(!$)return"";let w=Array.isArray($)?$.filter(Boolean):[$];if(w.length===0)return"";if(w.length===1)return` or alias "${w[0]}"`;return` or aliases ${w.map((Y)=>`"${Y}"`).join(", ")}`}class gz{fileLoader=new mz;envProcessor=new LJ;validator=new dz;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)u$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){if(W instanceof Error&&W.name==="ConfigNotFoundError")throw W;let f=Date.now()-w;throw u$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||BU.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(X$(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw z1.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${L7(U)}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?bA($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)u$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)u$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?bA($,Y,U):Y,W=[X$(ow(),".config",$),X$(ow(),".config"),ow()];for(let f of W){if(U)u$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)u$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?bA($,A,X):A;try{let f=X$(Y,"package.json");if(!RE(f))return null;let B={};try{B=JSON.parse(ME(f,"utf8"))}catch(G){if(X)u$.warn("Failed to parse package.json:",[G instanceof Error?G:Error(String(G))]);return null}let j=B[$],z=$;if(!j&&w){let G=Array.isArray(w)?w:[w];for(let F of G){if(!F)continue;if(B[F]){j=B[F],z=F;break}}}if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)u$.success(`Configuration loaded from package.json: ${z}`);return{config:vz(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)u$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:bA($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw z1.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return aA.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);aA.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias){let A=Array.isArray(w.alias)?w.alias.join(","):w.alias;Y.push(`alias:${A}`)}if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,X$($,"config"),X$($,".config"),w?X$($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(X$(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[X$(ow(),".config",$),X$(ow(),".config"),ow()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function bA($,w,Y=!1){let A=new LJ,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=BU.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}function pz($){return GJ.readFileSync($,"utf8")}function EJ($,w){let Y=[];function A(U){let X;try{X=GJ.readdirSync(U)}catch{return}for(let J of X){let W=E$.join(U,J);try{if(GJ.statSync(W).isDirectory())A(W);else if(J===w)Y.push(U)}catch{continue}}}return A($),Y}function V($,w,Y){if(Y||B0.verbose)console.debug(`[tlsx:${$}] ${w}`)}function tz(){return nz.env.SUDO_PASSWORD}function Z7($){let w=$.toLowerCase();return k7.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function JU($){if(Array.isArray($))return $.map((Y)=>JU(Y));if(typeof $==="string")return D7.test($)?lj:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(Z7(Y)){w[Y]=lj;continue}w[Y]=JU(A)}return w}function GU($){return JSON.stringify(JU($))}function x7($){let w=tz();if(!w||!/(^|\|\s*|&&\s*|;\s*)sudo\s/.test($))return $;let Y=w.replace(/'/g,"'\\''"),A=$.replace(/(^|\|\s*|&&\s*|;\s*)sudo(?!\s+-[Sn])(\s+)/g,"$1sudo -S$2");return`echo '${Y}' | ${A}`}async function Bw($,w={}){let Y=x7($);try{let{stdout:A,stderr:U}=await _7(Y,{cwd:w.cwd||nz.cwd(),timeout:w.timeout||30000});return{stdout:A.trim(),stderr:U.trim()}}catch(A){let U=Error(`Failed to execute command: ${$}
127
+ Error: ${A.message}`);throw U.stack=A.stack,U}}function rz($){if($.domain)return $.domain;if($.domains?.length)return $.domains[0];throw Error("Either domain or domains must be specified")}function QJ($){let w=E$.join(O7.homedir(),".stacks","ssl"),Y=$.basePath&&$.basePath.trim()!==""?$.basePath:B0.basePath&&B0.basePath.trim()!==""?B0.basePath:w,A=$.certPath?E$.isAbsolute($.certPath)?$.certPath:E$.join(Y,$.certPath):E$.join(Y,B0.certPath),U=$.keyPath?E$.isAbsolute($.keyPath)?$.keyPath:E$.join(Y,$.keyPath):E$.join(Y,B0.keyPath),X=$.caCertPath?E$.isAbsolute($.caCertPath)?$.caCertPath:E$.join(Y,$.caCertPath):E$.join(Y,B0.caCertPath);return{certPath:A,keyPath:U,caCertPath:X,basePath:Y}}function az($){let w=[],Y=new Set;if($.domain)Y.add($.domain);if($.domains?.length)$.domains.forEach((A)=>Y.add(A));for(let A of Y)w.push({type:2,value:A});if($.altNameIPs?.length)for(let A of $.altNameIPs)w.push({type:7,ip:A});if($.altNameURIs?.length)for(let A of $.altNameURIs)w.push({type:6,value:A});if($.subjectAltNames?.length)w.push(...$.subjectAltNames);return V(Q.CERT,`Generated ${w.length} Subject Alternative Names`,$.verbose),w}function OJ($){let w=$.notBeforeDays??T$.DEFAULT_NOT_BEFORE_DAYS,Y=$.validityDays??($.validityYears?$.validityYears*365:T$.DEFAULT_VALIDITY_DAYS);V(Q.CERT,"Calculating certificate validity dates",$.verbose);let A=new Date(Date.now()-86400*w*1000),U=new Date(A.getTime()+Y*24*60*60*1000);return A.setUTCHours(0,0,0,0),U.setUTCHours(23,59,59,999),V(Q.CERT,`Validity period: ${A.toISOString()} to ${U.toISOString()}`,$.verbose),{notBefore:A,notAfter:U}}function YY($){if($<128)return Buffer.from([$]);let w=[],Y=$;while(Y>0)w.unshift(Y&255),Y>>=8;return Buffer.from([128|w.length,...w])}function e0($,w){let Y=YY(w.length);return Buffer.concat([Buffer.from([$]),Y,w])}function fY($){let w=$.split(".").map(Number),Y=[];Y.push(40*w[0]+w[1]);for(let A=2;A<w.length;A++){let U=w[A],X=[];X.unshift(U&127),U>>=7;while(U>0)X.unshift(U&127|128),U>>=7;Y.push(...X)}return e0(H$.OID,Buffer.from(Y))}function KJ($){let w;if(typeof $==="bigint"){let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else if(typeof $==="number")if($===0)w=Buffer.from([0]);else{let Y=$.toString(16).padStart(2,"0");w=Buffer.from(Y.length%2?`0${Y}`:Y,"hex")}else w=$;if(w[0]&128)w=Buffer.concat([Buffer.from([0]),w]);return e0(H$.INTEGER,w)}function sz($,w=0){return e0(H$.BIT_STRING,Buffer.concat([Buffer.from([w]),$]))}function oz($){return e0(H$.OCTET_STRING,$)}function o0(...$){return e0(H$.SEQUENCE,Buffer.concat($))}function P7(...$){return e0(H$.SET,Buffer.concat($))}function b7($){return e0(H$.PRINTABLE_STRING,Buffer.from($,"ascii"))}function u7($){return e0(H$.UTF8_STRING,Buffer.from($,"utf8"))}function i7(){return Buffer.from([H$.NULL,0])}function nj($,w,Y=!0){let A=160|$|(Y?0:0),U=YY(w.length);return Buffer.concat([Buffer.from([A]),U,w])}function pj($){let w=$.getUTCFullYear();if(w>=2050){let Y=$.toISOString().replace(/[-:T]/g,"").slice(0,14)+"Z";return e0(H$.GENERALIZED_TIME,Buffer.from(Y,"ascii"))}else{let Y=(w%100).toString().padStart(2,"0"),A=($.getUTCMonth()+1).toString().padStart(2,"0"),U=$.getUTCDate().toString().padStart(2,"0"),X=$.getUTCHours().toString().padStart(2,"0"),J=$.getUTCMinutes().toString().padStart(2,"0"),W=$.getUTCSeconds().toString().padStart(2,"0"),f=`${Y}${A}${U}${X}${J}${W}Z`;return e0(H$.UTC_TIME,Buffer.from(f,"ascii"))}}function c7($,w){return o0(pj($),pj(w))}function tj($){let w=[];for(let Y of $){let A;switch(Y.shortName){case"CN":A=v0.COMMON_NAME;break;case"C":A=v0.COUNTRY;break;case"L":A=v0.LOCALITY;break;case"ST":A=v0.STATE;break;case"O":A=v0.ORGANIZATION;break;case"OU":A=v0.ORGANIZATIONAL_UNIT;break;default:continue}let U=Y.shortName==="C"?b7(Y.value):u7(Y.value),X=o0(fY(A),U);w.push(P7(X))}return o0(...w)}function ez($){return o0(fY($),i7())}function v7($){return $.export({type:"spki",format:"der"})}function m7($){if($.includes(":")){let w=$;if($.includes("::")){let U=$.split("::"),X=U[0]?U[0].split(":"):[],J=U[1]?U[1].split(":"):[],W=8-X.length-J.length,f=Array.from({length:W},()=>"0");w=[...X,...f,...J].join(":")}let Y=w.split(":"),A=Buffer.alloc(16);for(let U=0;U<8;U++){let X=Number.parseInt(Y[U]||"0",16);A.writeUInt16BE(X,U*2)}return A}else{let w=$.split(".").map((Y)=>Number.parseInt(Y,10));return Buffer.from(w)}}function d7($){let w=[];for(let Y of $)if(Y.type===2&&Y.value){let A=YY(Y.value.length);w.push(Buffer.concat([Buffer.from([130]),A,Buffer.from(Y.value,"ascii")]))}else if(Y.type===7&&Y.ip){let A=m7(Y.ip),U=YY(A.length);w.push(Buffer.concat([Buffer.from([135]),U,A]))}else if(Y.type===6&&Y.value){let A=YY(Y.value.length);w.push(Buffer.concat([Buffer.from([134]),A,Buffer.from(Y.value,"ascii")]))}return o0(...w)}function g7($,w){if($){if(w!==void 0)return o0(e0(1,Buffer.from([255])),KJ(w));return o0(e0(1,Buffer.from([255])))}return o0()}function l7($){let w=0;if($.digitalSignature)w|=128;if($.keyEncipherment)w|=32;if($.keyCertSign)w|=4;if($.cRLSign)w|=2;let Y=0,A=w;while(A>0&&(A&1)===0)Y++,A>>=1;if(w===0)Y=7;return sz(Buffer.from([w]),Y)}function n7($){let w=[];if($.serverAuth)w.push(fY(v0.SERVER_AUTH));if($.clientAuth)w.push(fY(v0.CLIENT_AUTH));return o0(...w)}function $Y($,w,Y){let A=[fY($)];if(w)A.push(e0(1,Buffer.from([255])));return A.push(oz(Y)),o0(...A)}function p7($){let w=[];if(w.push(nj(0,KJ(2))),w.push(KJ($.serialNumber)),w.push(ez(v0.SHA256_WITH_RSA)),w.push(tj($.issuer)),w.push(c7($.notBefore,$.notAfter)),w.push(tj($.subject)),w.push(v7($.publicKey)),$.extensions){let Y=[];if($.extensions.basicConstraints)Y.push($Y(v0.BASIC_CONSTRAINTS,$.extensions.basicConstraints.critical??!0,g7($.extensions.basicConstraints.isCA,$.extensions.basicConstraints.pathLenConstraint)));if($.extensions.keyUsage)Y.push($Y(v0.KEY_USAGE,$.extensions.keyUsage.critical??!0,l7($.extensions.keyUsage)));if($.extensions.extendedKeyUsage)Y.push($Y(v0.EXTENDED_KEY_USAGE,!1,n7($.extensions.extendedKeyUsage)));if($.extensions.subjectAltName?.length)Y.push($Y(v0.SUBJECT_ALT_NAME,!1,d7($.extensions.subjectAltName)));if($.extensions.subjectKeyIdentifier)Y.push($Y(v0.SUBJECT_KEY_IDENTIFIER,!1,oz($.extensions.subjectKeyIdentifier)));if(Y.length>0)w.push(nj(3,o0(...Y)))}return o0(...w)}function t7($,w){let Y=F1.createSign("SHA256");Y.update($);let A=Y.sign(w);return o0($,ez(v0.SHA256_WITH_RSA),sz(A))}function r7($,w){let Y=$.toString("base64"),A=[];for(let U=0;U<Y.length;U+=64)A.push(Y.slice(U,U+64));return`-----BEGIN ${w}-----
128
+ ${A.join(`
129
129
  `)}
130
130
  -----END ${w}-----
131
- `}function qU(){return E1.randomBytes(20)}function g9($=2048){let{privateKey:w,publicKey:A}=E1.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:A}}function bT($){let w=$.export({type:"spki",format:"der"});return E1.createHash("sha1").update(w).digest()}function n9($){let w={serialNumber:$.serialNumber||qU(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:bT($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let A=ZT(w),Y=xT(A,$.signingKey);return{certificate:PT(Y,"CERTIFICATE"),certificateDer:Y}}function l9($){return $.export({type:"pkcs8",format:"pem"})}function uT($){return E1.createPrivateKey($)}function iT($){let w=new E1.X509Certificate($),A=w.publicKey,Y=[],X=w.subject.split(`
132
- `);for(let J of X){let[U,...W]=J.split("="),f=W.join("=");if(U&&f)Y.push({shortName:U.trim(),value:f.trim()})}return{publicKey:A,subject:Y}}async function MU($={}){V("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||M$.DEFAULT_KEY_SIZE;V("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:A,publicKey:Y}=g9(w),X=[{shortName:"C",value:$.countryName||B0.countryName},{shortName:"ST",value:$.stateName||B0.stateName},{shortName:"L",value:$.localityName||B0.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:J,notAfter:U}=RU({validityYears:$.validityYears||M$.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=n9({serialNumber:qU(),notBefore:J,notAfter:U,subject:X,publicKey:Y,signingKey:A,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:l9(A),notBefore:J,notAfter:U}}async function IU($){if(V("ca","Generating new certificate",$.verbose),V("ca",`Options: ${jX($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=iT($.rootCA.certificate),A=uT($.rootCA.privateKey);V("ca",`Generating ${M$.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let Y=M$.DEFAULT_KEY_SIZE,{privateKey:X,publicKey:J}=g9(Y),U=$.commonName||i9($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||B0.countryName},{shortName:"ST",value:$.stateName||B0.stateName},{shortName:"L",value:$.localityName||B0.localityName},{shortName:"O",value:$.organizationName||B0.organizationName},{shortName:"CN",value:U}],{notBefore:f,notAfter:B}=RU({validityDays:$.validityDays||M$.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),j=c9($),z=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},E=$.extKeyUsage||{serverAuth:!0},{certificate:F}=n9({serialNumber:qU(),notBefore:f,notAfter:B,subject:W,issuer:w,publicKey:J,signingKey:A,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:z,extendedKeyUsage:E,subjectAltName:j});return{certificate:F,privateKey:l9(X),notBefore:f,notAfter:B}}function p9($,w){V(O.STORAGE,`Storing certificate and private key with options: ${jX(w)}`,w?.verbose);let{certPath:A,keyPath:Y}=NU({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});V(O.STORAGE,`Certificate path: ${A}`,w?.verbose),V(O.STORAGE,`Private key path: ${Y}`,w?.verbose);let X=UU.dirname(A);if(!m$.existsSync(X))V(O.STORAGE,`Creating certificate directory: ${X}`,w?.verbose),m$.mkdirSync(X,{recursive:!0});V(O.STORAGE,"Writing certificate file",w?.verbose),m$.writeFileSync(A,$.certificate);let J=UU.dirname(Y);if(!m$.existsSync(J))V(O.STORAGE,`Creating private key directory: ${J}`,w?.verbose),m$.mkdirSync(J,{recursive:!0});return V(O.STORAGE,"Writing private key file",w?.verbose),m$.writeFileSync(Y,$.privateKey),V(O.STORAGE,"Certificate and private key stored successfully",w?.verbose),A}function t9($,w){V(O.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:A}=NU({basePath:w?.basePath,caCertPath:w?.caCertPath});V(O.STORAGE,`CA certificate path: ${A}`,w?.verbose);let Y=UU.dirname(A);if(!m$.existsSync(Y))V(O.STORAGE,`Creating CA certificate directory: ${Y}`,w?.verbose),m$.mkdirSync(Y,{recursive:!0});return V(O.STORAGE,"Writing CA certificate file",w?.verbose),m$.writeFileSync(A,$),V(O.STORAGE,"CA certificate stored successfully",w?.verbose),A}async function cT($,w){if(XX.platform()!=="darwin")return!1;try{let A=ij(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"";if(!A)return V(O.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(ij("security find-certificate -a -Z -p | openssl x509 -noout -fingerprint -sha256 2>/dev/null || true").toString().includes(A))return V(O.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return V(O.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(A){return V(O.TRUST,`Error checking certificate trust: ${A}`,w),!1}}async function yU($,w,A){V(O.TRUST,`Adding certificate to system trust store with options: ${jX(A)}`,A?.verbose),V(O.TRUST,"Storing certificate and private key",A?.verbose);let Y=p9($,A);V(O.TRUST,"Storing CA certificate",A?.verbose);let X=t9(w,A),J=XX.platform();V(O.TRUST,`Detected platform: ${J}`,A?.verbose);let U=gT[J];if(!U){let W=`Unsupported platform: ${J}`;throw V(O.TRUST,`Error: ${W}`,A?.verbose),Error(W)}return await U.addCertificate(X,A),V(O.TRUST,"Certificate successfully added to system trust store",A?.verbose),Y}var lG,JX,gj="https://acme-staging-v02.api.letsencrypt.org/directory",nj="https://acme-v02.api.letsencrypt.org/directory",vY,oG="1.2.840.10045.2.1",eG="1.2.840.10045.3.1.7",$6="1.2.840.10045.4.3.2",w6="2.5.4.3",A6="1.2.840.113549.1.9.14",Y6="2.5.29.17",pY,WU,t6,r6=($)=>$,s6=($,w)=>{for(var A in w)t6($,A,{get:w[A],enumerable:!0,configurable:!0,set:a6.bind(w,A)})},o6=($,w)=>()=>($&&(w=$($=0)),w),X9,E9,z1,XA,G9,hK,VK,Ij,bY,rJ,k0,r,LK,yj,OK,Cj,QK,SK,bJ,_K,hj,Vj,uJ,kK,DK,ZK,xK,uY,K9,PK,D0,bK,uK,Lj,iY,aJ,N0,b,iK,Oj,cK,Qj,vK,mK,iJ,dK,Sj,_j,gK,cJ,nK,lK,pK,tK,rK,cY,T9,aK,sK="0.15.6",$$,oY,wA,sJ,oJ,eY,eJ,$U,AA,wU,AU,jw,H9,N9,q$,d$,R9,q9,oK,$T,M9,$X,a4,h0,c,s4,AT,o4,YT,e4,$y,kj,wy,XT,JT,Ay,Dj,Yy,Xy,Jy,Uy,fy,vJ,UT,Wy,y$,y9,wX,C9,h9,TU,V9,L9,AX,O9,Q9,F1,ET,u$,By,jy,zy,P9,B0,M$,O,j1,NT,xj="[redacted]",RT,qT,I$,m0,vT,mT,dT,gT;var r9=F0(()=>{lG=nG(import.meta.url);JX=new e1;vY=class vY extends Error{problem;httpStatus;constructor($,w,A){super($);this.name="AcmeError",this.problem=w,this.httpStatus=A}};pY=new A9,WU=new Y9,t6=Object.defineProperty;X9={};s6(X9,{withErrorRecovery:()=>f9,tryLoadConfig:()=>MK,loadConfigWithResult:()=>RK,loadConfig:()=>F9,isRetryableError:()=>EK,isConfigNotFoundError:()=>FK,isBunfigError:()=>W9,globalPerformanceMonitor:()=>XA,globalCache:()=>z1,getEnvOrDefault:()=>GK,generateConfigTypes:()=>IK,defaultGeneratedDir:()=>q9,defaultConfigDir:()=>R9,deepMergeWithArrayStrategy:()=>EU,deepMerge:()=>B9,createLibraryConfig:()=>yK,config:()=>qK,bunfigPlugin:()=>CK,applyEnvVarsToConfig:()=>s1,TypeGenerationError:()=>$U,SchemaValidationError:()=>AA,PluginError:()=>AU,PerformanceMonitor:()=>jU,FileSystemError:()=>eJ,ErrorFactory:()=>jw,EnvVarError:()=>eY,EnvProcessor:()=>fX,ConfigValidator:()=>GU,ConfigValidationError:()=>sJ,ConfigNotFoundError:()=>oY,ConfigMergeError:()=>oJ,ConfigLoader:()=>KU,ConfigLoadError:()=>wA,ConfigFileLoader:()=>WX,ConfigCache:()=>BU,CacheUtils:()=>G9,BunfigError:()=>$$,BrowserConfigError:()=>wU,ArrayMergeStrategies:()=>H9});oK=o6(async()=>{E9=import.meta.require,z1=new BU,XA=new jU,G9={createKey:e6,isEquivalent:$K,estimateMemoryUsage:wK},hK=nY(pJ.cwd(),"config"),VK=nY(pJ.cwd(),"src/generated"),Ij=gY.env.CLARITY_LOG_DIR||G6(XK(),"logs"),bY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Ij,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},rJ=await JK(),k0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},r=k0,LK=k0.red,yj=k0.green,OK=k0.yellow,Cj=k0.blue,QK=k0.magenta,SK=k0.cyan,bJ=k0.white,_K=k0.gray,hj=k0.bgRed,Vj=k0.bgYellow,uJ=k0.bold,kK=k0.dim,DK=k0.italic,ZK=k0.underline,xK=k0.reset,uY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},K9={debug:"\uD83D\uDD0D",info:Cj("ℹ"),success:yj("✓"),warning:Vj(bJ(uJ(" WARN "))),error:hj(bJ(uJ(" ERROR ")))},PK=new rY("stacks"),D0=new rY("bunfig",{showTags:!0}),bK=c0($A.cwd(),"config"),uK=c0($A.cwd(),"src/generated"),Lj=dY.env.CLARITY_LOG_DIR||F6(BK(),"logs"),iY={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Lj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},aJ=await jK(),N0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},b=N0,iK=N0.red,Oj=N0.green,cK=N0.yellow,Qj=N0.blue,vK=N0.magenta,mK=N0.cyan,iJ=N0.white,dK=N0.gray,Sj=N0.bgRed,_j=N0.bgYellow,gK=N0.bgGray,cJ=N0.bold,nK=N0.dim,lK=N0.italic,pK=N0.underline,tK=N0.strikethrough,rK=N0.reset,cY={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},T9={debug:"\uD83D\uDD0D",info:Qj("ℹ"),success:Oj("✓"),warning:_j(iJ(cJ(" WARN "))),error:Sj(iJ(cJ(" ERROR ")))},aK=new sY("stacks"),$$=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},oY=class extends $${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A?` or alias "${A}"`:"";super(`Configuration "${$}"${Y} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}},wA=class extends $${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}},sJ=class extends $${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}},oJ=class extends $${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},eY=class extends $${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}},eJ=class extends $${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}},$U=class extends $${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}},AA=class extends $${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}},wU=class extends $${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}},AU=class extends $${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}},jw={configNotFound($,w,A){return new oY($,w,A)},configLoad($,w,A){return new wA($,w,A)},configValidation($,w,A){return new sJ($,w,A)},configMerge($,w,A,Y){return new oJ($,w,A,Y)},envVar($,w,A,Y){return new eY($,w,A,Y)},fileSystem($,w,A){return new eJ($,w,A)},typeGeneration($,w,A){return new $U($,w,A)},schemaValidation($,w,A){return new AA($,w,A)},browserConfig($,w,A,Y){return new wU($,w,A,Y)},plugin($,w,A){return new AU($,w,A)}},H9={replace:"replace",concat:"concat",smart:"smart"},N9=/^https?:\/\//,q$=new sY("bunfig",{showTags:!0}),d$=new KU,R9=v0(Vw.cwd(),"config"),q9=v0(Vw.cwd(),"src/generated")});$T=lY.env.CLARITY_LOG_DIR||P6(eK(),"logs"),M9={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:$T,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},$X={...M9},a4=(async()=>{try{let{loadConfig:$}=await oK().then(()=>X9),w=await $({name:"clarity",alias:"logging",defaultConfig:M9,cwd:lY.cwd()});if(w)Object.assign($X,w)}catch{}return $X})();h0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},c=h0,s4=h0.red,AT=h0.green,o4=h0.yellow,YT=h0.blue,e4=h0.magenta,$y=h0.cyan,kj=h0.white,wy=h0.gray,XT=h0.bgRed,JT=h0.bgYellow,Ay=h0.bgGray,Dj=h0.bold,Yy=h0.dim,Xy=h0.italic,Jy=h0.underline,Uy=h0.strikethrough,fy=h0.reset,vJ={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},UT={debug:"\uD83D\uDD0D",info:YT("ℹ"),success:AT("✓"),warning:JT(kj(Dj(" WARN "))),error:XT(kj(Dj(" ERROR ")))};Wy=new BX("stacks");y$=class y$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,A])=>`${w}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};y9=class y9 extends y${code="CONFIG_NOT_FOUND";constructor($,w,A){let Y=A===void 0?[]:Array.isArray(A)?A.filter(Boolean):[A],X="";if(Y.length===1)X=` or alias "${Y[0]}"`;else if(Y.length>1)X=` or aliases ${Y.map((J)=>`"${J}"`).join(", ")}`;super(`Configuration "${$}"${X} not found`,{configName:$,alias:A,searchPaths:w,searchPathCount:w.length})}};wX=class wX extends y${code="CONFIG_LOAD_ERROR";constructor($,w,A){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:A,originalError:w.name,originalMessage:w.message});this.cause=w}};C9=class C9 extends y${code="CONFIG_VALIDATION_ERROR";constructor($,w,A){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:A,validationErrors:w,errorCount:w.length})}};h9=class h9 extends y${code="CONFIG_MERGE_ERROR";constructor($,w,A,Y){super(`Failed to merge configuration from "${$}" with "${w}": ${A.message}`,{sourcePath:$,targetPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}};TU=class TU extends y${code="ENV_VAR_ERROR";constructor($,w,A,Y){super(`Failed to parse environment variable "${$}" with value "${w}" as ${A}`,{envKey:$,envValue:w,expectedType:A,configName:Y})}};V9=class V9 extends y${code="FILE_SYSTEM_ERROR";constructor($,w,A){super(`File system ${$} failed for "${w}": ${A.message}`,{operation:$,path:w,originalError:A.name,originalMessage:A.message});this.cause=A}};L9=class L9 extends y${code="TYPE_GENERATION_ERROR";constructor($,w,A){super(`Failed to generate types from "${$}" to "${w}": ${A.message}`,{configDir:$,outputPath:w,originalError:A.name,originalMessage:A.message});this.cause=A}};AX=class AX extends y${code="SCHEMA_VALIDATION_ERROR";constructor($,w,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:$,configName:A,validationErrors:w,errorCount:w.length})}};O9=class O9 extends y${code="BROWSER_CONFIG_ERROR";constructor($,w,A,Y){super(`Failed to fetch configuration from "${$}": ${w} ${A}`,{endpoint:$,status:w,statusText:A,configName:Y})}};Q9=class Q9 extends y${code="PLUGIN_ERROR";constructor($,w,A){super(`Plugin "${$}" failed during ${w}: ${A.message}`,{pluginName:$,operation:w,originalError:A.name,originalMessage:A.message});this.cause=A}};F1={configNotFound($,w,A){return new y9($,w,A)},configLoad($,w,A){return new wX($,w,A)},configValidation($,w,A){return new C9($,w,A)},configMerge($,w,A,Y){return new h9($,w,A,Y)},envVar($,w,A,Y){return new TU($,w,A,Y)},fileSystem($,w,A){return new V9($,w,A)},typeGeneration($,w,A){return new L9($,w,A)},schemaValidation($,w,A){return new AX($,w,A)},browserConfig($,w,A,Y){return new O9($,w,A,Y)},plugin($,w,A){return new Q9($,w,A)}};ET=/^https?:\/\//;u$=new BX("bunfig",{showTags:!0});By=new x9;jy=B$(UX.cwd(),"config"),zy=B$(UX.cwd(),"src/generated"),P9={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:IJ.join(MJ.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:IJ.join(MJ.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:IJ.join(MJ.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},B0=P9,M$={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"},j1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};NT=HT(KT);RT=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),qT=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;I$={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},m0={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"};vT={platform:"darwin",async addCertificate($,w){if(await cT($,w?.verbose)){V(O.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),j1.success("Certificate is already trusted in system keychain");return}V(O.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Bw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,A){let Y=A||B0.commonName;V(O.TRUST,`Removing certificate ${Y} from macOS keychain`,w?.verbose);try{await Bw(`sudo security delete-certificate -c "${Y}" /Library/Keychains/System.keychain`),V(O.TRUST,`Removed certificate ${Y} from macOS keychain`,w?.verbose)}catch(X){throw V(O.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},mT={platform:"win32",async addCertificate($,w){V(O.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Bw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,A){let Y=A||B0.commonName;V(O.TRUST,`Removing certificate ${Y} from Windows certificate store`,w?.verbose);try{await Bw(`certutil -delstore -enterprise Root "${Y}"`),V(O.TRUST,`Removed certificate ${Y} from Windows certificate store`,w?.verbose)}catch(X){throw V(O.TRUST,`Error removing certificate: ${X}`,w?.verbose),X}}},dT={platform:"linux",async addCertificate($,w){V(O.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let A=XX.homedir(),Y=M$.LINUX_CERT_DB_FILENAME,X=M$.LINUX_TRUST_ARGS;V(O.TRUST,`Searching for certificate databases in ${A}`,w?.verbose);let J=XU(A,Y);if(J.length===0){j1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let U of J){V(O.TRUST,`Processing certificate database in ${U}`,w?.verbose);try{V(O.TRUST,`Attempting to delete existing cert for ${B0.commonName}`,w?.verbose),await Bw(`certutil -d sql:${U} -D -n ${B0.commonName}`)}catch(W){V(O.TRUST,`Warning: Error deleting existing cert: ${W}`,w?.verbose),console.warn(`Error deleting existing cert: ${W}`)}V(O.TRUST,`Adding new certificate to ${U}`,w?.verbose),await Bw(`certutil -d sql:${U} -A -t ${X} -n ${B0.commonName} -i ${$}`),j1.info(`Cert added to ${U}`)}},async removeCertificate($,w,A){let Y=A||B0.commonName;V(O.TRUST,`Removing certificate ${Y} from Linux certificate store`,w?.verbose);let X=XX.homedir(),J=M$.LINUX_CERT_DB_FILENAME;V(O.TRUST,`Searching for certificate databases in ${X}`,w?.verbose);let U=XU(X,J);if(U.length===0){j1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of U){V(O.TRUST,`Processing certificate database in ${W}`,w?.verbose);try{await Bw(`certutil -d sql:${W} -D -n "${Y}"`),j1.info(`Cert removed from ${W}`)}catch(f){V(O.TRUST,`Error removing cert from ${W}: ${f}`,w?.verbose),console.warn(`Error removing cert from ${W}: ${f}`)}}}},gT={darwin:vT,win32:mT,linux:dT}});var CU=F0(()=>{r9()});import{homedir as hU}from"node:os";import{join as VU,resolve as WC}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",nT,LU;var OU=F0(()=>{HJ();nT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:VU(hU(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:VU(hU(),".stacks","ssl","stacks.localhost.crt"),keyPath:VU(hU(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},LU=nT});import{execSync as a9}from"node:child_process";function s9($){return($.includes("=")?$.split("=").pop():$).replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()}function zX($){try{let w=a9(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`,{encoding:"utf8"});return s9(w)}catch{return null}}function FX($,w){try{let A=a9(`openssl x509 -in "${$}" -noout -text`,{encoding:"utf8"});return w.every((Y)=>A.includes(`DNS:${Y}`))}catch{return!1}}var QU=()=>{};import{existsSync as o9,statSync as e9}from"fs";import{existsSync as tU,mkdirSync as sT,readdirSync as oT,writeFileSync as eT}from"fs";import{homedir as G1}from"os";import{dirname as $2,resolve as g0}from"path";import Lw from"process";import{join as $7,relative as w7,resolve as w2}from"path";import QX from"process";import{existsSync as b2,mkdirSync as MC,readdirSync as IC,writeFileSync as yC}from"fs";import{homedir as SU}from"os";import{dirname as VC,resolve as d0}from"path";import UA from"process";import{join as A7,relative as Y7,resolve as A2}from"path";import SX from"process";import{existsSync as u2,mkdirSync as _C,readdirSync as kC,writeFileSync as DC}from"fs";import{dirname as xC,resolve as _X}from"path";import rU from"process";import{Buffer as Fw}from"buffer";import{createCipheriv as X7,createDecipheriv as J7,randomBytes as _U}from"crypto";import{closeSync as kU,createReadStream as Y2,createWriteStream as U7,existsSync as DU,fsyncSync as X2,openSync as J2,writeFileSync as f7}from"fs";import{access as W7,constants as U2,mkdir as B7,readdir as EX,rename as f2,stat as K1,unlink as GX,writeFile as ZU}from"fs/promises";import{join as T1}from"path";import Z0 from"process";import{pipeline as j7}from"stream/promises";import{createGzip as W2}from"zlib";import H1 from"process";import l$ from"process";import{Buffer as g$}from"buffer";import{createCipheriv as z7,createDecipheriv as F7,randomBytes as xU}from"crypto";import{closeSync as PU,createReadStream as B2,createWriteStream as E7,existsSync as KX,fsyncSync as j2,openSync as z2,writeFileSync as G7}from"fs";import{access as K7,constants as F2,mkdir as T7,readdir as TX,rename as E2,stat as N1,unlink as HX,writeFile as bU}from"fs/promises";import{isAbsolute as H7,join as R1,resolve as N7}from"path";import Z from"process";import{pipeline as R7}from"stream/promises";import{createGzip as G2}from"zlib";import q1 from"process";import p$ from"process";import NX from"process";import{existsSync as RX}from"fs";import{resolve as uU}from"path";import{existsSync as q7}from"fs";import{existsSync as M7,readdirSync as I7}from"fs";import{extname as iU,resolve as K2}from"path";import y7 from"process";import{join as CH,relative as hH,resolve as L2}from"path";import uX from"process";import{Buffer as n$}from"buffer";import{createCipheriv as OH,createDecipheriv as QH,randomBytes as gU}from"crypto";import{closeSync as nU,createReadStream as O2,createWriteStream as SH,existsSync as MX,fsyncSync as Q2,openSync as S2,writeFileSync as _H}from"fs";import{access as kH,constants as _2,mkdir as DH,readdir as IX,rename as k2,stat as M1,unlink as yX,writeFile as lU}from"fs/promises";import{isAbsolute as ZH,join as I1,resolve as xH}from"path";import x from"process";import{pipeline as PH}from"stream/promises";import{createGzip as D2}from"zlib";import y1 from"process";import t$ from"process";function tT($,w){this[$]=pT.bind(null,w)}class Jf{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let A=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${A}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,A],[,Y])=>A.timestamp.getTime()-Y.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let A=0;A<w;A++)this.cache.delete($[A][0])}set($,w,A,Y){if(!this.options.enabled)return;let X=this.generateKey($,A),J=Y??this.options.ttl,U=this.estimateSize(w);this.cache.set(X,{value:w,timestamp:new Date,ttl:J,hits:0,size:U}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let A=this.generateKey($,w),Y=this.cache.get(A);if(!Y){this.totalMisses++;return}if(this.isExpired(Y)){this.cache.delete(A),this.totalMisses++;return}return Y.hits++,this.totalHits++,Y.value}isFileModified($,w){try{if(!o9($))return!0;return e9($).mtime>w}catch{return!0}}getWithFileCheck($,w){let A=this.get($,w);if(!A)return;if(this.isFileModified(w,A.fileTimestamp)){this.delete($,w);return}return A.value}setWithFileCheck($,w,A,Y){try{let X=o9(A)?e9(A):null,J=X?X.mtime:new Date;this.set($,{value:w,fileTimestamp:J},A,Y)}catch{this.set($,w,A,Y)}}delete($,w){let A=this.generateKey($,w);return this.cache.delete(A)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,A]of this.cache.entries())if(this.isExpired(A))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((Y,X)=>Y+X.size,0),A=$.map((Y)=>Y.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:A[0],newestEntry:A[A.length-1]}}export(){let $={};for(let[w,A]of this.cache.entries())$[w]={value:A.value,timestamp:A.timestamp.toISOString(),ttl:A.ttl,hits:A.hits,size:A.size};return $}import($){this.cache.clear();for(let[w,A]of Object.entries($))if(typeof A==="object"&&A!==null){let Y=A;this.cache.set(w,{value:Y.value,timestamp:new Date(Y.timestamp),ttl:Y.ttl,hits:Y.hits,size:Y.size})}}}class Uf{metrics=[];maxMetrics=1000;async track($,w,A={}){let Y=performance.now(),X=new Date;try{let J=await w(),U=performance.now()-Y;return this.recordMetric({operation:$,duration:U,timestamp:X,...A}),J}catch(J){let U=performance.now()-Y;throw this.recordMetric({operation:`${$}:error`,duration:U,timestamp:X,...A}),J}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((X)=>X.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let A=w.map((X)=>X.duration),Y=A.reduce((X,J)=>X+J,0);return{count:w.length,averageDuration:Y/w.length,minDuration:Math.min(...A),maxDuration:Math.max(...A),totalDuration:Y,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function C7($,w={}){let Y=Object.keys(w).sort().map((X)=>`${X}:${w[X]}`).join("|");return Y?`${$}:${Y}`:$}function h7($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function V7($){return $.getStats().size*2}function ff($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&$0(w[0])&&"id"in w[0]&&w[0].id===3&&$0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if($0(w)&&$0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if($0($)&&"arr"in $&&Array.isArray($.arr)&&$0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&$0(w[0])&&$0($[0])){let Y=[...w];for(let X of $)if($0(X)&&"name"in X){if(!Y.find((U)=>$0(U)&&("name"in U)&&U.name===X.name))Y.push(X)}else if($0(X)&&"path"in X){if(!Y.find((U)=>$0(U)&&("path"in U)&&U.path===X.path))Y.push(X)}else if(!Y.some((J)=>kX(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!$0(w)||!$0($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if($0(X)&&$0(A[Y]))A[Y]=ff(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&$0(X[0])&&$0(A[Y][0])){let J=[...X];for(let U of A[Y])if($0(U)&&"name"in U){if(!J.find((f)=>$0(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if($0(U)&&"path"in U){if(!J.find((f)=>$0(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((W)=>kX(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function kX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!kX($[A],w[A]))return!1;return!0}if($0($)&&$0(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!kX($[X],w[X]))return!1}return!0}return!1}function $0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function L7($,w){if(!u2($))return null;try{let A=await import($),Y=A.default||A;if(typeof Y!=="object"||Y===null||Array.isArray(Y))return null;try{return ff(w,Y)}catch{return null}}catch{return null}}async function O7({name:$="",cwd:w,defaultConfig:A}){let Y=w||rU.cwd(),X=[".ts",".js",".mjs",".cjs",".json"],J=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let U of J)for(let W of X){let f=_X(Y,`${U}${W}`),B=await L7(f,A);if(B!==null)return B}try{let U=_X(Y,"package.json");if(u2(U)){let f=(await import(U))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return ff(A,f)}catch{}}}catch{}return A}function Q7($,w={}){let A=SX.cwd();while(A.includes("storage"))A=A2(A,"..");let Y=A2(A,$||"");if(w?.relative)return Y7(SX.cwd(),Y);return Y}async function S7(){try{let $=await O7({name:"clarity",defaultConfig:hX,cwd:SX.cwd(),endpoint:"",headers:{}});return{...hX,...$}}catch{return hX}}function U0(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function _7(){if(l$.env.NODE_ENV==="test"||l$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof l$<"u"){let $=l$.type;if($==="renderer"||$==="worker")return!1;return!!(l$.versions&&(l$.versions.node||l$.versions.bun))}return!1}class i2{async format($){let w=await _7(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:H1.pid,hostname:w(),environment:H1.env.NODE_ENV||"development",platform:H1.platform,version:H1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:H1.env.NODE_ENV||H1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class DX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...sU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new i2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Z0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...VX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...VX};return{...VX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:sU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await W7(this.config.logDirectory,U2.F_OK|U2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await B7(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Fw.from($);try{if(!DU(this.currentLogFile))await ZU(this.currentLogFile,"",{mode:420});if(X=J2(this.currentLogFile,"a",420),f7(X,f,{flag:"a"}),X2(X),X!==void 0)kU(X),X=void 0;if((await K1(this.currentLogFile)).size===0){if(await ZU(this.currentLogFile,f,{flag:"w",mode:420}),(await K1(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 E=W*2**J;await new Promise((F)=>setTimeout(F,E)),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{kU(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return T1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return T1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return T1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(U0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.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 _U(16).toString("hex")}generateKey(){return _U(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=_U(16),Y=X7("aes-256-gcm",w,A),X=Fw.concat([Y.update($,"utf8"),Y.final()]),J=Y.getAuthTag();return{encrypted:Fw.concat([A,X,J]),iv:A}}async compressData($){return new Promise((w,A)=>{let Y=W2(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(Fw.from(Fw.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(U0())return;let $=await K1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await EX(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await K1(A).catch(()=>null))try{if(await f2(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await GX(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await ZU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await K1(A).catch(()=>null))await f2(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await EX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await GX(T1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=Y2($),Y=U7(w),X=W2();await j7(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);await this.writeToFile(Y),console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let A={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(A)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),DU(this.currentLogFile))try{let $=J2(this.currentLogFile,"r+");X2($),kU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!U0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await EX(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await GX(T1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?a.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=Z0.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${a.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);if(this.fancy&&!U0()){let B=r2[$],j=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.gray(U),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:a.green(U),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:X,icon:B,tag:j,message:U,level:$}),console.error(z),W){let E=W.split(`
133
- `);for(let F of E)if(F.trim()&&!F.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:a.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!U0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let f=`${J} ${this.environment}.${$.toUpperCase()}: ${U}
131
+ `}function SJ(){let $=F1.randomBytes(20);return $[0]=$[0]&127||1,$}function $9($=2048){let{privateKey:w,publicKey:Y}=F1.generateKeyPairSync("rsa",{modulusLength:$});return{privateKey:w,publicKey:Y}}function a7($){let w=$.export({type:"spki",format:"der"});return F1.createHash("sha1").update(w).digest()}function w9($){let w={serialNumber:$.serialNumber||SJ(),notBefore:$.notBefore,notAfter:$.notAfter,subject:$.subject,issuer:$.issuer||$.subject,publicKey:$.publicKey,extensions:{basicConstraints:{isCA:$.isCA??!1,critical:!0,pathLenConstraint:$.pathLenConstraint},subjectKeyIdentifier:a7($.publicKey)}};if($.keyUsage)w.extensions.keyUsage={...$.keyUsage,critical:!0};if($.extendedKeyUsage)w.extensions.extendedKeyUsage=$.extendedKeyUsage;if($.subjectAltName?.length)w.extensions.subjectAltName=$.subjectAltName;let Y=p7(w),A=t7(Y,$.signingKey);return{certificate:r7(A,"CERTIFICATE"),certificateDer:A}}function Y9($){return $.export({type:"pkcs8",format:"pem"})}function s7($){return F1.createPrivateKey($)}function o7($){let w=new F1.X509Certificate($),Y=w.publicKey,A=[],U=w.subject.split(`
132
+ `);for(let X of U){let[J,...W]=X.split("="),f=W.join("=");if(J&&f)A.push({shortName:J.trim(),value:f.trim()})}return{publicKey:Y,subject:A}}async function _J($={}){V("ca","Creating new Root CA Certificate",$.verbose);let w=$.keySize||T$.DEFAULT_KEY_SIZE;V("ca",`Generating ${w}-bit RSA key pair`,$.verbose);let{privateKey:Y,publicKey:A}=$9(w),U=[{shortName:"C",value:$.countryName||B0.countryName},{shortName:"ST",value:$.stateName||B0.stateName},{shortName:"L",value:$.localityName||B0.localityName},{shortName:"O",value:$.organization||"Local Development CA"},{shortName:"OU",value:$.organizationalUnit||"Certificate Authority"},{shortName:"CN",value:$.commonName||"Local Development Root CA"}],{notBefore:X,notAfter:J}=OJ({validityYears:$.validityYears||T$.DEFAULT_CA_VALIDITY_YEARS,verbose:$.verbose}),{certificate:W}=w9({serialNumber:SJ(),notBefore:X,notAfter:J,subject:U,publicKey:A,signingKey:Y,isCA:!0,keyUsage:{keyCertSign:!0,cRLSign:!0}});return{certificate:W,privateKey:Y9(Y),notBefore:X,notAfter:J}}async function kJ($){if(V("ca","Generating new certificate",$.verbose),V("ca",`Options: ${GU($)}`,$.verbose),!$.domain&&!$.domains?.length)throw Error("Either domain or domains must be specified");if(!$.rootCA?.certificate||!$.rootCA?.privateKey)throw Error("Root CA certificate and private key are required");let{subject:w}=o7($.rootCA.certificate),Y=s7($.rootCA.privateKey);V("ca",`Generating ${T$.DEFAULT_KEY_SIZE}-bit RSA key pair for host certificate`,$.verbose);let A=T$.DEFAULT_KEY_SIZE,{privateKey:U,publicKey:X}=$9(A),J=$.commonName||rz($),W=$.certificateAttributes||[{shortName:"C",value:$.countryName||B0.countryName},{shortName:"ST",value:$.stateName||B0.stateName},{shortName:"L",value:$.localityName||B0.localityName},{shortName:"O",value:$.organizationName||B0.organizationName},{shortName:"CN",value:J}],{notBefore:f,notAfter:B}=OJ({validityDays:$.validityDays||T$.DEFAULT_VALIDITY_DAYS,verbose:$.verbose}),j=az($),z=$.keyUsage||{digitalSignature:!0,keyEncipherment:!0},G=$.extKeyUsage||{serverAuth:!0},{certificate:F}=w9({serialNumber:SJ(),notBefore:f,notAfter:B,subject:W,issuer:w,publicKey:X,signingKey:Y,isCA:$.basicConstraints?.cA??!1,pathLenConstraint:$.basicConstraints?.pathLenConstraint,keyUsage:z,extendedKeyUsage:G,subjectAltName:j});return{certificate:F,privateKey:Y9(U),notBefore:f,notAfter:B}}function A9($,w){V(Q.STORAGE,`Storing certificate and private key with options: ${GU(w)}`,w?.verbose);let{certPath:Y,keyPath:A}=QJ({basePath:w?.basePath,certPath:w?.certPath,keyPath:w?.keyPath});V(Q.STORAGE,`Certificate path: ${Y}`,w?.verbose),V(Q.STORAGE,`Private key path: ${A}`,w?.verbose);let U=TJ.dirname(Y);if(!m$.existsSync(U))V(Q.STORAGE,`Creating certificate directory: ${U}`,w?.verbose),m$.mkdirSync(U,{recursive:!0});V(Q.STORAGE,"Writing certificate file",w?.verbose),m$.writeFileSync(Y,$.certificate);let X=TJ.dirname(A);if(!m$.existsSync(X))V(Q.STORAGE,`Creating private key directory: ${X}`,w?.verbose),m$.mkdirSync(X,{recursive:!0});return V(Q.STORAGE,"Writing private key file",w?.verbose),m$.writeFileSync(A,$.privateKey),V(Q.STORAGE,"Certificate and private key stored successfully",w?.verbose),Y}function U9($,w){V(Q.STORAGE,"Storing CA certificate",w?.verbose);let{caCertPath:Y}=QJ({basePath:w?.basePath,caCertPath:w?.caCertPath});V(Q.STORAGE,`CA certificate path: ${Y}`,w?.verbose);let A=TJ.dirname(Y);if(!m$.existsSync(A))V(Q.STORAGE,`Creating CA certificate directory: ${A}`,w?.verbose),m$.mkdirSync(A,{recursive:!0});return V(Q.STORAGE,"Writing CA certificate file",w?.verbose),m$.writeFileSync(Y,$),V(Q.STORAGE,"CA certificate stored successfully",w?.verbose),Y}function EU($){let w;if($.startsWith("-----BEGIN CERTIFICATE-----"))w=$;else w=pz($);return new e7.X509Certificate(w)}function KU($){return EU($).fingerprint256.replace(/:/g,"").toUpperCase()}function DJ($){return X9(EU($).subject)}function $T($){let w=[],Y=$.split(`
133
+ `);for(let A of Y){let[U,...X]=A.split("="),J=X.join("=");if(U&&J)w.push({shortName:U.trim(),value:J.trim()})}return w}function X9($){return $T($).find((w)=>w.shortName==="CN")?.value||""}function wT($){let w=[],Y=X9($.subject);if(Y&&!/^\d+\.\d+\.\d+\.\d+$/.test(Y))w.push(Y);let A=$.subjectAltName;if(A){let U=A.split(", ");for(let X of U)if(X.startsWith("DNS:"))w.push(X.slice(4))}return[...new Set(w)]}function ZJ($,w){let Y=EU($),A=wT(Y);for(let U of A){if(U===w)return!0;if(U.startsWith("*.")){let X=U.slice(2);if(w.endsWith(X)&&w.indexOf(".")===w.lastIndexOf("."))return!0}}return!1}async function AT($,w){if(fU.platform()!=="darwin")return!1;try{let Y=KU($);if(!Y)return V(Q.TRUST,"Could not extract certificate fingerprint",w),!1;try{if(YT("security find-certificate -a -Z 2>/dev/null || true").toString().split(`
134
+ `).some((A)=>{let U=A.match(/SHA-256 hash:\s*([A-F0-9]+)/i);return!!U&&U[1].toUpperCase()===Y}))return V(Q.TRUST,"Certificate fingerprint found in system keychain",w),!0}catch{}return V(Q.TRUST,"Certificate fingerprint not found in system keychain",w),!1}catch(Y){return V(Q.TRUST,`Error checking certificate trust: ${Y}`,w),!1}}async function xJ($,w,Y){V(Q.TRUST,`Adding certificate to system trust store with options: ${GU(Y)}`,Y?.verbose),V(Q.TRUST,"Storing certificate and private key",Y?.verbose);let A=A9($,Y);V(Q.TRUST,"Storing CA certificate",Y?.verbose);let U=U9(w,Y),X=fU.platform();V(Q.TRUST,`Detected platform: ${X}`,Y?.verbose);let J=fT[X];if(!J){let W=`Unsupported platform: ${X}`;throw V(Q.TRUST,`Error: ${W}`,Y?.verbose),Error(W)}return await J.addCertificate(U,Y),V(Q.TRUST,"Certificate successfully added to system trust store",Y?.verbose),A}var XE,WU,ej="https://acme-staging-v02.api.letsencrypt.org/directory",$z="https://acme-v02.api.letsencrypt.org/directory",gA,zE="1.2.840.10045.2.1",FE="1.2.840.10045.3.1.7",GE="1.2.840.10045.4.3.2",EE="2.5.4.3",KE="1.2.840.113549.1.9.14",TE="2.5.29.17",aA,NJ,fK,WK=($)=>$,jK=($,w)=>{for(var Y in w)fK($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:BK.bind(w,Y)})},zK=($,w)=>()=>($&&(w=$($=0)),w),Gz,Iz,j1,WY,yz,uK,iK,Dj,cA,UJ,S0,a,cK,Zj,vK,xj,mK,dK,n8,gK,Pj,bj,p8,lK,nK,pK,tK,vA,Cz,rK,_0,aK,sK,uj,mA,XJ,H0,P,oK,ij,eK,cj,$7,w7,t8,Y7,vj,mj,A7,r8,U7,X7,J7,f7,W7,dA,hz,B7,j7="0.15.6",s0,wU,XY,JJ,fJ,YU,WJ,BJ,JY,jJ,zJ,jw,Vz,Lz,K$,d$,Qz,Oz,z7,G7,Sz,AU,Ny,y0,i,qy,K7,Ry,T7,My,Iy,dj,yy,H7,N7,Cy,gj,hy,Vy,Ly,Qy,Oy,a8,q7,Sy,N$,kz,UU,Dz,Zz,VJ,xz,Pz,XU,bz,uz,z1,V7,u$,_y,ky,Dy,lz,B0,T$,Q,B1,_7,lj="[redacted]",k7,D7,H$,v0,UT,XT,JT,fT;var J9=j0(()=>{XE=UE(import.meta.url);WU=new AY;gA=class gA extends Error{problem;httpStatus;constructor($,w,Y){super($);this.name="AcmeError",this.problem=w,this.httpStatus=Y}};aA=new zz,NJ=new Fz,fK=Object.defineProperty;Gz={};jK(Gz,{withErrorRecovery:()=>Tz,tryLoadConfig:()=>ZK,loadConfigWithResult:()=>kK,loadConfig:()=>Mz,isRetryableError:()=>VK,isConfigNotFoundError:()=>hK,isBunfigError:()=>Hz,globalPerformanceMonitor:()=>WY,globalCache:()=>j1,getEnvOrDefault:()=>LK,generateConfigTypes:()=>xK,defaultGeneratedDir:()=>Oz,defaultConfigDir:()=>Qz,deepMergeWithArrayStrategy:()=>yJ,deepMerge:()=>Nz,createLibraryConfig:()=>PK,config:()=>DK,bunfigPlugin:()=>bK,applyEnvVarsToConfig:()=>wY,TypeGenerationError:()=>BJ,SchemaValidationError:()=>JY,PluginError:()=>zJ,PerformanceMonitor:()=>RJ,FileSystemError:()=>WJ,ErrorFactory:()=>jw,EnvVarError:()=>YU,EnvProcessor:()=>jU,ConfigValidator:()=>CJ,ConfigValidationError:()=>JJ,ConfigNotFoundError:()=>wU,ConfigMergeError:()=>fJ,ConfigLoader:()=>hJ,ConfigLoadError:()=>XY,ConfigFileLoader:()=>zU,ConfigCache:()=>qJ,CacheUtils:()=>yz,BunfigError:()=>s0,BrowserConfigError:()=>jJ,ArrayMergeStrategies:()=>Vz});z7=zK(async()=>{Iz=import.meta.require,j1=new qJ,WY=new RJ,yz={createKey:FK,isEquivalent:GK,estimateMemoryUsage:EK},uK=tA(YJ.cwd(),"config"),iK=tA(YJ.cwd(),"src/generated"),Dj=pA.env.CLARITY_LOG_DIR||LE(HK(),"logs"),cA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:Dj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},UJ=await NK(),S0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},a=S0,cK=S0.red,Zj=S0.green,vK=S0.yellow,xj=S0.blue,mK=S0.magenta,dK=S0.cyan,n8=S0.white,gK=S0.gray,Pj=S0.bgRed,bj=S0.bgYellow,p8=S0.bold,lK=S0.dim,nK=S0.italic,pK=S0.underline,tK=S0.reset,vA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},Cz={debug:"\uD83D\uDD0D",info:xj("ℹ"),success:Zj("✓"),warning:bj(n8(p8(" WARN "))),error:Pj(n8(p8(" ERROR ")))},rK=new oA("stacks"),_0=new oA("bunfig",{showTags:!0}),aK=i0(UY.cwd(),"config"),sK=i0(UY.cwd(),"src/generated"),uj=nA.env.CLARITY_LOG_DIR||hE(IK(),"logs"),mA={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:uj,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},XJ=await yK(),H0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},P=H0,oK=H0.red,ij=H0.green,eK=H0.yellow,cj=H0.blue,$7=H0.magenta,w7=H0.cyan,t8=H0.white,Y7=H0.gray,vj=H0.bgRed,mj=H0.bgYellow,A7=H0.bgGray,r8=H0.bold,U7=H0.dim,X7=H0.italic,J7=H0.underline,f7=H0.strikethrough,W7=H0.reset,dA={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},hz={debug:"\uD83D\uDD0D",info:cj("ℹ"),success:ij("✓"),warning:mj(t8(r8(" WARN "))),error:vj(t8(r8(" ERROR ")))},B7=new $U("stacks"),s0=class extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}},wU=class extends s0{code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y?` or alias "${Y}"`:"";super(`Configuration "${$}"${A} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}},XY=class extends s0{code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}},JJ=class extends s0{code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},fJ=class extends s0{code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},YU=class extends s0{code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}},WJ=class extends s0{code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},BJ=class extends s0{code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},JY=class extends s0{code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}},jJ=class extends s0{code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}},zJ=class extends s0{code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},jw={configNotFound($,w,Y){return new wU($,w,Y)},configLoad($,w,Y){return new XY($,w,Y)},configValidation($,w,Y){return new JJ($,w,Y)},configMerge($,w,Y,A){return new fJ($,w,Y,A)},envVar($,w,Y,A){return new YU($,w,Y,A)},fileSystem($,w,Y){return new WJ($,w,Y)},typeGeneration($,w,Y){return new BJ($,w,Y)},schemaValidation($,w,Y){return new JY($,w,Y)},browserConfig($,w,Y,A){return new jJ($,w,Y,A)},plugin($,w,Y){return new zJ($,w,Y)}},Vz={replace:"replace",concat:"concat",smart:"smart"},Lz=/^https?:\/\//,K$=new $U("bunfig",{showTags:!0}),d$=new hJ,Qz=c0(Vw.cwd(),"config"),Oz=c0(Vw.cwd(),"src/generated")});G7=rA.env.CLARITY_LOG_DIR||rE(F7(),"logs"),Sz={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:G7,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},AU={...Sz},Ny=(async()=>{try{let{loadConfig:$}=await z7().then(()=>Gz),w=await $({name:"clarity",alias:"logging",defaultConfig:Sz,cwd:rA.cwd()});if(w)Object.assign(AU,w)}catch{}return AU})();y0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},i=y0,qy=y0.red,K7=y0.green,Ry=y0.yellow,T7=y0.blue,My=y0.magenta,Iy=y0.cyan,dj=y0.white,yy=y0.gray,H7=y0.bgRed,N7=y0.bgYellow,Cy=y0.bgGray,gj=y0.bold,hy=y0.dim,Vy=y0.italic,Ly=y0.underline,Qy=y0.strikethrough,Oy=y0.reset,a8={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},q7={debug:"\uD83D\uDD0D",info:T7("ℹ"),success:K7("✓"),warning:N7(dj(gj(" WARN "))),error:H7(dj(gj(" ERROR ")))};Sy=new FU("stacks");N$=class N$ extends Error{timestamp;context;constructor($,w={}){super($);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=w,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let $=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([w,Y])=>`${w}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${$}`}};kz=class kz extends N${code="CONFIG_NOT_FOUND";constructor($,w,Y){let A=Y===void 0?[]:Array.isArray(Y)?Y.filter(Boolean):[Y],U="";if(A.length===1)U=` or alias "${A[0]}"`;else if(A.length>1)U=` or aliases ${A.map((X)=>`"${X}"`).join(", ")}`;super(`Configuration "${$}"${U} not found`,{configName:$,alias:Y,searchPaths:w,searchPathCount:w.length})}};UU=class UU extends N${code="CONFIG_LOAD_ERROR";constructor($,w,Y){super(`Failed to load configuration from "${$}": ${w.message}`,{configPath:$,configName:Y,originalError:w.name,originalMessage:w.message});this.cause=w}};Dz=class Dz extends N${code="CONFIG_VALIDATION_ERROR";constructor($,w,Y){super(`Configuration validation failed for "${$}"`,{configPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};Zz=class Zz extends N${code="CONFIG_MERGE_ERROR";constructor($,w,Y,A){super(`Failed to merge configuration from "${$}" with "${w}": ${Y.message}`,{sourcePath:$,targetPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};VJ=class VJ extends N${code="ENV_VAR_ERROR";constructor($,w,Y,A){super(`Failed to parse environment variable "${$}" with value "${w}" as ${Y}`,{envKey:$,envValue:w,expectedType:Y,configName:A})}};xz=class xz extends N${code="FILE_SYSTEM_ERROR";constructor($,w,Y){super(`File system ${$} failed for "${w}": ${Y.message}`,{operation:$,path:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};Pz=class Pz extends N${code="TYPE_GENERATION_ERROR";constructor($,w,Y){super(`Failed to generate types from "${$}" to "${w}": ${Y.message}`,{configDir:$,outputPath:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};XU=class XU extends N${code="SCHEMA_VALIDATION_ERROR";constructor($,w,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:$,configName:Y,validationErrors:w,errorCount:w.length})}};bz=class bz extends N${code="BROWSER_CONFIG_ERROR";constructor($,w,Y,A){super(`Failed to fetch configuration from "${$}": ${w} ${Y}`,{endpoint:$,status:w,statusText:Y,configName:A})}};uz=class uz extends N${code="PLUGIN_ERROR";constructor($,w,Y){super(`Plugin "${$}" failed during ${w}: ${Y.message}`,{pluginName:$,operation:w,originalError:Y.name,originalMessage:Y.message});this.cause=Y}};z1={configNotFound($,w,Y){return new kz($,w,Y)},configLoad($,w,Y){return new UU($,w,Y)},configValidation($,w,Y){return new Dz($,w,Y)},configMerge($,w,Y,A){return new Zz($,w,Y,A)},envVar($,w,Y,A){return new VJ($,w,Y,A)},fileSystem($,w,Y){return new xz($,w,Y)},typeGeneration($,w,Y){return new Pz($,w,Y)},schemaValidation($,w,Y){return new XU($,w,Y)},browserConfig($,w,Y,A){return new bz($,w,Y,A)},plugin($,w,Y){return new uz($,w,Y)}};V7=/^https?:\/\//;u$=new FU("bunfig",{showTags:!0});_y=new gz;ky=X$(BU.cwd(),"config"),Dy=X$(BU.cwd(),"src/generated"),lz={altNameIPs:["127.0.0.1"],altNameURIs:["localhost"],organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",commonName:"tlsx.localhost",validityDays:825,hostCertCN:"tlsx.localhost",domain:"tlsx.localhost",rootCA:{certificate:"",privateKey:""},basePath:"",caCertPath:_8.join(S8.homedir(),".tlsx","ssl","tlsx.localhost.ca.crt"),certPath:_8.join(S8.homedir(),".tlsx","ssl","tlsx.localhost.crt"),keyPath:_8.join(S8.homedir(),".tlsx","ssl","tlsx.localhost.crt.key"),verbose:!1},B0=lz,T$={DEFAULT_KEY_SIZE:2048,DEFAULT_VALIDITY_DAYS:825,DEFAULT_CA_VALIDITY_YEARS:100,DEFAULT_NOT_BEFORE_DAYS:2,LINUX_TRUST_ARGS:"TC, C, C",LINUX_CERT_DB_FILENAME:"cert9.db"},Q={CERT:"cert",CA:"ca",STORAGE:"storage",TRUST:"trust"},B1={info:(...$)=>console.log(...$),warn:(...$)=>console.warn(...$),success:(...$)=>console.log(...$),error:(...$)=>console.error(...$),debug:(...$)=>console.debug(...$)};_7=S7(Q7);k7=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),D7=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/;H$={SEQUENCE:48,SET:49,INTEGER:2,BIT_STRING:3,OCTET_STRING:4,NULL:5,OID:6,UTF8_STRING:12,PRINTABLE_STRING:19,IA5_STRING:22,UTC_TIME:23,GENERALIZED_TIME:24,CONTEXT_0:160,CONTEXT_2:130,CONTEXT_3:163},v0={SHA256_WITH_RSA:"1.2.840.113549.1.1.11",RSA_ENCRYPTION:"1.2.840.113549.1.1.1",COMMON_NAME:"2.5.4.3",COUNTRY:"2.5.4.6",LOCALITY:"2.5.4.7",STATE:"2.5.4.8",ORGANIZATION:"2.5.4.10",ORGANIZATIONAL_UNIT:"2.5.4.11",BASIC_CONSTRAINTS:"2.5.29.19",KEY_USAGE:"2.5.29.15",EXTENDED_KEY_USAGE:"2.5.29.37",SUBJECT_ALT_NAME:"2.5.29.17",SUBJECT_KEY_IDENTIFIER:"2.5.29.14",AUTHORITY_KEY_IDENTIFIER:"2.5.29.35",SERVER_AUTH:"1.3.6.1.5.5.7.3.1",CLIENT_AUTH:"1.3.6.1.5.5.7.3.2"};UT={platform:"darwin",async addCertificate($,w){if(await AT($,w?.verbose)){V(Q.TRUST,"Certificate is already trusted, skipping trust store update",w?.verbose),B1.success("Certificate is already trusted in system keychain");return}V(Q.TRUST,"Adding certificate to macOS keychain",w?.verbose),await Bw(`sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ${$}`)},async removeCertificate($,w,Y){let A=Y||B0.commonName;V(Q.TRUST,`Removing certificate ${A} from macOS keychain`,w?.verbose);try{await Bw(`sudo security delete-certificate -c "${A}" /Library/Keychains/System.keychain`),V(Q.TRUST,`Removed certificate ${A} from macOS keychain`,w?.verbose)}catch(U){throw V(Q.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},XT={platform:"win32",async addCertificate($,w){V(Q.TRUST,"Adding certificate to Windows certificate store",w?.verbose),await Bw(`certutil -f -v -addstore -enterprise Root ${$}`)},async removeCertificate($,w,Y){let A=Y||B0.commonName;V(Q.TRUST,`Removing certificate ${A} from Windows certificate store`,w?.verbose);try{await Bw(`certutil -delstore -enterprise Root "${A}"`),V(Q.TRUST,`Removed certificate ${A} from Windows certificate store`,w?.verbose)}catch(U){throw V(Q.TRUST,`Error removing certificate: ${U}`,w?.verbose),U}}},JT={platform:"linux",async addCertificate($,w){V(Q.TRUST,"Adding certificate to Linux certificate store",w?.verbose);let Y=fU.homedir(),A=T$.LINUX_CERT_DB_FILENAME,U=T$.LINUX_TRUST_ARGS;V(Q.TRUST,`Searching for certificate databases in ${Y}`,w?.verbose);let X=EJ(Y,A);if(X.length===0){B1.warn("No certificate databases found. Certificate may not be trusted by the system.");return}for(let J of X){V(Q.TRUST,`Processing certificate database in ${J}`,w?.verbose);try{V(Q.TRUST,`Attempting to delete existing cert for ${B0.commonName}`,w?.verbose),await Bw(`certutil -d sql:${J} -D -n ${B0.commonName}`)}catch(W){V(Q.TRUST,`Warning: Error deleting existing cert: ${W}`,w?.verbose),console.warn(`Error deleting existing cert: ${W}`)}V(Q.TRUST,`Adding new certificate to ${J}`,w?.verbose),await Bw(`certutil -d sql:${J} -A -t ${U} -n ${B0.commonName} -i ${$}`),B1.info(`Cert added to ${J}`)}},async removeCertificate($,w,Y){let A=Y||B0.commonName;V(Q.TRUST,`Removing certificate ${A} from Linux certificate store`,w?.verbose);let U=fU.homedir(),X=T$.LINUX_CERT_DB_FILENAME;V(Q.TRUST,`Searching for certificate databases in ${U}`,w?.verbose);let J=EJ(U,X);if(J.length===0){B1.warn("No certificate databases found. Cannot remove certificate.");return}for(let W of J){V(Q.TRUST,`Processing certificate database in ${W}`,w?.verbose);try{await Bw(`certutil -d sql:${W} -D -n "${A}"`),B1.info(`Cert removed from ${W}`)}catch(f){V(Q.TRUST,`Error removing cert from ${W}: ${f}`,w?.verbose),console.warn(`Error removing cert from ${W}: ${f}`)}}}},fT={darwin:UT,win32:XT,linux:JT}});var TU=j0(()=>{J9()});import{homedir as PJ}from"node:os";import{join as bJ,resolve as QC}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",BT,uJ;var iJ=j0(()=>{V8();BT={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:bJ(PJ(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:bJ(PJ(),".stacks","ssl","stacks.localhost.crt"),keyPath:bJ(PJ(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0},uJ=BT});function Lw($){try{return KU($)}catch{return null}}function cJ($){try{return DJ($)||null}catch{return null}}function HU($,w){try{return w.every((Y)=>ZJ($,Y))}catch{return!1}}var NU=j0(()=>{TU()});import{existsSync as f9,statSync as W9}from"fs";import{existsSync as Xf,mkdirSync as KT,readdirSync as TT,writeFileSync as HT}from"fs";import{homedir as G1}from"os";import{dirname as B9,resolve as d0}from"path";import Qw from"process";import{join as NT,relative as qT,resolve as j9}from"path";import xU from"process";import{existsSync as n9,mkdirSync as vC,readdirSync as mC,writeFileSync as dC}from"fs";import{homedir as vJ}from"os";import{dirname as nC,resolve as m0}from"path";import jY from"process";import{join as RT,relative as MT,resolve as z9}from"path";import PU from"process";import{existsSync as p9,mkdirSync as sC,readdirSync as oC,writeFileSync as eC}from"fs";import{dirname as wh,resolve as bU}from"path";import Jf from"process";import{Buffer as Fw}from"buffer";import{createCipheriv as IT,createDecipheriv as yT,randomBytes as mJ}from"crypto";import{closeSync as dJ,createReadStream as F9,createWriteStream as CT,existsSync as gJ,fsyncSync as G9,openSync as E9,writeFileSync as hT}from"fs";import{access as VT,constants as K9,mkdir as LT,readdir as qU,rename as T9,stat as E1,unlink as RU,writeFile as lJ}from"fs/promises";import{join as K1}from"path";import k0 from"process";import{pipeline as QT}from"stream/promises";import{createGzip as H9}from"zlib";import T1 from"process";import n$ from"process";import{Buffer as g$}from"buffer";import{createCipheriv as OT,createDecipheriv as ST,randomBytes as nJ}from"crypto";import{closeSync as pJ,createReadStream as N9,createWriteStream as _T,existsSync as MU,fsyncSync as q9,openSync as R9,writeFileSync as kT}from"fs";import{access as DT,constants as M9,mkdir as ZT,readdir as IU,rename as I9,stat as H1,unlink as yU,writeFile as tJ}from"fs/promises";import{isAbsolute as xT,join as N1,resolve as PT}from"path";import D from"process";import{pipeline as bT}from"stream/promises";import{createGzip as y9}from"zlib";import q1 from"process";import p$ from"process";import CU from"process";import{existsSync as hU}from"fs";import{resolve as rJ}from"path";import{existsSync as uT}from"fs";import{existsSync as iT,readdirSync as cT}from"fs";import{extname as aJ,resolve as C9}from"path";import vT from"process";import{join as mH,relative as dH,resolve as P9}from"path";import gU from"process";import{Buffer as l$}from"buffer";import{createCipheriv as nH,createDecipheriv as pH,randomBytes as wf}from"crypto";import{closeSync as Yf,createReadStream as b9,createWriteStream as tH,existsSync as LU,fsyncSync as u9,openSync as i9,writeFileSync as rH}from"fs";import{access as aH,constants as c9,mkdir as sH,readdir as QU,rename as v9,stat as R1,unlink as OU,writeFile as Af}from"fs/promises";import{isAbsolute as oH,join as M1,resolve as eH}from"path";import Z from"process";import{pipeline as $N}from"stream/promises";import{createGzip as m9}from"zlib";import I1 from"process";import t$ from"process";function FT($,w){this[$]=zT.bind(null,w)}class Tf{cache=new Map;totalHits=0;totalMisses=0;options;constructor($={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...$}}generateKey($,w){let Y=w?`:${w}`:"";return`${this.options.keyPrefix}${$}${Y}`}isExpired($){return Date.now()-$.timestamp.getTime()>$.ttl}estimateSize($){try{return JSON.stringify($).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let $=Array.from(this.cache.entries()).sort(([,Y],[,A])=>Y.timestamp.getTime()-A.timestamp.getTime()),w=$.length-this.options.maxSize+1;for(let Y=0;Y<w;Y++)this.cache.delete($[Y][0])}set($,w,Y,A){if(!this.options.enabled)return;let U=this.generateKey($,Y),X=A??this.options.ttl,J=this.estimateSize(w);this.cache.set(U,{value:w,timestamp:new Date,ttl:X,hits:0,size:J}),this.evictIfNeeded()}get($,w){if(!this.options.enabled){this.totalMisses++;return}let Y=this.generateKey($,w),A=this.cache.get(Y);if(!A){this.totalMisses++;return}if(this.isExpired(A)){this.cache.delete(Y),this.totalMisses++;return}return A.hits++,this.totalHits++,A.value}isFileModified($,w){try{if(!f9($))return!0;return W9($).mtime>w}catch{return!0}}getWithFileCheck($,w){let Y=this.get($,w);if(!Y)return;if(this.isFileModified(w,Y.fileTimestamp)){this.delete($,w);return}return Y.value}setWithFileCheck($,w,Y,A){try{let U=f9(Y)?W9(Y):null,X=U?U.mtime:new Date;this.set($,{value:w,fileTimestamp:X},Y,A)}catch{this.set($,w,Y,A)}}delete($,w){let Y=this.generateKey($,w);return this.cache.delete(Y)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let $=0;for(let[w,Y]of this.cache.entries())if(this.isExpired(Y))this.cache.delete(w),$++;return $}getStats(){let $=Array.from(this.cache.values()),w=$.reduce((A,U)=>A+U.size,0),Y=$.map((A)=>A.timestamp).sort();return{size:w,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:Y[0],newestEntry:Y[Y.length-1]}}export(){let $={};for(let[w,Y]of this.cache.entries())$[w]={value:Y.value,timestamp:Y.timestamp.toISOString(),ttl:Y.ttl,hits:Y.hits,size:Y.size};return $}import($){this.cache.clear();for(let[w,Y]of Object.entries($))if(typeof Y==="object"&&Y!==null){let A=Y;this.cache.set(w,{value:A.value,timestamp:new Date(A.timestamp),ttl:A.ttl,hits:A.hits,size:A.size})}}}class Hf{metrics=[];maxMetrics=1000;async track($,w,Y={}){let A=performance.now(),U=new Date;try{let X=await w(),J=performance.now()-A;return this.recordMetric({operation:$,duration:J,timestamp:U,...Y}),X}catch(X){let J=performance.now()-A;throw this.recordMetric({operation:`${$}:error`,duration:J,timestamp:U,...Y}),X}}recordMetric($){if(this.metrics.push($),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats($){let w=$?this.metrics.filter((U)=>U.operation===$):this.metrics;if(w.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let Y=w.map((U)=>U.duration),A=Y.reduce((U,X)=>U+X,0);return{count:w.length,averageDuration:A/w.length,minDuration:Math.min(...Y),maxDuration:Math.max(...Y),totalDuration:A,recentMetrics:w.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations($){return this.metrics.filter((w)=>w.duration>$)}}function mT($,w={}){let A=Object.keys(w).sort().map((U)=>`${U}:${w[U]}`).join("|");return A?`${$}:${A}`:$}function dT($,w){try{return JSON.stringify($)===JSON.stringify(w)}catch{return $===w}}function gT($){return $.getStats().size*2}function Nf($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&w0(w[0])&&"id"in w[0]&&w[0].id===3&&w0(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(w0(w)&&w0($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(w0($)&&"arr"in $&&Array.isArray($.arr)&&w0(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&w0(w[0])&&w0($[0])){let A=[...w];for(let U of $)if(w0(U)&&"name"in U){if(!A.find((J)=>w0(J)&&("name"in J)&&J.name===U.name))A.push(U)}else if(w0(U)&&"path"in U){if(!A.find((J)=>w0(J)&&("path"in J)&&J.path===U.path))A.push(U)}else if(!A.some((X)=>uU(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!w0(w)||!w0($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(w0(U)&&w0(Y[A]))Y[A]=Nf(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&w0(U[0])&&w0(Y[A][0])){let X=[...U];for(let J of Y[A])if(w0(J)&&"name"in J){if(!X.find((f)=>w0(f)&&("name"in f)&&f.name===J.name))X.push(J)}else if(w0(J)&&"path"in J){if(!X.find((f)=>w0(f)&&("path"in f)&&f.path===J.path))X.push(J)}else if(!X.some((W)=>uU(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function uU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!uU($[Y],w[Y]))return!1;return!0}if(w0($)&&w0(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!uU($[U],w[U]))return!1}return!0}return!1}function w0($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function lT($,w){if(!p9($))return null;try{let Y=await import($),A=Y.default||Y;if(typeof A!=="object"||A===null||Array.isArray(A))return null;try{return Nf(w,A)}catch{return null}}catch{return null}}async function nT({name:$="",cwd:w,defaultConfig:Y}){let A=w||Jf.cwd(),U=[".ts",".js",".mjs",".cjs",".json"],X=[`${$}.config`,`.${$}.config`,$,`.${$}`];for(let J of X)for(let W of U){let f=bU(A,`${J}${W}`),B=await lT(f,Y);if(B!==null)return B}try{let J=bU(A,"package.json");if(p9(J)){let f=(await import(J))[$];if(f&&typeof f==="object"&&!Array.isArray(f))try{return Nf(Y,f)}catch{}}}catch{}return Y}function pT($,w={}){let Y=PU.cwd();while(Y.includes("storage"))Y=z9(Y,"..");let A=z9(Y,$||"");if(w?.relative)return MT(PU.cwd(),A);return A}async function tT(){try{let $=await nT({name:"clarity",defaultConfig:_U,cwd:PU.cwd(),endpoint:"",headers:{}});return{..._U,...$}}catch{return _U}}function J0(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function rT(){if(n$.env.NODE_ENV==="test"||n$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof n$<"u"){let $=n$.type;if($==="renderer"||$==="worker")return!1;return!!(n$.versions&&(n$.versions.node||n$.versions.bun))}return!1}class t9{async format($){let w=await rT(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:T1.pid,hostname:w(),environment:T1.env.NODE_ENV||"development",platform:T1.platform,version:T1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:T1.env.NODE_ENV||T1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class iU{name;fileLocks=new Map;currentKeyId=null;keys=new Map;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...Wf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new t9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??k0.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...kU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...kU};return{...kU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Wf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await VT(this.config.logDirectory,K9.F_OK|K9.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await LT(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:Fw.from($);try{if(!gJ(this.currentLogFile))await lJ(this.currentLogFile,"",{mode:420});if(U=E9(this.currentLogFile,"a",420),hT(U,f,{flag:"a"}),G9(U),U!==void 0)dJ(U),U=void 0;if((await E1(this.currentLogFile)).size===0){if(await lJ(this.currentLogFile,f,{flag:"w",mode:420}),(await E1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{dJ(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return K1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return K1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return K1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(J0())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return mJ(16).toString("hex")}generateKey(){return mJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=mJ(16),A=IT("aes-256-gcm",w,Y),U=Fw.concat([A.update($,"utf8"),A.final()]),X=A.getAuthTag();return{encrypted:Fw.concat([Y,U,X]),iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=H9(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(Fw.from(Fw.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(J0())return;let $=await E1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await qU(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await E1(Y).catch(()=>null))try{if(await T9(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await RU(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await lJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await E1(Y).catch(()=>null))await T9(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await qU(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await RU(K1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=F9($),A=CT(w),U=H9();await QT(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);await this.writeToFile(A),console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated)await this.writeToFile(w),console.log(w);else{if(this.logBuffer.length>=this.fingersCrossedConfig.bufferSize)this.logBuffer.shift();let Y={timestamp:new Date,level:$,message:w,name:this.name};this.logBuffer.push(Y)}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;return this.getLevelValue($)>=this.getLevelValue(this.fingersCrossedConfig.activationLevel)}getLevelValue($){return{debug:0,info:1,success:2,warning:3,error:4}[$]}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),gJ(this.currentLogFile))try{let $=E9(this.currentLogFile,"r+");G9($),dJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!J0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await qU(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await RU(K1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.fancy?s.gray($.toLocaleTimeString()):$.toLocaleTimeString()}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=k0.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${s.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);if(this.fancy&&!J0()){let B=U2[$],j=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",z;switch($){case"debug":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:s.gray(J),level:$}),console.error(z);break;case"info":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z);break;case"success":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:s.green(J),level:$}),console.error(z);break;case"warning":z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.warn(z);break;case"error":if(z=this.formatConsoleMessage({timestamp:U,icon:B,tag:j,message:J,level:$}),console.error(z),W){let G=W.split(`
135
+ `);for(let F of G)if(F.trim()&&!F.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:s.gray(` ${F}`),level:$,showTimestamp:!1}))}break}}else if(!J0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let f=`${X} ${this.environment}.${$.toUpperCase()}: ${J}
134
136
  `;if(W)f+=`${W}
135
- `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!U0()){let A=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:a.blue("◐"),tag:A,message:`${a.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),X=Math.round(Y-w),J=`${$} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
136
- `,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!U0()){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}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!U0())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new DX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(U0())throw Error("createReadStream is not supported in browser environments");if(!DU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return Y2(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=Fw.isBuffer($)?$:Fw.from($,"base64"),X=Y.slice(0,16),J=Y.slice(-16),U=Y.slice(16,-16),W=J7("aes-256-gcm",A,X);return W.setAuthTag(J),Fw.concat([W.update(U),W.final()]).toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return U0()}isServerMode(){return!U0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w);if(this.fancy&&!U0()){let J=$.split(`
137
- `),U=Math.max(...J.map((j)=>j.length))+2,W=`┌${"─".repeat(U)}┐`,f=`└${"─".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:A,message:a.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:A,message:a.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:A,message:a.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:A,message:a.cyan(f),showTimestamp:!1}))}else if(!U0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${$}`);let X=`${Y} ${this.environment}.INFO: [BOX] ${$}
138
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}async prompt($){if(U0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${a.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let X=Y.toString().trim().toLowerCase();Z0.stdin.removeListener("data",A);try{if(typeof Z0.stdin.setRawMode==="function")Z0.stdin.setRawMode(!1)}catch{}Z0.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof Z0.stdin.setRawMode==="function")Z0.stdin.setRawMode(!0)}catch{}Z0.stdin.resume(),Z0.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let U=/%([sdijfo%])/g,W=0;if(A=$.replace(U,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)A+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!U0()){let U=this.options.showTags!==!1&&this.name?a.gray(this.formatTag(this.name)):"",W=a.blue("◐");console.error(`${W} ${U} ${a.cyan(A)}`)}let J=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${A}
139
- `.replace(this.ANSI_PATTERN,"");await this.writeToFile(J)}progress($,w=""){if(!this.enabled||!this.fancy||U0()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let A=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:A,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(U,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,U)),W!==void 0)this.activeProgressBar.message=W;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},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,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||U0())return;Z0.stdout.write(`${"\r".padEnd(Z0.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||U0()||!Z0.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),X=$.barLength-Y,J=a.green("━".repeat(Y)),U=a.gray("━".repeat(X)),W=`[${J}${U}]`,f=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",j=w||A===100?a.green("✓"):a.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${a.gray(this.formatTag(this.name))}`:"",E=`\r${j}${z} ${W} ${f}${B}`,F=Z0.stdout.columns||80,T=" ".repeat(Math.max(0,F-E.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${E}${T}`,Z0.stdout.write($.lastRenderedLine),w)Z0.stdout.write(`
140
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||U0()||!Z0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(U0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await EX(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let J=T1(this.config.logDirectory,Y);if($.before)try{if((await K1(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await GX(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function CX($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&p(w[0])&&"id"in w[0]&&w[0].id===3&&p(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(p(w)&&p($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(p($)&&"arr"in $&&Array.isArray($.arr)&&p(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&p(w[0])&&p($[0])){let Y=[...w];for(let X of $)if(p(X)&&"name"in X){if(!Y.find((U)=>p(U)&&("name"in U)&&U.name===X.name))Y.push(X)}else if(p(X)&&"path"in X){if(!Y.find((U)=>p(U)&&("path"in U)&&U.path===X.path))Y.push(X)}else if(!Y.some((J)=>ZX(J,X)))Y.push(X);return Y}if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}if(!p(w)||!p($))return w;let A={...$};for(let Y in w)if(Object.prototype.hasOwnProperty.call(w,Y)){let X=w[Y];if(X===null||X===void 0)continue;else if(p(X)&&p(A[Y]))A[Y]=CX(A[Y],X);else if(Array.isArray(X)&&Array.isArray(A[Y]))if(X.length>0&&A[Y].length>0&&p(X[0])&&p(A[Y][0])){let J=[...X];for(let U of A[Y])if(p(U)&&"name"in U){if(!J.find((f)=>p(f)&&("name"in f)&&f.name===U.name))J.push(U)}else if(p(U)&&"path"in U){if(!J.find((f)=>p(f)&&("path"in f)&&f.path===U.path))J.push(U)}else if(!J.some((W)=>ZX(W,U)))J.push(U);A[Y]=J}else if(X.every((J)=>typeof J==="string")&&A[Y].every((J)=>typeof J==="string")){let J=[...X];for(let U of A[Y])if(!J.includes(U))J.push(U);A[Y]=J}else A[Y]=X;else A[Y]=X}return A}function Wf($,w,A="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return A==="replace"?w:CX($,w);if(Array.isArray($))return A==="replace"?w:CX($,w);if(!p(w)||!p($))return w;let Y={...$};for(let X of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,X))continue;let J=w[X],U=Y[X];if(J===null||J===void 0)continue;if(Array.isArray(J)||Array.isArray(U))if(A==="replace")Y[X]=J;else Y[X]=CX(U,J);else if(p(J)&&p(U))Y[X]=Wf(U,J,A);else Y[X]=J}return Y}function ZX($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!ZX($[A],w[A]))return!1;return!0}if(p($)&&p(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!ZX($[X],w[X]))return!1}return!0}return!1}function p($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function qX($,w,A="replace"){if(!b2($))return null;try{let Y=await import($),X=Y.default||Y;if(typeof X!=="object"||X===null||Array.isArray(X))return null;try{return Wf(w,X,A)}catch{return null}}catch{return null}}function k7($,w,A=!1){if(!$)return w;let Y=$.toUpperCase().replace(/-/g,"_"),X={...w};function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${Y}_${z.map(E).join("_")}`,T=`${Y}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(A)P0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=J(j,z);else{let K=UA.env[F]||UA.env[T];if(K!==void 0){if(A)P0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((N)=>N.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return J(X)}async function D7({name:$="",alias:w,cwd:A,configDir:Y,defaultConfig:X,verbose:J=!1,checkEnv:U=!0,arrayStrategy:W="replace"}){let f=U&&typeof X==="object"&&X!==null&&!Array.isArray(X)?k7($,X,J):X,B=A||UA.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(J)P0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),E=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,d0(B,"config"),d0(B,".config"),Y?d0(B,Y):void 0].filter(Boolean)));for(let H of K){if(J)P0.info(`Searching for configuration in: ${H}`);let R=[d0(B,"config"),d0(B,".config")].concat(Y?[d0(B,Y)]:[]).includes(H)?[...z,...E,...F,...T]:[...E,...z,...T,...F];for(let M of R)for(let y of j){let I=d0(H,`${M}${y}`),C=await qX(I,f,W);if(C!==null){if(J)P0.success(`Configuration loaded from: ${I}`);return C}}}if($){let H=d0(SU(),".config",$),N=["config",`${$}.config`];if(w)N.push(`${w}.config`);if(J)P0.info(`Checking user config directory: ${H}`);for(let R of N)for(let M of j){let y=d0(H,`${R}${M}`),I=await qX(y,f,W);if(I!==null){if(J)P0.success(`Configuration loaded from user config directory: ${y}`);return I}}}if($){let H=d0(SU(),".config"),N=[`.${$}.config`];if(w)N.push(`.${w}.config`);if(J)P0.info(`Checking user config directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=d0(H,`${R}${M}`),I=await qX(y,f,W);if(I!==null){if(J)P0.success(`Configuration loaded from user config directory dotfile: ${y}`);return I}}}if($){let H=SU(),N=[`.${$}.config`,`.${$}`];if(w)N.push(`.${w}.config`),N.push(`.${w}`);if(J)P0.info(`Checking user home directory for dotfile configs: ${H}`);for(let R of N)for(let M of j){let y=d0(H,`${R}${M}`),I=await qX(y,f,W);if(I!==null){if(J)P0.success(`Configuration loaded from user home directory: ${y}`);return I}}}try{let H=d0(B,"package.json");if(b2(H)){let N=await import(H),R=N[$];if(!R&&w){if(R=N[w],R&&J)P0.success(`Using alias "${w}" configuration from package.json`)}if(R&&typeof R==="object"&&!Array.isArray(R))try{if(J)P0.success(`Configuration loaded from package.json: ${R===N[$]?$:w}`);return Wf(f,R,W)}catch(M){if(J)P0.warn("Failed to merge package.json config:",M)}}}catch(H){if(J)P0.warn("Failed to load package.json:",H)}if(J)P0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function Z7($,w={}){let A=QX.cwd();while(A.includes("storage"))A=w2(A,"..");let Y=w2(A,$||"");if(w?.relative)return w7(QX.cwd(),Y);return Y}async function x7(){try{let $=await D7({name:"clarity",alias:"logging",defaultConfig:LX,cwd:QX.cwd()});return{...LX,...$||{}}}catch{return LX}}function q0(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function P7(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p$<"u"){let $=p$.type;if($==="renderer"||$==="worker")return!1;return!!(p$.versions&&(p$.versions.node||p$.versions.bun))}return!1}class c2{async format($){let w=await P7(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:q1.pid,hostname:w(),environment:q1.env.NODE_ENV||"development",platform:q1.platform,version:q1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:q1.env.NODE_ENV||q1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class xX{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...oU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new c2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...OX,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...OX};return{...OX,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:oU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await K7(this.config.logDirectory,F2.F_OK|F2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await T7(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:g$.from($);try{if(!KX(this.currentLogFile))await bU(this.currentLogFile,"",{mode:420});if(X=z2(this.currentLogFile,"a",420),G7(X,f,{flag:"a"}),j2(X),X!==void 0)PU(X),X=void 0;if((await N1(this.currentLogFile)).size===0){if(await bU(this.currentLogFile,f,{flag:"w",mode:420}),(await N1(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 E=W*2**J;await new Promise((F)=>setTimeout(F,E)),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{PU(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}finally{this.pendingOperations.splice(Y,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return R1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return R1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return R1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.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 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 $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=xU(16),Y=z7("aes-256-gcm",w,A),X=g$.isBuffer($)?$:g$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=g$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=G2(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(g$.from(g$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let $=await N1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await TX(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await N1(A).catch(()=>null))try{if(await E2(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await HX(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await bU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await N1(A).catch(()=>null))await E2(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await TX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await HX(R1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=B2($),Y=E7(w),X=G2();await R7(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),KX(this.currentLogFile))try{let $=z2(this.currentLogFile,"r+");j2($),PU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await TX(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await HX(R1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?u.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let $=typeof Z.env.NO_COLOR<"u",w=Z.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof Z.stderr<"u"&&Z.stderr.isTTY||typeof Z.stdout<"u"&&Z.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=Z.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${u.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=u.underline(u.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\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}),w=w.replace(/`([^`]+)`/g,(A,Y)=>u.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>u.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>u.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>u.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>u.strikethrough(Y)),w}supportsHyperlinks(){if(q0())return!1;let $=Z.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=Z.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(H7(w)||w.startsWith("./")||w.startsWith("../"))w=N7(w);else return null;return KX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":a2[$],E=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:u.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:u.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
141
- `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:u.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!q0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}if(!this.shouldLog($))return;let j=`${J} ${this.environment}.${$.toUpperCase()}: ${B}
137
+ `;f=f.replace(this.ANSI_PATTERN,""),await this.writeToFile(f)}time($){let w=performance.now();if(this.fancy&&!J0()){let Y=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:s.blue("◐"),tag:Y,message:`${s.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
138
+ `,B=B.replace(this.ANSI_PATTERN,""),this.fancy&&!J0()){let j=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:s.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!J0())console.error(B.trim());await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new iU(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(J0())throw Error("createReadStream is not supported in browser environments");if(!gJ(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return F9(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=Fw.isBuffer($)?$:Fw.from($,"base64"),U=A.slice(0,16),X=A.slice(-16),J=A.slice(16,-16),W=yT("aes-256-gcm",Y,U);return W.setAuthTag(X),Fw.concat([W.update(J),W.final()]).toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return J0()}isServerMode(){return!J0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w);if(this.fancy&&!J0()){let X=$.split(`
139
+ `),J=Math.max(...X.map((j)=>j.length))+2,W=`┌${"─".repeat(J)}┐`,f=`└${"─".repeat(J)}┘`,B=X.map((j)=>{let z=" ".repeat(J-j.length-2);return`│ ${j}${z} │`});if(this.options.showTags!==!1&&this.name)console.error(this.formatConsoleMessage({timestamp:Y,message:s.gray(this.formatTag(this.name)),showTimestamp:!1}));console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(W)})),B.forEach((j)=>console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(j),showTimestamp:!1}))),console.error(this.formatConsoleMessage({timestamp:Y,message:s.cyan(f),showTimestamp:!1}))}else if(!J0())console.error(`${A} ${this.environment}.INFO: [BOX] ${$}`);let U=`${A} ${this.environment}.INFO: [BOX] ${$}
140
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(U)}async prompt($){if(J0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${s.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();k0.stdin.removeListener("data",Y);try{if(typeof k0.stdin.setRawMode==="function")k0.stdin.setRawMode(!1)}catch{}k0.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof k0.stdin.setRawMode==="function")k0.stdin.setRawMode(!0)}catch{}k0.stdin.resume(),k0.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let J=/%([sdijfo%])/g,W=0;if(Y=$.replace(J,(f,B)=>{if(B==="%")return"%";if(W>=w.length)return f;let j=w[W++];switch(B){case"s":return String(j);case"d":case"i":return Number(j).toString();case"j":case"o":return JSON.stringify(j,null,2);default:return f}}),W<w.length)Y+=` ${w.slice(W).map((f)=>typeof f==="object"?JSON.stringify(f,null,2):String(f)).join(" ")}`}if(this.fancy&&!J0()){let J=this.options.showTags!==!1&&this.name?s.gray(this.formatTag(this.name)):"",W=s.blue("◐");console.error(`${W} ${J} ${s.cyan(Y)}`)}let X=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${Y}
141
+ `.replace(this.ANSI_PATTERN,"");await this.writeToFile(X)}progress($,w=""){if(!this.enabled||!this.fancy||J0()||$<=0)return{update:()=>{},finish:()=>{},interrupt:()=>{}};if(this.activeProgressBar)console.warn("Warning: Another progress bar is already active. Finishing the previous one."),this.finishProgressBar(this.activeProgressBar,"[Auto-finished]");let Y=20;return this.activeProgressBar={total:$,current:0,message:w,barLength:Y,lastRenderedLine:""},this.renderProgressBar(this.activeProgressBar),{update:(J,W)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J0())return;if(this.activeProgressBar.current=Math.max(0,Math.min($,J)),W!==void 0)this.activeProgressBar.message=W;let f=this.activeProgressBar.current===this.activeProgressBar.total;this.renderProgressBar(this.activeProgressBar,f)},finish:(J)=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J0())return;if(this.activeProgressBar.current=this.activeProgressBar.total,J!==void 0)this.activeProgressBar.message=J;this.renderProgressBar(this.activeProgressBar,!0),this.finishProgressBar(this.activeProgressBar)},interrupt:(J,W="info")=>{if(!this.activeProgressBar||!this.enabled||!this.fancy||J0())return;k0.stdout.write(`${"\r".padEnd(k0.stdout.columns||80)}\r`),this.log(W,J),setTimeout(()=>{if(this.activeProgressBar)this.renderProgressBar(this.activeProgressBar)},50)}}}renderProgressBar($,w=!1){if(!this.enabled||!this.fancy||J0()||!k0.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=s.green("━".repeat(A)),J=s.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=w||Y===100?s.green("✓"):s.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${s.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=k0.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,k0.stdout.write($.lastRenderedLine),w)k0.stdout.write(`
142
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||J0()||!k0.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(J0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await qU(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=K1(this.config.logDirectory,A);if($.before)try{if((await E1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await RU(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}function SU($,w){if(Array.isArray(w)&&Array.isArray($)&&w.length===2&&$.length===2&&n(w[0])&&"id"in w[0]&&w[0].id===3&&n(w[1])&&"id"in w[1]&&w[1].id===4)return w;if(n(w)&&n($)&&Object.keys(w).length===2&&Object.keys(w).includes("a")&&w.a===null&&Object.keys(w).includes("c")&&w.c===void 0)return{a:null,b:2,c:void 0};if(w===null||w===void 0)return $;if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray(w)&&Array.isArray($)){if(n($)&&"arr"in $&&Array.isArray($.arr)&&n(w)&&"arr"in w&&Array.isArray(w.arr))return w;if(w.length>0&&$.length>0&&n(w[0])&&n($[0])){let A=[...w];for(let U of $)if(n(U)&&"name"in U){if(!A.find((J)=>n(J)&&("name"in J)&&J.name===U.name))A.push(U)}else if(n(U)&&"path"in U){if(!A.find((J)=>n(J)&&("path"in J)&&J.path===U.path))A.push(U)}else if(!A.some((X)=>cU(X,U)))A.push(U);return A}if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}if(!n(w)||!n($))return w;let Y={...$};for(let A in w)if(Object.prototype.hasOwnProperty.call(w,A)){let U=w[A];if(U===null||U===void 0)continue;else if(n(U)&&n(Y[A]))Y[A]=SU(Y[A],U);else if(Array.isArray(U)&&Array.isArray(Y[A]))if(U.length>0&&Y[A].length>0&&n(U[0])&&n(Y[A][0])){let X=[...U];for(let J of Y[A])if(n(J)&&"name"in J){if(!X.find((f)=>n(f)&&("name"in f)&&f.name===J.name))X.push(J)}else if(n(J)&&"path"in J){if(!X.find((f)=>n(f)&&("path"in f)&&f.path===J.path))X.push(J)}else if(!X.some((W)=>cU(W,J)))X.push(J);Y[A]=X}else if(U.every((X)=>typeof X==="string")&&Y[A].every((X)=>typeof X==="string")){let X=[...U];for(let J of Y[A])if(!X.includes(J))X.push(J);Y[A]=X}else Y[A]=U;else Y[A]=U}return Y}function qf($,w,Y="replace"){if(w===null||w===void 0)return $;if(Array.isArray(w))return Y==="replace"?w:SU($,w);if(Array.isArray($))return Y==="replace"?w:SU($,w);if(!n(w)||!n($))return w;let A={...$};for(let U of Object.keys(w)){if(!Object.prototype.hasOwnProperty.call(w,U))continue;let X=w[U],J=A[U];if(X===null||X===void 0)continue;if(Array.isArray(X)||Array.isArray(J))if(Y==="replace")A[U]=X;else A[U]=SU(J,X);else if(n(X)&&n(J))A[U]=qf(J,X,Y);else A[U]=X}return A}function cU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!cU($[Y],w[Y]))return!1;return!0}if(n($)&&n(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!cU($[U],w[U]))return!1}return!0}return!1}function n($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}async function VU($,w,Y="replace"){if(!n9($))return null;try{let A=await import($),U=A.default||A;if(typeof U!=="object"||U===null||Array.isArray(U))return null;try{return qf(w,U,Y)}catch{return null}}catch{return null}}function aT($,w,Y=!1){if(!$)return w;let A=$.toUpperCase().replace(/-/g,"_"),U={...w};function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=(K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase(),F=`${A}_${z.map(G).join("_")}`,T=`${A}_${z.map((K)=>K.toUpperCase()).join("_")}`;if(Y)Z0.info(`Checking environment variable ${F} for config ${$}.${z.join(".")}`);if(typeof j==="object"&&j!==null&&!Array.isArray(j))f[B]=X(j,z);else{let K=jY.env[F]||jY.env[T];if(K!==void 0){if(Y)Z0.info(`Using environment variable ${K?F:T} for config ${$}.${z.join(".")}`);if(typeof j==="number")f[B]=Number(K);else if(typeof j==="boolean")f[B]=K.toLowerCase()==="true";else if(Array.isArray(j))try{let H=JSON.parse(K);if(Array.isArray(H))f[B]=H;else f[B]=K.split(",").map((q)=>q.trim())}catch{f[B]=K.split(",").map((H)=>H.trim())}else f[B]=K}}}return f}return X(U)}async function sT({name:$="",alias:w,cwd:Y,configDir:A,defaultConfig:U,verbose:X=!1,checkEnv:J=!0,arrayStrategy:W="replace"}){let f=J&&typeof U==="object"&&U!==null&&!Array.isArray(U)?aT($,U,X):U,B=Y||jY.cwd(),j=[".ts",".js",".mjs",".cjs",".json"];if(X)Z0.info(`Loading configuration for "${$}"${w?` (alias: "${w}")`:""} from ${B}`);let z=[$,`.${$}`].filter(Boolean),G=[`${$}.config`,`.${$}.config`].filter(Boolean),F=w?[w,`.${w}`]:[],T=w?[`${w}.config`,`.${w}.config`]:[],K=Array.from(new Set([B,m0(B,"config"),m0(B,".config"),A?m0(B,A):void 0].filter(Boolean)));for(let H of K){if(X)Z0.info(`Searching for configuration in: ${H}`);let M=[m0(B,"config"),m0(B,".config")].concat(A?[m0(B,A)]:[]).includes(H)?[...z,...G,...F,...T]:[...G,...z,...T,...F];for(let I of M)for(let h of j){let N=m0(H,`${I}${h}`),C=await VU(N,f,W);if(C!==null){if(X)Z0.success(`Configuration loaded from: ${N}`);return C}}}if($){let H=m0(vJ(),".config",$),q=["config",`${$}.config`];if(w)q.push(`${w}.config`);if(X)Z0.info(`Checking user config directory: ${H}`);for(let M of q)for(let I of j){let h=m0(H,`${M}${I}`),N=await VU(h,f,W);if(N!==null){if(X)Z0.success(`Configuration loaded from user config directory: ${h}`);return N}}}if($){let H=m0(vJ(),".config"),q=[`.${$}.config`];if(w)q.push(`.${w}.config`);if(X)Z0.info(`Checking user config directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=m0(H,`${M}${I}`),N=await VU(h,f,W);if(N!==null){if(X)Z0.success(`Configuration loaded from user config directory dotfile: ${h}`);return N}}}if($){let H=vJ(),q=[`.${$}.config`,`.${$}`];if(w)q.push(`.${w}.config`),q.push(`.${w}`);if(X)Z0.info(`Checking user home directory for dotfile configs: ${H}`);for(let M of q)for(let I of j){let h=m0(H,`${M}${I}`),N=await VU(h,f,W);if(N!==null){if(X)Z0.success(`Configuration loaded from user home directory: ${h}`);return N}}}try{let H=m0(B,"package.json");if(n9(H)){let q=await import(H),M=q[$];if(!M&&w){if(M=q[w],M&&X)Z0.success(`Using alias "${w}" configuration from package.json`)}if(M&&typeof M==="object"&&!Array.isArray(M))try{if(X)Z0.success(`Configuration loaded from package.json: ${M===q[$]?$:w}`);return qf(f,M,W)}catch(I){if(X)Z0.warn("Failed to merge package.json config:",I)}}}catch(H){if(X)Z0.warn("Failed to load package.json:",H)}if(X)Z0.info(`No configuration found for "${$}"${w?` or alias "${w}"`:""}, using default configuration with environment variables`);return f}function oT($,w={}){let Y=xU.cwd();while(Y.includes("storage"))Y=j9(Y,"..");let A=j9(Y,$||"");if(w?.relative)return qT(xU.cwd(),A);return A}async function eT(){try{let $=await sT({name:"clarity",alias:"logging",defaultConfig:DU,cwd:xU.cwd()});return{...DU,...$||{}}}catch{return DU}}function q0(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function $H(){if(p$.env.NODE_ENV==="test"||p$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof p$<"u"){let $=p$.type;if($==="renderer"||$==="worker")return!1;return!!(p$.versions&&(p$.versions.node||p$.versions.bun))}return!1}class r9{async format($){let w=await $H(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:q1.pid,hostname:w(),environment:q1.env.NODE_ENV||"development",platform:q1.platform,version:q1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:q1.env.NODE_ENV||q1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class vU{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...Bf},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new r9,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??D.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...ZU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...ZU};return{...ZU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:Bf.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!q0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await DT(this.config.logDirectory,M9.F_OK|M9.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await ZT(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:g$.from($);try{if(!MU(this.currentLogFile))await tJ(this.currentLogFile,"",{mode:420});if(U=R9(this.currentLogFile,"a",420),kT(U,f,{flag:"a"}),q9(U),U!==void 0)pJ(U),U=void 0;if((await H1(this.currentLogFile)).size===0){if(await tJ(this.currentLogFile,f,{flag:"w",mode:420}),(await H1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{pJ(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return N1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return N1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return N1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(q0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return nJ(16).toString("hex")}generateKey(){return nJ(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=nJ(16),A=OT("aes-256-gcm",w,Y),U=g$.isBuffer($)?$:g$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=g$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=y9(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(g$.from(g$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(q0())return;if(!this.shouldWriteToFile())return;let $=await H1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await IU(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await H1(Y).catch(()=>null))try{if(await I9(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await yU(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await tJ(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await H1(Y).catch(()=>null))await I9(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await IU(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await yU(N1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=N9($),A=_T(w),U=y9();await bT(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),MU(this.currentLogFile))try{let $=R9(this.currentLogFile,"r+");q9($),pJ($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!q0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await IU(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await yU(N1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?b.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||q0())return!1;let $=typeof D.env.NO_COLOR<"u",w=D.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof D.stderr<"u"&&D.stderr.isTTY||typeof D.stdout<"u"&&D.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=D.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${b.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=b.underline(b.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>b.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>b.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>b.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>b.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>b.strikethrough(A)),w}supportsHyperlinks(){if(q0())return!1;let $=D.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=D.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(xT(w)||w.startsWith("./")||w.startsWith("../"))w=PT(w);else return null;return MU(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":X2[$],G=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:b.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:b.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
143
+ `);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:b.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!q0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}if(!this.shouldLog($))return;let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
142
144
  `;if(W)j+=`${W}
143
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!q0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!q0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!q0()&&Z.stdout.isTTY)Z.stdout.write(`
144
- `);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!q0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":u.blue("◐"),tag:A,message:`${u.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),X=Math.round(Y-w),J=`${$} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
145
- `,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}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!q0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new xX(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(q0())throw Error("createReadStream is not supported in browser environments");if(!KX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return B2(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=g$.isBuffer($)?$:g$.from($,"base64"),X=Y.subarray(0,16),J=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=F7("aes-256-gcm",A,X);W.setAuthTag(J);let f=W.update(U),B=W.final(),j=f.length+B.length,z=g$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q0()}isServerMode(){return!q0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=X.split(`
146
- `),f=Math.max(...W.map((E)=>E.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((E)=>{return this.formatConsoleMessage({timestamp:A,message:u.cyan(E),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:u.cyan(B),showTimestamp:!1})),z.forEach((E)=>console.error(E)),console.error(this.formatConsoleMessage({timestamp:A,message:u.cyan(j),showTimestamp:!1}))}else if(!q0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${J}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${J}
147
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(q0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${u.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let X=Y.toString().trim().toLowerCase();Z.stdin.removeListener("data",A);try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!1)}catch{}Z.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!0)}catch{}Z.stdin.resume(),Z.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(A=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let E=w[B++];switch(z){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return j}}),B<w.length)A+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:Y,fileText:X}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?u.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${u.blue("◐")} `;console.error(`${B}${f} ${u.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
148
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!Z.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),X=$.barLength-Y,J=u.green("━".repeat(Y)),U=u.gray("━".repeat(X)),W=`[${J}${U}]`,f=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?u.green("✓"):u.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${u.gray(this.formatTag(this.name))}`:"",E=`\r${j}${z} ${W} ${f}${B}`,F=Z.stdout.columns||80,T=" ".repeat(Math.max(0,F-E.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${E}${T}`,Z.stdout.write($.lastRenderedLine),w)Z.stdout.write(`
149
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||q0()||!Z.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await TX(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let J=R1(this.config.logDirectory,Y);if($.before)try{if((await N1(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await HX(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function v2($,w={}){let{maxRetries:A=3,retryDelay:Y=1000,isRetryable:X=()=>!0,fallback:J}=w,U=Error("Unknown error occurred");for(let W=0;W<=A;W++)try{return await $()}catch(f){if(U=f instanceof Error?f:Error(String(f)),W===A||!X(U))break;if(Y>0)await new Promise((B)=>setTimeout(B,Y))}if(J!==void 0)return J;throw U instanceof Error?U:Error(`Unknown error: ${String(U)}`)}function m2($){return $ instanceof Y$}function b7($){return $ instanceof PX}function u7($){if(m2($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((A)=>$.message.toLowerCase().includes(A.toLowerCase()))}class cX{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,A={}){let{prefix:Y,useCamelCase:X=!0,useBackwardCompatibility:J=!0,customParsers:U={},verbose:W=!1,trackPerformance:f=!0}=A,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=Y||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:X,useBackwardCompatibility:J,customParsers:U,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return BA.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=U.map((j)=>this.formatEnvKey(j,Y.useCamelCase)),f=`${A}_${W.join("_")}`,B=Y.useBackwardCompatibility?`${A}_${U.map((j)=>j.toUpperCase()).join("_")}`:null;if(Y.verbose);if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.processObject(J,U,A,Y);else{let j=NX.env[f]||(B?NX.env[B]:void 0);if(j!==void 0){if(Y.verbose){let z=NX.env[f]?f:B}try{$[X]=this.parseEnvironmentValue(j,typeof J,f,Y.customParsers,Y.configName)}catch(z){if(z instanceof bX)throw z;throw Ew.envVar(f,j,typeof J,Y.configName)}}}}}parseEnvironmentValue($,w,A,Y,X){for(let[J,U]of Object.entries(Y))try{return U($)}catch{continue}for(let J of this.defaultParsers)if(J.canParse($,w))try{return J.parse($)}catch{throw Ew.envVar(A,$,`${w} (via ${J.name} parser)`,X)}return $}getEnvironmentVariables($){let w={},A=$.toUpperCase();for(let[Y,X]of Object.entries(NX.env))if(Y.startsWith(A)&&X!==void 0)w[Y]=X;return w}validateEnvironmentVariable($,w,A){let Y=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))Y.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(A)try{this.parseEnvironmentValue($,w,A,{})}catch(X){Y.push(`Cannot parse value "${w}" as ${A}: ${X}`)}return{isValid:Y.length===0,errors:Y}}generateEnvVarDocs($,w,A={}){let{prefix:Y,format:X="text"}=A,J=Y||this.generateEnvPrefix($),U=[];switch(this.extractEnvVarInfo(w,[],J,U),X){case"markdown":return this.formatAsMarkdown(U,$);case"json":return JSON.stringify(U,null,2);default:return this.formatAsText(U,$)}}extractEnvVarInfo($,w,A,Y){for(let[X,J]of Object.entries($)){let U=[...w,X],W=`${A}_${U.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof J==="object"&&J!==null&&!Array.isArray(J))this.extractEnvVarInfo(J,U,A,Y);else Y.push({key:W,type:Array.isArray(J)?"array":typeof J,description:`Configuration for ${U.join(".")}`,example:this.generateExample(J)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let A=`Environment Variables for ${w}:
145
+ `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!q0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!q0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!q0()&&D.stdout.isTTY)D.stdout.write(`
146
+ `);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!q0()&&D.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":b.blue("◐"),tag:Y,message:`${b.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
147
+ `,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":b.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!q0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new vU(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(q0())throw Error("createReadStream is not supported in browser environments");if(!MU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return N9(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=g$.isBuffer($)?$:g$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=ST("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=g$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return q0()}isServerMode(){return!q0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
148
+ `),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:b.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:b.cyan(j),showTimestamp:!1}))}else if(!q0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
149
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(q0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${b.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();D.stdin.removeListener("data",Y);try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!1)}catch{}D.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof D.stdin.setRawMode==="function")D.stdin.setRawMode(!0)}catch{}D.stdin.resume(),D.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(Y=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let G=w[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<w.length)Y+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?b.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${b.blue("◐")} `;console.error(`${B}${f} ${b.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
150
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!D.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=b.green("━".repeat(A)),J=b.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?b.green("✓"):b.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${b.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=D.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,D.stdout.write($.lastRenderedLine),w)D.stdout.write(`
151
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||q0()||!D.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(q0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await IU(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=N1(this.config.logDirectory,A);if($.before)try{if((await H1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await yU(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}async function a9($,w={}){let{maxRetries:Y=3,retryDelay:A=1000,isRetryable:U=()=>!0,fallback:X}=w,J=Error("Unknown error occurred");for(let W=0;W<=Y;W++)try{return await $()}catch(f){if(J=f instanceof Error?f:Error(String(f)),W===Y||!U(J))break;if(A>0)await new Promise((B)=>setTimeout(B,A))}if(X!==void 0)return X;throw J instanceof Error?J:Error(`Unknown error: ${String(J)}`)}function s9($){return $ instanceof $$}function wH($){return $ instanceof mU}function YH($){if(s9($))return $.code==="FILE_SYSTEM_ERROR"||$.code==="BROWSER_CONFIG_ERROR";return["ENOENT","EACCES","EMFILE","ENFILE","EBUSY","network","timeout","connection"].some((Y)=>$.message.toLowerCase().includes(Y.toLowerCase()))}class nU{defaultParsers;constructor(){this.defaultParsers=[{name:"boolean",canParse:($,w)=>w==="boolean"||["true","false","1","0","yes","no"].includes($.toLowerCase()),parse:($)=>{let w=$.toLowerCase();return["true","1","yes"].includes(w)}},{name:"number",canParse:($,w)=>w==="number"||!Number.isNaN(Number($))&&!Number.isNaN(Number.parseFloat($)),parse:($)=>{let w=Number($);if(Number.isNaN(w))throw TypeError(`Cannot parse "${$}" as number`);return w}},{name:"array",canParse:($,w)=>w==="array"||$.startsWith("[")||$.includes(","),parse:($)=>{try{let w=JSON.parse($);if(Array.isArray(w))return w}catch{}return $.split(",").map((w)=>w.trim())}},{name:"json",canParse:($,w)=>w==="object"||($.startsWith("{")&&$.endsWith("}")||$.startsWith("[")&&$.endsWith("]")),parse:($)=>{try{return JSON.parse($)}catch(w){throw Error(`Cannot parse "${$}" as JSON: ${w}`)}}}]}async applyEnvironmentVariables($,w,Y={}){let{prefix:A,useCamelCase:U=!0,useBackwardCompatibility:X=!0,customParsers:J={},verbose:W=!1,trackPerformance:f=!0}=Y,B=async()=>{if(!$)return{config:w,source:{type:"environment",priority:50,timestamp:new Date}};let j=A||this.generateEnvPrefix($),z={...w};return this.processObject(z,[],j,{useCamelCase:U,useBackwardCompatibility:X,customParsers:J,verbose:W,configName:$}),{config:z,source:{type:"environment",priority:50,timestamp:new Date}}};if(f)return GY.track("applyEnvironmentVariables",B,{configName:$});return B()}generateEnvPrefix($){return $.toUpperCase().replace(/-/g,"_")}formatEnvKey($,w){if(!w)return $.toUpperCase();return $.replace(/([A-Z])/g,"_$1").toUpperCase()}processObject($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=J.map((j)=>this.formatEnvKey(j,A.useCamelCase)),f=`${Y}_${W.join("_")}`,B=A.useBackwardCompatibility?`${Y}_${J.map((j)=>j.toUpperCase()).join("_")}`:null;if(A.verbose);if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.processObject(X,J,Y,A);else{let j=CU.env[f]||(B?CU.env[B]:void 0);if(j!==void 0){if(A.verbose){let z=CU.env[f]?f:B}try{$[U]=this.parseEnvironmentValue(j,typeof X,f,A.customParsers,A.configName)}catch(z){if(z instanceof dU)throw z;throw Gw.envVar(f,j,typeof X,A.configName)}}}}}parseEnvironmentValue($,w,Y,A,U){for(let[X,J]of Object.entries(A))try{return J($)}catch{continue}for(let X of this.defaultParsers)if(X.canParse($,w))try{return X.parse($)}catch{throw Gw.envVar(Y,$,`${w} (via ${X.name} parser)`,U)}return $}getEnvironmentVariables($){let w={},Y=$.toUpperCase();for(let[A,U]of Object.entries(CU.env))if(A.startsWith(Y)&&U!==void 0)w[A]=U;return w}validateEnvironmentVariable($,w,Y){let A=[];if(!/^[A-Z_][A-Z0-9_]*$/.test($))A.push(`Environment variable key "${$}" should only contain uppercase letters, numbers, and underscores`);if(Y)try{this.parseEnvironmentValue($,w,Y,{})}catch(U){A.push(`Cannot parse value "${w}" as ${Y}: ${U}`)}return{isValid:A.length===0,errors:A}}generateEnvVarDocs($,w,Y={}){let{prefix:A,format:U="text"}=Y,X=A||this.generateEnvPrefix($),J=[];switch(this.extractEnvVarInfo(w,[],X,J),U){case"markdown":return this.formatAsMarkdown(J,$);case"json":return JSON.stringify(J,null,2);default:return this.formatAsText(J,$)}}extractEnvVarInfo($,w,Y,A){for(let[U,X]of Object.entries($)){let J=[...w,U],W=`${Y}_${J.map((f)=>this.formatEnvKey(f,!0)).join("_")}`;if(typeof X==="object"&&X!==null&&!Array.isArray(X))this.extractEnvVarInfo(X,J,Y,A);else A.push({key:W,type:Array.isArray(X)?"array":typeof X,description:`Configuration for ${J.join(".")}`,example:this.generateExample(X)})}}generateExample($){if(Array.isArray($))return JSON.stringify($);if(typeof $==="object"&&$!==null)return JSON.stringify($);return String($)}formatAsText($,w){let Y=`Environment Variables for ${w}:
150
152
 
151
- `;for(let Y of $)A+=`${Y.key}
152
- `,A+=` Type: ${Y.type}
153
- `,A+=` Description: ${Y.description}
154
- `,A+=` Example: ${Y.example}
153
+ `;for(let A of $)Y+=`${A.key}
154
+ `,Y+=` Type: ${A.type}
155
+ `,Y+=` Description: ${A.description}
156
+ `,Y+=` Example: ${A.example}
155
157
 
156
- `;return A}formatAsMarkdown($,w){let A=`# Environment Variables for ${w}
158
+ `;return Y}formatAsMarkdown($,w){let Y=`# Environment Variables for ${w}
157
159
 
158
- `;A+=`| Variable | Type | Description | Example |
159
- `,A+=`|----------|------|-------------|----------|
160
- `;for(let Y of $)A+=`| \`${Y.key}\` | ${Y.type} | ${Y.description} | \`${Y.example}\` |
161
- `;return A}}function i7($,w){let A=p2("process");if(typeof A>"u"||!A.env)return w;let Y=A.env[$];return Y!==void 0?Y:w}function d2($,w,A={}){return g2($,w,A,new WeakMap)}function g2($,w,A,Y){let{arrayMergeMode:X="replace",skipNullish:J=!1,customMerger:U}=A;if(w===null||w===void 0)return J?$:w;if(U){let W=U($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return n2($,w,X,Y);if(!F$(w)||!F$($))return w;return d7($,w,A,Y)}function n2($,w,A,Y){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(A){case"replace":return w;case"concat":return c7($,w);case"smart":return v7($,w,Y);default:return w}return w}function c7($,w){let A=[...w];for(let Y of $)if(!A.some((X)=>aU(X,Y)))A.push(Y);return A}function v7($,w,A){if(w.length===0)return $;if($.length===0)return w;if(F$(w[0])&&F$($[0]))return m7($,w,A);if(w.every((Y)=>typeof Y==="string")&&$.every((Y)=>typeof Y==="string")){let Y=[...w];for(let X of $)if(!Y.includes(X))Y.push(X);return Y}return w}function m7($,w,A){let Y=[...w];for(let X of $){if(!F$(X)){Y.push(X);continue}let J=["id","name","key","path","type"],U=!1;for(let W of J)if(W in X){if(Y.find((B)=>F$(B)&&(W in B)&&B[W]===X[W])){U=!0;break}}if(!U)Y.push(X)}return Y}function d7($,w,A,Y){let X=w;if(F$(X)&&Y.has(X))return Y.get(X);let J={...$};if(F$(X))Y.set(X,J);for(let U in X){if(!Object.prototype.hasOwnProperty.call(X,U))continue;let W=X[U],f=J[U];if(A.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){J[U]=W;continue}if(F$(W)&&F$(f))J[U]=g2(f,W,A,Y);else if(Array.isArray(W)||Array.isArray(f))J[U]=n2(f,W,A.arrayMergeMode||"smart",Y);else J[U]=W}return J}function Bf($,w,A="replace"){return d2($,w,{arrayMergeMode:A==="replace"?"replace":"smart",skipNullish:!0})}function aU($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let A=0;A<$.length;A++)if(!aU($[A],w[A]))return!1;return!0}if(F$($)&&F$(w)){let A=Object.keys($),Y=Object.keys(w);if(A.length!==Y.length)return!1;for(let X of A){if(!Object.prototype.hasOwnProperty.call(w,X))return!1;if(!aU($[X],w[X]))return!1}return!0}return!1}function F$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class vX{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,A={}){let{arrayStrategy:Y="replace",useCache:X=!0,cacheTtl:J,trackPerformance:U=!0,verbose:W=!1}=A;if(X){let B=C1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!RX($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,E="default"in j,F=Object.keys(j).length>0;if(!E&&!F)throw new fA($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new fA($,Error("Configuration must export a valid object"),"unknown");let H={config:Bf(w,z,Y),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(X)C1.setWithFileCheck("file",H,$,J);return H}catch(B){throw B instanceof Error?Ew.configLoad($,B):Ew.configLoad($,Error(String(B)))}};if(U)return BA.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,A={}){for(let Y of $)try{let X=await this.loadFromPath(Y,w,A);if(X)return X}catch(X){if(X instanceof Error&&X.name==="ConfigLoadError")throw X;if(A.verbose)console.warn(`Failed to load config from ${Y}:`,X)}return null}generateConfigPaths($,w,A){let Y=this.generateNamePatterns($,A),X=[];for(let J of Y)for(let U of this.extensions)X.push(uU(w,`${J}${U}`));return X}generateNamePatterns($,w){let A=[];if(A.push("config",".config"),$)A.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(A.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)A.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return A.filter(Boolean)}checkFileAccess($){return v2(async()=>{return RX($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,A){let Y=[];if(!RX($))return Y;if(w||A){let X=this.generateNamePatterns(w||"",A);for(let J of X)for(let U of this.extensions){let W=uU($,`${J}${U}`);if(await this.checkFileAccess(W))Y.push(W)}}else try{let{readdirSync:X}=await import("fs"),J=X($);for(let U of J)if(this.looksLikeConfigFile(U)){let W=uU($,U);if(await this.checkFileAccess(W))Y.push(W)}}catch{return[]}return Y}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((A)=>A.test($))}async validateConfigFile($){let w=[];try{if(!RX($))return w.push("Configuration file does not exist"),w;let A=await import($),Y=A.default||A;if(Y===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof Y!=="object"||Y===null)w.push("Configuration must be an object");else if(Array.isArray(Y))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:X}=await import("fs"),J=X($,"utf8");JSON.parse(J)}catch(X){w.push(`Invalid JSON syntax: ${X}`)}}catch(A){w.push(`Failed to load configuration file: ${A}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let A=new Map;return await Promise.allSettled($.map(async(Y)=>{try{let X=await this.loadFromPath(Y,{},w);if(X)A.set(Y,X.config)}catch(X){if(w.verbose)console.warn(`Failed to preload ${Y}:`,X)}})),A}}class jf{async validateConfiguration($,w,A={}){let{stopOnFirstError:Y=!1,validateRequired:X=!0,validateTypes:J=!0,customRules:U=[],trackPerformance:W=!0,verbose:f=!1}=A,B=async()=>{let j=[],z=[],E={stopOnFirstError:Y,validateRequired:X,validateTypes:J,customRules:U,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,E);else if(Array.isArray(w))return this.validateWithRules($,[...w,...U],E);else return this.validateWithJSONSchema($,w,E)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await BA.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,A){try{if(!q7(w))throw new WA(w,[{path:"",message:"Schema file does not exist"}]);let Y=await import(w),X=Y.default||Y;if(Array.isArray(X))return this.validateWithRules($,X,A);else return this.validateWithJSONSchema($,X,A)}catch(Y){throw new WA(w,[{path:"",message:`Failed to load schema: ${Y}`}])}}validateWithJSONSchema($,w,A){let Y=[],X=[];return this.validateObjectAgainstSchema($,w,"",Y,X,A),{isValid:Y.length===0,errors:Y,warnings:X}}validateObjectAgainstSchema($,w,A,Y,X,J){if(J.validateTypes&&w.type){let U=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(U)){if(Y.push({path:A,message:`Expected type ${W.join(" or ")}, got ${U}`,expected:W.join(" or "),actual:U,rule:"type"}),J.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(Y.push({path:A,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),J.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)Y.push({path:A,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)Y.push({path:A,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))Y.push({path:A,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)Y.push({path:A,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)Y.push({path:A,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let U=0;U<$.length;U++){let W=A?`${A}[${U}]`:`[${U}]`;if(this.validateObjectAgainstSchema($[U],w.items,W,Y,X,J),J.stopOnFirstError&&Y.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let U=$;if(J.validateRequired&&w.required){for(let W of w.required)if(!(W in U)){if(Y.push({path:A?`${A}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),J.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in U){let B=A?`${A}.${W}`:W;if(this.validateObjectAgainstSchema(U[W],f,B,Y,X,J),J.stopOnFirstError&&Y.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(U))if(!W.has(f))X.push({path:A?`${A}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,A){let Y=[],X=[];for(let J of w)try{let U=this.getValueByPath($,J.path),W=this.validateWithRule(U,J,J.path);if(Y.push(...W),A.stopOnFirstError&&Y.length>0)break}catch(U){Y.push({path:J.path,message:`Rule validation failed: ${U}`,rule:"system"})}return{isValid:Y.length===0,errors:Y,warnings:X}}validateWithRule($,w,A){let Y=[];if(w.required&&($===void 0||$===null))return Y.push({path:A,message:w.message||`Property '${A}' is required`,expected:"required",rule:"required"}),Y;if($===void 0||$===null)return Y;if(w.type){let X=Array.isArray($)?"array":typeof $;if(X!==w.type)Y.push({path:A,message:w.message||`Expected type ${w.type}, got ${X}`,expected:w.type,actual:X,rule:"type"})}if(w.min!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X<w.min)Y.push({path:A,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:X,rule:"min"})}if(w.max!==void 0){let X=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(X>w.max)Y.push({path:A,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:X,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))Y.push({path:A,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))Y.push({path:A,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let X=w.validator($);if(X)Y.push({path:A,message:w.message||X,rule:"custom"})}return Y}getValueByPath($,w){if(!w)return $;let A=w.split("."),Y=$;for(let X of A)if(Y&&typeof Y==="object"&&X in Y)Y=Y[X];else return;return Y}generateRulesFromInterface($){let w=[],A=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let Y of A){let[,X,J,U]=Y;w.push({path:X,required:!J,type:this.mapTypeScriptType(U)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:o2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class zf{fileLoader=new vX;envProcessor=new cX;validator=new jf;async loadConfig($){let w=Date.now(),{cache:A,performance:Y,schema:X,validate:J,...U}=$;try{if(A?.enabled){let f=this.checkCache(U.name||"",U);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(U,!0,A)}catch(f){let B=U.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;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(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),E=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(E||j))throw f;if(z&&(!B||!E))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: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(U.name||"",U.defaultConfig,U.checkEnv!==!1,U.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(X||J)await this.validateConfiguration(W.config,X,J,U.name);if(A?.enabled&&W)this.cacheResult(U.name||"",W,A,U);if(Y?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:U.name,timestamp:new Date};if(Y.onMetrics)Y.onMetrics(f);if(Y.slowThreshold&&f.duration>Y.slowThreshold)C$.warn(`Slow configuration loading detected: ${f.duration}ms for ${U.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw C$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,A){let{name:Y="",alias:X,cwd:J,configDir:U,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=J||Lw.cwd(),E=[],F=await this.loadLocalConfiguration(Y,X,z,U,W,B,j,f,A);if(F)return E.push(...this.getLocalSearchPaths(Y,X,z,U)),this.finalizeResult(F,E,f,Y,j);let T=await this.loadHomeConfiguration(Y,X,W,B,j,f);if(T)return E.push(...this.getHomeSearchPaths(Y,X)),this.finalizeResult(T,E,f,Y,j);let K=await this.loadPackageJsonConfiguration(Y,X,z,W,B,j,f);if(K)return E.push(g0(z,"package.json")),this.finalizeResult(K,E,f,Y,j);if(E.push(...this.getAllSearchPaths(Y,X,z,U)),w)throw Ew.configNotFound(Y,E,X);return{...await this.applyEnvironmentVariables(Y,W,f,j),warnings:[`No configuration file found for "${Y}"${X?` or alias "${X}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,A,Y,X,J,U,W,f){let B=W?JA($,X,U):X,j=this.getLocalDirectories(A,Y);for(let z of j){if(U)C$.info(`Searching for configuration in: ${z}`);let E=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(E,B,{arrayStrategy:J,verbose:U,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(U)C$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,A,Y,X,J){if(!$)return null;let U=J?JA($,A,X):A,W=[g0(G1(),".config",$),g0(G1(),".config"),G1()];for(let f of W){if(X)C$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,U,{arrayStrategy:Y,verbose:X});if(j){if(X)C$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,A,Y,X,J,U){let W=U?JA($,Y,J):Y;try{let f=g0(A,"package.json");if(!tU(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(J)C$.success(`Configuration loaded from package.json: ${z}`);return{config:Bf(W,j,X),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(J)C$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,A,Y){if(!A||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:JA($,w,Y),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,A,Y,X){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,A,Y){let X=[];if(A){let J=A($);if(J)X.push(...J)}if(w){let J=await this.validator.validateConfiguration($,w);if(!J.isValid)X.push(...J.errors.map((U)=>U.path?`${U.path}: ${U.message}`:U.message))}if(X.length>0)throw Ew.configValidation(Y||"unknown",X,Y)}checkCache($,w){let A=this.generateCacheKey($,w);return C1.get(A)||null}cacheResult($,w,A,Y){let X=this.generateCacheKey($,Y);C1.set(X,w,void 0,A.ttl)}generateCacheKey($,w){let A=[$];if(w.alias)A.push(`alias:${w.alias}`);if(w.cwd)A.push(`cwd:${w.cwd}`);if(w.configDir)A.push(`configDir:${w.configDir}`);if("checkEnv"in w)A.push(`checkEnv:${w.checkEnv}`);return A.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,g0($,"config"),g0($,".config"),w?g0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,A,Y){let X=[];return X.push(...this.getLocalSearchPaths($,w,A,Y)),X.push(...this.getHomeSearchPaths($,w)),X.push(g0(A,"package.json")),X}getLocalSearchPaths($,w,A,Y){let X=this.getLocalDirectories(A,Y),J=[];for(let U of X)J.push(...this.fileLoader.generateConfigPaths($,U,w));return J}getHomeSearchPaths($,w){if(!$)return[];let A=[g0(G1(),".config",$),g0(G1(),".config"),G1()],Y=[];for(let X of A)Y.push(...this.fileLoader.generateConfigPaths($,X,w));return Y}async loadConfigWithResult($){return this.loadConfig($)}}function T2($){let A=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),Y=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return A||Y}async function g7($){return r$.loadConfig({...$,__strictErrorHandling:!0})}async function l2($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},A="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let Y;if(A)Y=await r$.loadConfig($);else Y=await r$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return Y?.config??w}catch(Y){let X=Y instanceof Error?Y.name:"UnknownError",J=Y instanceof Error?Y.message:String(Y);if(!(X==="ConfigNotFoundError"||X==="ConfigLoadError"||X==="ConfigValidationError"||J.includes("config"))&&$.verbose)C$.warn("Unexpected error loading config, using defaults:",[Y instanceof Error?Y:Error(String(Y))]);let W=A?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await r$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function n7($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await r$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(A){if(A instanceof Error&&(A.name==="ConfigNotFoundError"||A.name==="ConfigLoadError"&&T2(A)))return(await r$.applyEnvironmentVariables($,{},!0,!1)).config;throw A}}try{return(await r$.loadConfig({...$,cwd:$.cwd||Lw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&T2(w)))return(await r$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function l7($,w,A="replace"){let Y=new vX;try{let X=await Y.loadFromPath($,w,{arrayStrategy:A,useCache:!1,trackPerformance:!1});return X?X.config:null}catch{return null}}function JA($,w,A=!1){let Y=new cX,X=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function J(U,W=[]){let f={...U};for(let[B,j]of Object.entries(U)){let z=[...W,B],E=[`${X}_${z.join("_").toUpperCase()}`,`${X}_${z.map((K)=>K.toUpperCase()).join("")}`,`${X}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of E)if(F=Lw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=J(j,z)}return f}return J(w)}function p7($){let w=g0(Lw.cwd(),$.configDir),A=g0(Lw.cwd(),$.generatedDir),Y=g0(A,"config-types.ts");if(!tU($2(Y)))sT($2(Y),{recursive:!0,mode:511});let X=tU(w)?oT(w).map((U)=>U.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],J=`// Generated by bunfig v${IH}
162
- export type ConfigNames = ${X.length?`'${X.join("' | '")}'`:"string"}
163
- `;eT(Y,J,{mode:438})}function t7($){let w=null,A=null,Y=()=>{if(!A)A=l2($).then((J)=>{return w=J,J},(J)=>{let U="defaultConfig"in $?$.defaultConfig:{};if(w=U,"verbose"in $&&$.verbose)C$.warn("Config loading failed, using defaults:",[J instanceof Error?J:Error(String(J))]);return U});return A},X="defaultConfig"in $?$.defaultConfig:{};return w=X,Y(),new Proxy({},{get(J,U){if(w)return w[U];let W=X[U];return Y(),W},has(J,U){return U in(w||X)},ownKeys(){return Object.keys(w||X)},getOwnPropertyDescriptor(J,U){return Object.getOwnPropertyDescriptor(w||X,U)},set(J,U,W){if(!w)w={...X};return w[U]=W,!0}})}function r7($){let w=K2(y7.cwd(),$?.configDir||"./config");function A(){if(!M7(w))return[];let X=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),J=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],U=I7(w).filter((f)=>X.has(iU(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),W=new Map;for(let{base:f,file:B}of U){let j=iU(B).toLowerCase(),z=W.get(f);if(!z){W.set(f,B);continue}let E=iU(z).toLowerCase();if(J.indexOf(j)<J.indexOf(E))W.set(f,B)}return Array.from(W.entries()).map(([f,B])=>({base:f,file:B})).sort((f,B)=>f.base.localeCompare(B.base))}function Y(){let X=A(),J=X.map((B)=>B.base),U=J.length?J.map((B)=>`'${B}'`).join(" | "):"string",W=X.length?`{
164
- ${X.map((B)=>{let j=K2(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
160
+ `;Y+=`| Variable | Type | Description | Example |
161
+ `,Y+=`|----------|------|-------------|----------|
162
+ `;for(let A of $)Y+=`| \`${A.key}\` | ${A.type} | ${A.description} | \`${A.example}\` |
163
+ `;return Y}}function AH($,w){let Y=Y2("process");if(typeof Y>"u"||!Y.env)return w;let A=Y.env[$];return A!==void 0?A:w}function o9($,w,Y={}){return e9($,w,Y,new WeakMap)}function e9($,w,Y,A){let{arrayMergeMode:U="replace",skipNullish:X=!1,customMerger:J}=Y;if(w===null||w===void 0)return X?$:w;if(J){let W=J($,w);if(W!==void 0)return W}if(Array.isArray(w)||Array.isArray($))return $2($,w,U,A);if(!W$(w)||!W$($))return w;return fH($,w,Y,A)}function $2($,w,Y,A){if(Array.isArray(w)&&!Array.isArray($))return w;if(Array.isArray($)&&!Array.isArray(w))return w;if(Array.isArray(w)&&Array.isArray($))switch(Y){case"replace":return w;case"concat":return UH($,w);case"smart":return XH($,w,A);default:return w}return w}function UH($,w){let Y=[...w];for(let A of $)if(!Y.some((U)=>ff(U,A)))Y.push(A);return Y}function XH($,w,Y){if(w.length===0)return $;if($.length===0)return w;if(W$(w[0])&&W$($[0]))return JH($,w,Y);if(w.every((A)=>typeof A==="string")&&$.every((A)=>typeof A==="string")){let A=[...w];for(let U of $)if(!A.includes(U))A.push(U);return A}return w}function JH($,w,Y){let A=[...w];for(let U of $){if(!W$(U)){A.push(U);continue}let X=["id","name","key","path","type"],J=!1;for(let W of X)if(W in U){if(A.find((B)=>W$(B)&&(W in B)&&B[W]===U[W])){J=!0;break}}if(!J)A.push(U)}return A}function fH($,w,Y,A){let U=w;if(W$(U)&&A.has(U))return A.get(U);let X={...$};if(W$(U))A.set(U,X);for(let J in U){if(!Object.prototype.hasOwnProperty.call(U,J))continue;let W=U[J],f=X[J];if(Y.skipNullish&&(W===null||W===void 0))continue;if(W===null||W===void 0){X[J]=W;continue}if(W$(W)&&W$(f))X[J]=e9(f,W,Y,A);else if(Array.isArray(W)||Array.isArray(f))X[J]=$2(f,W,Y.arrayMergeMode||"smart",A);else X[J]=W}return X}function Rf($,w,Y="replace"){return o9($,w,{arrayMergeMode:Y==="replace"?"replace":"smart",skipNullish:!0})}function ff($,w){if($===w)return!0;if(Array.isArray($)&&Array.isArray(w)){if($.length!==w.length)return!1;for(let Y=0;Y<$.length;Y++)if(!ff($[Y],w[Y]))return!1;return!0}if(W$($)&&W$(w)){let Y=Object.keys($),A=Object.keys(w);if(Y.length!==A.length)return!1;for(let U of Y){if(!Object.prototype.hasOwnProperty.call(w,U))return!1;if(!ff($[U],w[U]))return!1}return!0}return!1}function W$($){return Boolean($&&typeof $==="object"&&!Array.isArray($))}class pU{extensions=[".ts",".js",".mjs",".cjs",".json",".mts",".cts"];async loadFromPath($,w,Y={}){let{arrayStrategy:A="replace",useCache:U=!0,cacheTtl:X,trackPerformance:J=!0,verbose:W=!1}=Y;if(U){let B=y1.getWithFileCheck("file",$);if(B){if(W)console.log(`Configuration loaded from cache: ${$}`);return B}}let f=async()=>{if(!hU($))return null;try{let B=`?t=${Date.now()}`,j=await import($+B),z=j.default||j,G="default"in j,F=Object.keys(j).length>0;if(!G&&!F)throw new zY($,Error("Configuration file is empty and exports nothing"),"unknown");if(typeof z!=="object"||z===null||Array.isArray(z))throw new zY($,Error("Configuration must export a valid object"),"unknown");let H={config:Rf(w,z,A),source:{type:"file",path:$,priority:100,timestamp:new Date}};if(U)y1.setWithFileCheck("file",H,$,X);return H}catch(B){throw B instanceof Error?Gw.configLoad($,B):Gw.configLoad($,Error(String(B)))}};if(J)return GY.track("loadFromPath",f,{path:$});return f()}async tryLoadFromPaths($,w,Y={}){for(let A of $)try{let U=await this.loadFromPath(A,w,Y);if(U)return U}catch(U){if(U instanceof Error&&U.name==="ConfigLoadError")throw U;if(Y.verbose)console.warn(`Failed to load config from ${A}:`,U)}return null}generateConfigPaths($,w,Y){let A=this.generateNamePatterns($,Y),U=[];for(let X of A)for(let J of this.extensions)U.push(rJ(w,`${X}${J}`));return U}generateNamePatterns($,w){let Y=[];if(Y.push("config",".config"),$)Y.push($,`.${$}.config`,`${$}.config`,`.${$}`);if(w){if(Y.push(w,`.${w}.config`,`${w}.config`,`.${w}`),$)Y.push(`${$}.${w}.config`,`.${$}.${w}.config`)}return Y.filter(Boolean)}checkFileAccess($){return a9(async()=>{return hU($)},{maxRetries:2,retryDelay:100,fallback:!1})}async discoverConfigFiles($,w,Y){let A=[];if(!hU($))return A;if(w||Y){let U=this.generateNamePatterns(w||"",Y);for(let X of U)for(let J of this.extensions){let W=rJ($,`${X}${J}`);if(await this.checkFileAccess(W))A.push(W)}}else try{let{readdirSync:U}=await import("fs"),X=U($);for(let J of X)if(this.looksLikeConfigFile(J)){let W=rJ($,J);if(await this.checkFileAccess(W))A.push(W)}}catch{return[]}return A}looksLikeConfigFile($){return[/\.config\.(ts|js|mjs|cjs|json|mts|cts)$/,/^\..*\.(ts|js|mjs|cjs|json|mts|cts)$/,/config\.(ts|js|mjs|cjs|json|mts|cts)$/].some((Y)=>Y.test($))}async validateConfigFile($){let w=[];try{if(!hU($))return w.push("Configuration file does not exist"),w;let Y=await import($),A=Y.default||Y;if(A===void 0)w.push("Configuration file must export a default value or named exports");else if(typeof A!=="object"||A===null)w.push("Configuration must be an object");else if(Array.isArray(A))w.push("Configuration cannot be an array at the root level");if($.endsWith(".json"))try{let{readFileSync:U}=await import("fs"),X=U($,"utf8");JSON.parse(X)}catch(U){w.push(`Invalid JSON syntax: ${U}`)}}catch(Y){w.push(`Failed to load configuration file: ${Y}`)}return w}async getFileModificationTime($){try{let{statSync:w}=await import("fs");return w($).mtime}catch{return null}}async preloadConfigurations($,w={}){let Y=new Map;return await Promise.allSettled($.map(async(A)=>{try{let U=await this.loadFromPath(A,{},w);if(U)Y.set(A,U.config)}catch(U){if(w.verbose)console.warn(`Failed to preload ${A}:`,U)}})),Y}}class Mf{async validateConfiguration($,w,Y={}){let{stopOnFirstError:A=!1,validateRequired:U=!0,validateTypes:X=!0,customRules:J=[],trackPerformance:W=!0,verbose:f=!1}=Y,B=async()=>{let j=[],z=[],G={stopOnFirstError:A,validateRequired:U,validateTypes:X,customRules:J,trackPerformance:W,verbose:f};try{if(typeof w==="string")return await this.validateWithSchemaFile($,w,G);else if(Array.isArray(w))return this.validateWithRules($,[...w,...J],G);else return this.validateWithJSONSchema($,w,G)}catch(F){return j.push({path:"",message:`Validation failed: ${F}`,rule:"system"}),{isValid:!1,errors:j,warnings:z}}};if(W)return await GY.track("validateConfiguration",B);return B()}async validateWithSchemaFile($,w,Y){try{if(!uT(w))throw new FY(w,[{path:"",message:"Schema file does not exist"}]);let A=await import(w),U=A.default||A;if(Array.isArray(U))return this.validateWithRules($,U,Y);else return this.validateWithJSONSchema($,U,Y)}catch(A){throw new FY(w,[{path:"",message:`Failed to load schema: ${A}`}])}}validateWithJSONSchema($,w,Y){let A=[],U=[];return this.validateObjectAgainstSchema($,w,"",A,U,Y),{isValid:A.length===0,errors:A,warnings:U}}validateObjectAgainstSchema($,w,Y,A,U,X){if(X.validateTypes&&w.type){let J=Array.isArray($)?"array":typeof $,W=Array.isArray(w.type)?w.type:[w.type];if(!W.includes(J)){if(A.push({path:Y,message:`Expected type ${W.join(" or ")}, got ${J}`,expected:W.join(" or "),actual:J,rule:"type"}),X.stopOnFirstError)return}}if(w.enum&&!w.enum.includes($)){if(A.push({path:Y,message:`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"}),X.stopOnFirstError)return}if(typeof $==="string"){if(w.minLength!==void 0&&$.length<w.minLength)A.push({path:Y,message:`String length must be at least ${w.minLength}`,expected:`>= ${w.minLength}`,actual:$.length,rule:"minLength"});if(w.maxLength!==void 0&&$.length>w.maxLength)A.push({path:Y,message:`String length must not exceed ${w.maxLength}`,expected:`<= ${w.maxLength}`,actual:$.length,rule:"maxLength"});if(w.pattern){if(!new RegExp(w.pattern).test($))A.push({path:Y,message:`String does not match pattern ${w.pattern}`,expected:w.pattern,actual:$,rule:"pattern"})}}if(typeof $==="number"){if(w.minimum!==void 0&&$<w.minimum)A.push({path:Y,message:`Value must be at least ${w.minimum}`,expected:`>= ${w.minimum}`,actual:$,rule:"minimum"});if(w.maximum!==void 0&&$>w.maximum)A.push({path:Y,message:`Value must not exceed ${w.maximum}`,expected:`<= ${w.maximum}`,actual:$,rule:"maximum"})}if(Array.isArray($)&&w.items)for(let J=0;J<$.length;J++){let W=Y?`${Y}[${J}]`:`[${J}]`;if(this.validateObjectAgainstSchema($[J],w.items,W,A,U,X),X.stopOnFirstError&&A.length>0)return}if($&&typeof $==="object"&&!Array.isArray($)){let J=$;if(X.validateRequired&&w.required){for(let W of w.required)if(!(W in J)){if(A.push({path:Y?`${Y}.${W}`:W,message:`Missing required property '${W}'`,expected:"required",rule:"required"}),X.stopOnFirstError)return}}if(w.properties){for(let[W,f]of Object.entries(w.properties))if(W in J){let B=Y?`${Y}.${W}`:W;if(this.validateObjectAgainstSchema(J[W],f,B,A,U,X),X.stopOnFirstError&&A.length>0)return}}if(w.additionalProperties===!1){let W=new Set(Object.keys(w.properties||{}));for(let f of Object.keys(J))if(!W.has(f))U.push({path:Y?`${Y}.${f}`:f,message:`Additional property '${f}' is not allowed`,rule:"additionalProperties"})}}}validateWithRules($,w,Y){let A=[],U=[];for(let X of w)try{let J=this.getValueByPath($,X.path),W=this.validateWithRule(J,X,X.path);if(A.push(...W),Y.stopOnFirstError&&A.length>0)break}catch(J){A.push({path:X.path,message:`Rule validation failed: ${J}`,rule:"system"})}return{isValid:A.length===0,errors:A,warnings:U}}validateWithRule($,w,Y){let A=[];if(w.required&&($===void 0||$===null))return A.push({path:Y,message:w.message||`Property '${Y}' is required`,expected:"required",rule:"required"}),A;if($===void 0||$===null)return A;if(w.type){let U=Array.isArray($)?"array":typeof $;if(U!==w.type)A.push({path:Y,message:w.message||`Expected type ${w.type}, got ${U}`,expected:w.type,actual:U,rule:"type"})}if(w.min!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U<w.min)A.push({path:Y,message:w.message||`Value must be at least ${w.min}`,expected:`>= ${w.min}`,actual:U,rule:"min"})}if(w.max!==void 0){let U=Array.isArray($)?$.length:typeof $==="string"?$.length:typeof $==="number"?$:0;if(U>w.max)A.push({path:Y,message:w.message||`Value must not exceed ${w.max}`,expected:`<= ${w.max}`,actual:U,rule:"max"})}if(w.pattern&&typeof $==="string"){if(!w.pattern.test($))A.push({path:Y,message:w.message||`Value does not match pattern ${w.pattern}`,expected:w.pattern.toString(),actual:$,rule:"pattern"})}if(w.enum&&!w.enum.includes($))A.push({path:Y,message:w.message||`Value must be one of: ${w.enum.join(", ")}`,expected:w.enum.join(", "),actual:$,rule:"enum"});if(w.validator){let U=w.validator($);if(U)A.push({path:Y,message:w.message||U,rule:"custom"})}return A}getValueByPath($,w){if(!w)return $;let Y=w.split("."),A=$;for(let U of Y)if(A&&typeof A==="object"&&U in A)A=A[U];else return;return A}generateRulesFromInterface($){let w=[],Y=$.matchAll(/(\w+)(\?)?:\s*(\w+)/g);for(let A of Y){let[,U,X,J]=A;w.push({path:U,required:!X,type:this.mapTypeScriptType(J)})}return w}mapTypeScriptType($){switch($.toLowerCase()){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"array":return"array";case"object":return"object";default:return"object"}}static createCommonRules(){return{server:[{path:"port",required:!0,type:"number",min:1,max:65535},{path:"host",required:!0,type:"string",min:1},{path:"ssl",type:"boolean"}],database:[{path:"url",required:!0,type:"string",min:1},{path:"pool",type:"number",min:1,max:100},{path:"timeout",type:"number",min:0}],api:[{path:"baseUrl",required:!0,type:"string",pattern:f2},{path:"timeout",type:"number",min:0},{path:"retries",type:"number",min:0,max:10}]}}}class If{fileLoader=new pU;envProcessor=new nU;validator=new Mf;async loadConfig($){let w=Date.now(),{cache:Y,performance:A,schema:U,validate:X,...J}=$;try{if(Y?.enabled){let f=this.checkCache(J.name||"",J);if(f)return f}let W;try{W=await this.loadConfigurationStrategies(J,!0,Y)}catch(f){let B=J.__strictErrorHandling;if(f instanceof Error&&f.name==="ConfigNotFoundError"){if(B)throw f;W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`No configuration file found for "${J.name||"config"}", using defaults with environment variables`]}}else if(f instanceof Error&&f.name==="ConfigLoadError"){let j=f.message.includes("EACCES")||f.message.includes("EPERM")||f.message.includes("permission denied"),z=!j&&(f.message.includes("syntax")||f.message.includes("Expected")||f.message.includes("Unexpected")||f.message.includes("BuildMessage")||f.message.includes("errors building")),G=f.message.includes("Configuration must export a valid object")||f.message.includes("Configuration file is empty and exports nothing");if(B&&(G||j))throw f;if(z&&(!B||!G))W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:["Configuration file has syntax errors, using defaults with environment variables"]};else if(!B)W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading error, using defaults: ${f.message}`]};else throw f}else W={...await this.applyEnvironmentVariables(J.name||"",J.defaultConfig,J.checkEnv!==!1,J.verbose||!1),warnings:[`Configuration loading failed, using defaults: ${f instanceof Error?f.message:String(f)}`]}}if(U||X)await this.validateConfiguration(W.config,U,X,J.name);if(Y?.enabled&&W)this.cacheResult(J.name||"",W,Y,J);if(A?.enabled){let f={operation:"loadConfig",duration:Date.now()-w,configName:J.name,timestamp:new Date};if(A.onMetrics)A.onMetrics(f);if(A.slowThreshold&&f.duration>A.slowThreshold)q$.warn(`Slow configuration loading detected: ${f.duration}ms for ${J.name}`);W.metrics=f}return W}catch(W){let f=Date.now()-w;throw q$.error(`Configuration loading failed after ${f}ms:`,[W instanceof Error?W:Error(String(W))]),W}}async loadConfigurationStrategies($,w=!1,Y){let{name:A="",alias:U,cwd:X,configDir:J,defaultConfig:W,checkEnv:f=!0,arrayStrategy:B="replace",verbose:j=!1}=$,z=X||Qw.cwd(),G=[],F=await this.loadLocalConfiguration(A,U,z,J,W,B,j,f,Y);if(F)return G.push(...this.getLocalSearchPaths(A,U,z,J)),this.finalizeResult(F,G,f,A,j);let T=await this.loadHomeConfiguration(A,U,W,B,j,f);if(T)return G.push(...this.getHomeSearchPaths(A,U)),this.finalizeResult(T,G,f,A,j);let K=await this.loadPackageJsonConfiguration(A,U,z,W,B,j,f);if(K)return G.push(d0(z,"package.json")),this.finalizeResult(K,G,f,A,j);if(G.push(...this.getAllSearchPaths(A,U,z,J)),w)throw Gw.configNotFound(A,G,U);return{...await this.applyEnvironmentVariables(A,W,f,j),warnings:[`No configuration file found for "${A}"${U?` or alias "${U}"`:""}, using defaults with environment variables`]}}async loadLocalConfiguration($,w,Y,A,U,X,J,W,f){let B=W?BY($,U,J):U,j=this.getLocalDirectories(Y,A);for(let z of j){if(J)q$.info(`Searching for configuration in: ${z}`);let G=this.fileLoader.generateConfigPaths($,z,w),F=await this.fileLoader.tryLoadFromPaths(G,B,{arrayStrategy:X,verbose:J,cacheTtl:f?.ttl,useCache:!f?.ttl||f.ttl>100});if(F){if(J)q$.success(`Configuration loaded from: ${F.source.path}`);return F}}return null}async loadHomeConfiguration($,w,Y,A,U,X){if(!$)return null;let J=X?BY($,Y,U):Y,W=[d0(G1(),".config",$),d0(G1(),".config"),G1()];for(let f of W){if(U)q$.info(`Checking home directory: ${f}`);let B=this.fileLoader.generateConfigPaths($,f,w),j=await this.fileLoader.tryLoadFromPaths(B,J,{arrayStrategy:A,verbose:U});if(j){if(U)q$.success(`Configuration loaded from home directory: ${j.source.path}`);return j}}return null}async loadPackageJsonConfiguration($,w,Y,A,U,X,J){let W=J?BY($,A,X):A;try{let f=d0(Y,"package.json");if(!Xf(f))return null;let B=await import(f),j=B[$],z=$;if(!j&&w)j=B[w],z=w;if(j&&typeof j==="object"&&!Array.isArray(j)){if(X)q$.success(`Configuration loaded from package.json: ${z}`);return{config:Rf(W,j,U),source:{type:"package.json",path:f,priority:30,timestamp:new Date}}}}catch(f){if(X)q$.warn("Failed to load package.json:",[f instanceof Error?f:Error(String(f))])}return null}async applyEnvironmentVariables($,w,Y,A){if(!Y||!$||typeof w!=="object"||w===null||Array.isArray(w))return{config:w,source:{type:"default",priority:10,timestamp:new Date}};return{config:BY($,w,A),source:{type:"environment",priority:20,timestamp:new Date}}}async finalizeResult($,w,Y,A,U){return{config:$.config,source:$.source,path:$.source.path}}async validateConfiguration($,w,Y,A){let U=[];if(Y){let X=Y($);if(X)U.push(...X)}if(w){let X=await this.validator.validateConfiguration($,w);if(!X.isValid)U.push(...X.errors.map((J)=>J.path?`${J.path}: ${J.message}`:J.message))}if(U.length>0)throw Gw.configValidation(A||"unknown",U,A)}checkCache($,w){let Y=this.generateCacheKey($,w);return y1.get(Y)||null}cacheResult($,w,Y,A){let U=this.generateCacheKey($,A);y1.set(U,w,void 0,Y.ttl)}generateCacheKey($,w){let Y=[$];if(w.alias)Y.push(`alias:${w.alias}`);if(w.cwd)Y.push(`cwd:${w.cwd}`);if(w.configDir)Y.push(`configDir:${w.configDir}`);if("checkEnv"in w)Y.push(`checkEnv:${w.checkEnv}`);return Y.join("|")}getLocalDirectories($,w){return Array.from(new Set([$,d0($,"config"),d0($,".config"),w?d0($,w):void 0].filter(Boolean)))}getAllSearchPaths($,w,Y,A){let U=[];return U.push(...this.getLocalSearchPaths($,w,Y,A)),U.push(...this.getHomeSearchPaths($,w)),U.push(d0(Y,"package.json")),U}getLocalSearchPaths($,w,Y,A){let U=this.getLocalDirectories(Y,A),X=[];for(let J of U)X.push(...this.fileLoader.generateConfigPaths($,J,w));return X}getHomeSearchPaths($,w){if(!$)return[];let Y=[d0(G1(),".config",$),d0(G1(),".config"),G1()],A=[];for(let U of Y)A.push(...this.fileLoader.generateConfigPaths($,U,w));return A}async loadConfigWithResult($){return this.loadConfig($)}}function h9($){let Y=!($.message.includes("EACCES")||$.message.includes("EPERM")||$.message.includes("permission denied"))&&($.message.includes("syntax")||$.message.includes("Expected")||$.message.includes("Unexpected")||$.message.includes("BuildMessage")),A=$.message.includes("Configuration must export a valid object")||$.message.includes("Configuration file is empty and exports nothing");return Y||A}async function WH($){return r$.loadConfig({...$,__strictErrorHandling:!0})}async function w2($){let w="defaultConfig"in $&&$.defaultConfig!==void 0?$.defaultConfig:{},Y="cache"in $||"performance"in $||"schema"in $||"validate"in $;try{let A;if(Y)A=await r$.loadConfig($);else A=await r$.loadConfig({...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}});return A?.config??w}catch(A){let U=A instanceof Error?A.name:"UnknownError",X=A instanceof Error?A.message:String(A);if(!(U==="ConfigNotFoundError"||U==="ConfigLoadError"||U==="ConfigValidationError"||X.includes("config"))&&$.verbose)q$.warn("Unexpected error loading config, using defaults:",[A instanceof Error?A:Error(String(A))]);let W=Y?{...$,defaultConfig:w}:{...$,defaultConfig:w,cache:{enabled:!0},performance:{enabled:!1}};if("checkEnv"in $?$.checkEnv!==!1:!0)return(await r$.applyEnvironmentVariables(W.name||"",w,!0,W.verbose||!1))?.config??w;return w}}async function BH($={defaultConfig:{}}){if(typeof $==="string"){let{cwd:w}=await import("process");try{return(await r$.loadConfig({name:$,cwd:w(),generatedDir:"./generated",configDir:"./config",defaultConfig:{},checkEnv:!0,arrayStrategy:"replace"})).config}catch(Y){if(Y instanceof Error&&(Y.name==="ConfigNotFoundError"||Y.name==="ConfigLoadError"&&h9(Y)))return(await r$.applyEnvironmentVariables($,{},!0,!1)).config;throw Y}}try{return(await r$.loadConfig({...$,cwd:$.cwd||Qw.cwd(),cache:{enabled:!0},performance:{enabled:!1}})).config}catch(w){if(w instanceof Error&&(w.name==="ConfigNotFoundError"||w.name==="ConfigLoadError"&&h9(w)))return(await r$.applyEnvironmentVariables($.name||"",$.defaultConfig||{},$.checkEnv!==!1,$.verbose||!1)).config;throw w}}async function jH($,w,Y="replace"){let A=new pU;try{let U=await A.loadFromPath($,w,{arrayStrategy:Y,useCache:!1,trackPerformance:!1});return U?U.config:null}catch{return null}}function BY($,w,Y=!1){let A=new nU,U=$.toUpperCase().replace(/[^A-Z0-9]/g,"_");function X(J,W=[]){let f={...J};for(let[B,j]of Object.entries(J)){let z=[...W,B],G=[`${U}_${z.join("_").toUpperCase()}`,`${U}_${z.map((K)=>K.toUpperCase()).join("")}`,`${U}_${z.map((K)=>K.replace(/([A-Z])/g,"_$1").toUpperCase()).join("")}`],F,T;for(let K of G)if(F=Qw.env[K],F!==void 0){T=K;break}if(F!==void 0&&T)if(typeof j==="boolean")f[B]=["true","1","yes"].includes(F.toLowerCase());else if(typeof j==="number"){let K=Number(F);if(!Number.isNaN(K))f[B]=K}else if(Array.isArray(j))try{f[B]=JSON.parse(F)}catch{f[B]=F.split(",").map((K)=>K.trim())}else f[B]=F;else if(j&&typeof j==="object"&&!Array.isArray(j))f[B]=X(j,z)}return f}return X(w)}function zH($){let w=d0(Qw.cwd(),$.configDir),Y=d0(Qw.cwd(),$.generatedDir),A=d0(Y,"config-types.ts");if(!Xf(B9(A)))KT(B9(A),{recursive:!0,mode:511});let U=Xf(w)?TT(w).map((J)=>J.replace(/\.(ts|js|mjs|cjs|mts|cts|json)$/,"")).sort():[],X=`// Generated by bunfig v${cH}
164
+ export type ConfigNames = ${U.length?`'${U.join("' | '")}'`:"string"}
165
+ `;HT(A,X,{mode:438})}function FH($){let w=null,Y=null,A=()=>{if(!Y)Y=w2($).then((X)=>{return w=X,X},(X)=>{let J="defaultConfig"in $?$.defaultConfig:{};if(w=J,"verbose"in $&&$.verbose)q$.warn("Config loading failed, using defaults:",[X instanceof Error?X:Error(String(X))]);return J});return Y},U="defaultConfig"in $?$.defaultConfig:{};return w=U,A(),new Proxy({},{get(X,J){if(w)return w[J];let W=U[J];return A(),W},has(X,J){return J in(w||U)},ownKeys(){return Object.keys(w||U)},getOwnPropertyDescriptor(X,J){return Object.getOwnPropertyDescriptor(w||U,J)},set(X,J,W){if(!w)w={...U};return w[J]=W,!0}})}function GH($){let w=C9(vT.cwd(),$?.configDir||"./config");function Y(){if(!iT(w))return[];let U=new Set([".ts",".js",".mjs",".cjs",".mts",".cts",".json"]),X=[".ts",".mts",".cts",".js",".mjs",".cjs",".json"],J=cT(w).filter((f)=>U.has(aJ(f))).map((f)=>({base:f.replace(/\.(?:ts|js|mjs|cjs|mts|cts|json)$/i,""),file:f})),W=new Map;for(let{base:f,file:B}of J){let j=aJ(B).toLowerCase(),z=W.get(f);if(!z){W.set(f,B);continue}let G=aJ(z).toLowerCase();if(X.indexOf(j)<X.indexOf(G))W.set(f,B)}return Array.from(W.entries()).map(([f,B])=>({base:f,file:B})).sort((f,B)=>f.base.localeCompare(B.base))}function A(){let U=Y(),X=U.map((B)=>B.base),J=X.length?X.map((B)=>`'${B}'`).join(" | "):"string",W=U.length?`{
166
+ ${U.map((B)=>{let j=C9(w,B.file).replace(/\\/g,"/");return` '${B.base}': typeof import('${j}').default`}).join(`,
165
167
  `)}
166
- }`:"Record<string, any>";return`export type ConfigNames = ${U}
168
+ }`:"Record<string, any>";return`export type ConfigNames = ${J}
167
169
  export type ConfigByName = ${W}
168
170
  export type Config<N extends ConfigNames> = N extends keyof ConfigByName ? ConfigByName[N] : unknown
169
171
  export type ConfigOf = Config
170
- `}return{name:"bunfig-plugin",setup(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:Y(),loader:"ts"}})}}}function VH($,w={}){let A=uX.cwd();while(A.includes("storage"))A=L2(A,"..");let Y=L2(A,$||"");if(w?.relative)return hH(uX.cwd(),Y);return Y}function I0(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function bH(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t$<"u"){let $=t$.type;if($==="renderer"||$==="worker")return!1;return!!(t$.versions&&(t$.versions.node||t$.versions.bun))}return!1}class Az{async format($){let w=await bH(),A=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:A})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:y1.pid,hostname:w(),environment:y1.env.NODE_ENV||"development",platform:y1.platform,version:y1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:y1.env.NODE_ENV||y1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ow{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...iX},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new Az,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??x.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let A={...w},Y=w.timestamp!==void 0;if(Y)delete A.timestamp;if(this.config={...this.config,...A,timestamp:Y||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let X=this.generateKeyId(),J=this.generateKey();this.currentKeyId=X,this.keys.set(X,J),this.encryptionKeys.set(X,{key:J,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},A=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[A]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...pU,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...pU};return{...pU,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:iX.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},A={...w,...Object.fromEntries(Object.entries($).filter(([,Y])=>Y!==void 0))};if(!A.level||!["debug","info","success","warning","error"].includes(A.level))A.level=w.level;return A}shouldWriteToFile(){return!I0()&&this.config.writeToFile===!0}async writeToFile($){let A=(async()=>{let X,J=0,U=3,W=1000;while(J<U)try{try{try{await kH(this.config.logDirectory,_2.F_OK|_2.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await DH(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:n$.from($);try{if(!MX(this.currentLogFile))await lU(this.currentLogFile,"",{mode:420});if(X=S2(this.currentLogFile,"a",420),_H(X,f,{flag:"a"}),Q2(X),X!==void 0)nU(X),X=void 0;if((await M1(this.currentLogFile)).size===0){if(await lU(this.currentLogFile,f,{flag:"w",mode:420}),(await M1(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 E=W*2**J;await new Promise((F)=>setTimeout(F,E)),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{nU(X)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(J===U-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}J++;let B=W*2**(J-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(A);let Y=this.pendingOperations.length-1;try{await A}catch(X){throw console.error("Debug: [writeToFile] Error in operation:",X),X}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 $=new Date().toISOString().split("T")[0];return I1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(I0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let A=typeof w.interval==="number"?w.interval:60,Y=Math.max(A,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((X)=>{console.error("Error rotating keys:",X)})},Y)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,A=this.generateKeyId(),Y=this.generateKey();this.currentKeyId=A,this.keys.set(A,Y),this.encryptionKeys.set(A,{key:Y,createdAt:new Date});let X=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),J=typeof w.maxKeys==="number"?w.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 gU(16).toString("hex")}generateKey(){return gU(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),A=gU(16),Y=OH("aes-256-gcm",w,A),X=n$.isBuffer($)?$:n$.from($,"utf8"),J=Y.update(X),U=Y.final(),W=J.length+U.length,f=Y.getAuthTag(),B=n$.allocUnsafe(16+W+16);return A.copy(B,0),J.copy(B,16),U.copy(B,16+J.length),f.copy(B,16+W),{encrypted:B,iv:A}}async compressData($){return new Promise((w,A)=>{let Y=D2(),X=[];Y.on("data",(J)=>X.push(J)),Y.on("end",()=>w(n$.from(n$.concat(X)))),Y.on("error",A),Y.write($),Y.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(I0())return;if(!this.shouldWriteToFile())return;let $=await M1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let A=this.currentLogFile,Y=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let X=await IX(this.config.logDirectory),J=X.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),U=J.length>0?Number.parseInt(J[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${A}.${U}`;if(await M1(A).catch(()=>null))try{if(await k2(A,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await yX(W)}catch(f){console.error("Error compressing rotated file:",f)}if(J.length===0&&!X.some((f)=>f.endsWith(".log.1")))try{let f=`${A}.1`;await lU(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let X=new Date().toISOString().replace(/[:.]/g,"-"),J=A.replace(/\.log$/,`-${X}.log`);if(await M1(A).catch(()=>null))await k2(A,J)}if(this.currentLogFile=Y,w.maxFiles){let J=(await IX(this.config.logDirectory)).filter((U)=>U.startsWith(this.name)).sort((U,W)=>W.localeCompare(U));for(let U of J.slice(w.maxFiles))await yX(I1(this.config.logDirectory,U))}}}async compressLogFile($,w){let A=O2($),Y=SH(w),X=D2();await PH(A,X,Y)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let A of this.logBuffer){let Y=await this.formatter.format(A);if(this.shouldWriteToFile())await this.writeToFile(Y);console.log(Y)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),MX(this.currentLogFile))try{let $=S2(this.currentLogFile,"r+");Q2($),nU($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!I0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await IX(this.config.logDirectory)).filter((A)=>(A.includes("temp")||A.includes(".tmp"))&&A.includes(this.name));for(let A of w)try{await yX(I1(this.config.logDirectory,A))}catch(Y){console.error(`Failed to delete temp file ${A}:`,Y)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?v.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||I0())return!1;let $=typeof x.env.NO_COLOR<"u",w=x.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof x.stderr<"u"&&x.stderr.isTTY||typeof x.stdout<"u"&&x.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:A="",tag:Y="",message:X,level:J,showTimestamp:U=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(U)F.push(w);if(J==="warning")F.push("WARN");else if(J==="error")F.push("ERROR");else if(A)F.push(A.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(Y)F.push(Y.replace(/[[\]]/g,""));return F.push(X),F.join(" ")}let f=x.stdout.columns||120,B="";if(J==="warning"||J==="error")B=`${A} ${X}`;else if(J==="info"||J==="success")B=`${A} ${Y} ${X}`;else B=`${A} ${Y} ${v.cyan(X)}`;if(!U)return B.trim();let j=W(B).trim().length,z=W(w).length,E=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(E)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(J,U)=>{let W=Number.parseInt(U,10);return W<w[0].length?String(w[0][W]):J});let A=/%([sdijfo%])/g,Y=0,X=$.replace(A,(J,U)=>{if(U==="%")return"%";if(Y>=w.length)return J;let W=w[Y++];switch(U){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return J}});if(Y<w.length)X+=` ${w.slice(Y).map((J)=>typeof J==="object"?JSON.stringify(J,null,2):String(J)).join(" ")}`;return X}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(A,Y,X)=>{let J=v.underline(v.blue(Y)),U=this.toAbsoluteFilePath(X);if(U&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(U)}`,f="\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}),w=w.replace(/`([^`]+)`/g,(A,Y)=>v.bgGray(Y)),w=w.replace(/\*\*([^*]+)\*\*/g,(A,Y)=>v.bold(Y)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(A,Y)=>v.italic(Y)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(A,Y)=>v.italic(Y)),w=w.replace(/~([^~]+)~/g,(A,Y)=>v.strikethrough(Y)),w}supportsHyperlinks(){if(I0())return!1;let $=x.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let A=x.env.HOME||"";if(A)w=w.replace(/^~(?=$|\/)/,A)}if(ZH(w)||w.startsWith("./")||w.startsWith("../"))w=xH(w);else return null;return MX(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,A=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:A}}async log($,w,...A){if(!this.shouldLog($))return;let Y=new Date,X=this.formatConsoleTimestamp(Y),J=this.formatFileTimestamp(Y),U,W;if(w instanceof Error)U=w.message,W=w.stack;else U=this.formatMessage(w,A);let{consoleText:f,fileText:B}=this.buildOutputTexts(U);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":mH[$],E=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:v.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:v.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:X,icon:z,tag:E,message:f,level:$}),console.error(F),W){let T=W.split(`
171
- `);for(let K of T)if(K.trim()&&!K.includes(U))console.error(this.formatConsoleMessage({timestamp:X,message:v.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!I0()){if(console.error(`${J} ${this.environment}.${$.toUpperCase()}: ${U}`),W)console.error(W)}let j=`${J} ${this.environment}.${$.toUpperCase()}: ${B}
172
+ `}return{name:"bunfig-plugin",setup(U){U.onResolve({filter:/^virtual:bunfig-types$/},(X)=>{return{path:X.path,namespace:"bunfig-virtual"}}),U.onLoad({filter:/^virtual:bunfig-types$/,namespace:"bunfig-virtual"},()=>{return{contents:A(),loader:"ts"}})}}}function gH($,w={}){let Y=gU.cwd();while(Y.includes("storage"))Y=P9(Y,"..");let A=P9(Y,$||"");if(w?.relative)return dH(gU.cwd(),A);return A}function M0(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function wN(){if(t$.env.NODE_ENV==="test"||t$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof t$<"u"){let $=t$.type;if($==="renderer"||$==="worker")return!1;return!!(t$.versions&&(t$.versions.node||t$.versions.bun))}return!1}class z2{async format($){let w=await wN(),Y=await this.getMetadata(w);return JSON.stringify({timestamp:$.timestamp.toISOString(),level:$.level,name:$.name,message:$.message,metadata:Y})}async getMetadata($){if($){let{hostname:w}=await import("os");return{pid:I1.pid,hostname:w(),environment:I1.env.NODE_ENV||"development",platform:I1.platform,version:I1.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:I1.env.NODE_ENV||I1.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class Ow{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor($,w={}){this.name=$,this.config={...lU},this.options=this.normalizeOptions(w),this.formatter=this.options.formatter||new z2,this.enabled=w.enabled??!0,this.fancy=w.fancy??!0,this.tagFormat=w.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=w.timestampPosition??"right",this.environment=w.environment??Z.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(w);let Y={...w},A=w.timestamp!==void 0;if(A)delete Y.timestamp;if(this.config={...this.config,...Y,timestamp:A||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let U=this.generateKeyId(),X=this.generateKey();this.currentKeyId=U,this.keys.set(U,X),this.encryptionKeys.set(U,{key:X,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed($){if(!this.fingersCrossedConfig)return!1;let w={debug:0,info:1,success:2,warning:3,error:4},Y=this.fingersCrossedConfig.activationLevel??"error";return w[$]>=w[Y]}initializeFingersCrossedConfig($){if(!$.fingersCrossedEnabled&&$.fingersCrossed)return{...Uf,...$.fingersCrossed};if(!$.fingersCrossedEnabled)return null;if(!$.fingersCrossed)return{...Uf};return{...Uf,...$.fingersCrossed}}normalizeOptions($){let w={format:"json",level:"info",logDirectory:lU.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},Y={...w,...Object.fromEntries(Object.entries($).filter(([,A])=>A!==void 0))};if(!Y.level||!["debug","info","success","warning","error"].includes(Y.level))Y.level=w.level;return Y}shouldWriteToFile(){return!M0()&&this.config.writeToFile===!0}async writeToFile($){let Y=(async()=>{let U,X=0,J=3,W=1000;while(X<J)try{try{try{await aH(this.config.logDirectory,c9.F_OK|c9.W_OK)}catch(B){if(B instanceof Error&&"code"in B)if(B.code==="ENOENT")await sH(this.config.logDirectory,{recursive:!0,mode:493});else if(B.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw B;else throw B}}catch(B){throw console.error("Debug: [writeToFile] Failed to create log directory:",B),B}let f=this.validateEncryptionConfig()?(await this.encrypt($)).encrypted:l$.from($);try{if(!LU(this.currentLogFile))await Af(this.currentLogFile,"",{mode:420});if(U=i9(this.currentLogFile,"a",420),rH(U,f,{flag:"a"}),u9(U),U!==void 0)Yf(U),U=void 0;if((await R1(this.currentLogFile)).size===0){if(await Af(this.currentLogFile,f,{flag:"w",mode:420}),(await R1(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(B){let j=B;if(j.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(j.code)){if(X<J-1){let z=typeof j.message==="string"?j.message:"Unknown error";console.error(`Network error during write attempt ${X+1}/${J}:`,z);let G=W*2**X;await new Promise((F)=>setTimeout(F,G)),X++;continue}}if(j?.code&&["ENOSPC","EDQUOT"].includes(j.code))throw Error(`Disk quota exceeded or no space left on device: ${j.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",j),j}finally{if(U!==void 0)try{Yf(U)}catch(B){console.error("Debug: [writeToFile] Error closing file descriptor:",B)}}}catch(f){if(X===J-1){let j=f,z=typeof j.message==="string"?j.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",z),f}X++;let B=W*2**(X-1);await new Promise((j)=>setTimeout(j,B))}})();this.pendingOperations.push(Y);let A=this.pendingOperations.length-1;try{await Y}catch(U){throw console.error("Debug: [writeToFile] Error in operation:",U),U}finally{this.pendingOperations.splice(A,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return M1(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return M1(this.config.logDirectory,`${this.name}.log`);let $=new Date().toISOString().split("T")[0];return M1(this.config.logDirectory,`${this.name}-${$}.log`)}setupRotation(){if(M0())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let $=this.config.rotation,w;switch($.frequency){case"daily":w=86400000;break;case"weekly":w=604800000;break;case"monthly":w=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},w)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let w=this.config.rotation.keyRotation;if(!w?.enabled)return;let Y=typeof w.interval==="number"?w.interval:60,A=Math.max(Y,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((U)=>{console.error("Error rotating keys:",U)})},A)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let w=this.config.rotation.keyRotation,Y=this.generateKeyId(),A=this.generateKey();this.currentKeyId=Y,this.keys.set(Y,A),this.encryptionKeys.set(Y,{key:A,createdAt:new Date});let U=Array.from(this.encryptionKeys.entries()).sort(([,W],[,f])=>f.createdAt.getTime()-W.createdAt.getTime()),X=typeof w.maxKeys==="number"?w.maxKeys:1,J=Math.max(1,X);if(U.length>J)for(let[W]of U.slice(J))this.encryptionKeys.delete(W),this.keys.delete(W)}generateKeyId(){return wf(16).toString("hex")}generateKey(){return wf(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let $=this.keys.get(this.currentKeyId);if(!$)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:$,id:this.currentKeyId}}encrypt($){let{key:w}=this.getCurrentKey(),Y=wf(16),A=nH("aes-256-gcm",w,Y),U=l$.isBuffer($)?$:l$.from($,"utf8"),X=A.update(U),J=A.final(),W=X.length+J.length,f=A.getAuthTag(),B=l$.allocUnsafe(16+W+16);return Y.copy(B,0),X.copy(B,16),J.copy(B,16+X.length),f.copy(B,16+W),{encrypted:B,iv:Y}}async compressData($){return new Promise((w,Y)=>{let A=m9(),U=[];A.on("data",(X)=>U.push(X)),A.on("end",()=>w(l$.from(l$.concat(U)))),A.on("error",Y),A.write($),A.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let $={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let w=this.config.rotation.encrypt;return{...$,...w}}return $}async rotateLog(){if(M0())return;if(!this.shouldWriteToFile())return;let $=await R1(this.currentLogFile).catch(()=>null);if(!$)return;let w=this.config.rotation;if(typeof w==="boolean")return;if(w.maxSize&&$.size>=w.maxSize){let Y=this.currentLogFile,A=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let U=await QU(this.config.logDirectory),X=U.filter((f)=>f.startsWith(this.name)&&/\.log\.\d+$/.test(f)).sort((f,B)=>{let j=Number.parseInt(f.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(B.match(/\.log\.(\d+)$/)?.[1]||"0")-j}),J=X.length>0?Number.parseInt(X[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,W=`${Y}.${J}`;if(await R1(Y).catch(()=>null))try{if(await v9(Y,W),w.compress)try{let f=`${W}.gz`;await this.compressLogFile(W,f),await OU(W)}catch(f){console.error("Error compressing rotated file:",f)}if(X.length===0&&!U.some((f)=>f.endsWith(".log.1")))try{let f=`${Y}.1`;await Af(f,"")}catch(f){console.error("Error creating backup file:",f)}}catch(f){console.error(`Error during rotation: ${f instanceof Error?f.message:String(f)}`)}}else{let U=new Date().toISOString().replace(/[:.]/g,"-"),X=Y.replace(/\.log$/,`-${U}.log`);if(await R1(Y).catch(()=>null))await v9(Y,X)}if(this.currentLogFile=A,w.maxFiles){let X=(await QU(this.config.logDirectory)).filter((J)=>J.startsWith(this.name)).sort((J,W)=>W.localeCompare(J));for(let J of X.slice(w.maxFiles))await OU(M1(this.config.logDirectory,J))}}}async compressLogFile($,w){let Y=b9($),A=tH(w),U=m9();await $N(Y,U,A)}async handleFingersCrossedBuffer($,w){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed($)&&!this.isActivated){this.isActivated=!0;for(let Y of this.logBuffer){let A=await this.formatter.format(Y);if(this.shouldWriteToFile())await this.writeToFile(A);console.log(A)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(w);console.log(w)}}shouldLog($){if(!this.enabled)return!1;let w={debug:0,info:1,success:2,warning:3,error:4};return w[$]>=w[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map(($)=>{if($ instanceof Promise)return $.catch((w)=>{console.error("Error in pending write operation:",w)});return Promise.resolve()})),LU(this.currentLogFile))try{let $=i9(this.currentLogFile,"r+");u9($),Yf($)}catch($){console.error(`Error flushing file: ${$}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let $ of this.pendingOperations)if(typeof $.cancel==="function")$.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch($){console.error("Error waiting for pending operations:",$)}if(!M0()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let w=(await QU(this.config.logDirectory)).filter((Y)=>(Y.includes("temp")||Y.includes(".tmp"))&&Y.includes(this.name));for(let Y of w)try{await OU(M1(this.config.logDirectory,Y))}catch(A){console.error(`Failed to delete temp file ${Y}:`,A)}}catch($){console.error("Error cleaning up temporary files:",$)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag($){if(!$)return"";return`${this.tagFormat.prefix}${$}${this.tagFormat.suffix}`}formatFileTimestamp($){return`[${$.toISOString()}]`}formatConsoleTimestamp($){return this.shouldStyleConsole()?c.gray($.toLocaleTimeString()):$.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||M0())return!1;let $=typeof Z.env.NO_COLOR<"u",w=Z.env.FORCE_COLOR==="0";if($||w)return!1;return!!(typeof Z.stderr<"u"&&Z.stderr.isTTY||typeof Z.stdout<"u"&&Z.stdout.isTTY)}formatConsoleMessage($){let{timestamp:w,icon:Y="",tag:A="",message:U,level:X,showTimestamp:J=!0}=$,W=(F)=>F.replace(this.ANSI_PATTERN,"");if(!this.fancy){let F=[];if(J)F.push(w);if(X==="warning")F.push("WARN");else if(X==="error")F.push("ERROR");else if(Y)F.push(Y.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(A)F.push(A.replace(/[[\]]/g,""));return F.push(U),F.join(" ")}let f=Z.stdout.columns||120,B="";if(X==="warning"||X==="error")B=`${Y} ${U}`;else if(X==="info"||X==="success")B=`${Y} ${A} ${U}`;else B=`${Y} ${A} ${c.cyan(U)}`;if(!J)return B.trim();let j=W(B).trim().length,z=W(w).length,G=Math.max(1,f-2-j-z);return`${B.trim()}${" ".repeat(G)}${w}`}formatMessage($,w){if(w.length===1&&Array.isArray(w[0]))return $.replace(/\{(\d+)\}/g,(X,J)=>{let W=Number.parseInt(J,10);return W<w[0].length?String(w[0][W]):X});let Y=/%([sdijfo%])/g,A=0,U=$.replace(Y,(X,J)=>{if(J==="%")return"%";if(A>=w.length)return X;let W=w[A++];switch(J){case"s":return String(W);case"d":case"i":return Number(W).toString();case"j":case"o":return JSON.stringify(W,null,2);default:return X}});if(A<w.length)U+=` ${w.slice(A).map((X)=>typeof X==="object"?JSON.stringify(X,null,2):String(X)).join(" ")}`;return U}formatMarkdown($){if(!$)return $;let w=$;return w=w.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(Y,A,U)=>{let X=c.underline(c.blue(A)),J=this.toAbsoluteFilePath(U);if(J&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let W=`file://${encodeURI(J)}`,f="\x1B]8;;",B="\x1B\\";return`\x1B]8;;${W}\x1B\\${X}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${U}\x1B\\${X}\x1B]8;;\x1B\\`;return X}),w=w.replace(/`([^`]+)`/g,(Y,A)=>c.bgGray(A)),w=w.replace(/\*\*([^*]+)\*\*/g,(Y,A)=>c.bold(A)),w=w.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(Y,A)=>c.italic(A)),w=w.replace(/(?<!_)_([^_]+)_(?!_)/g,(Y,A)=>c.italic(A)),w=w.replace(/~([^~]+)~/g,(Y,A)=>c.strikethrough(A)),w}supportsHyperlinks(){if(M0())return!1;let $=Z.env;if(!$)return!1;if($.TERM_PROGRAM==="iTerm.app"||$.TERM_PROGRAM==="vscode"||$.TERM_PROGRAM==="WezTerm")return!0;if($.WT_SESSION)return!0;if($.TERM==="xterm-kitty")return!0;let w=$.VTE_VERSION?Number.parseInt($.VTE_VERSION,10):0;if(!Number.isNaN(w)&&w>=5000)return!0;return!1}toAbsoluteFilePath($){try{let w=$;if(w.startsWith("file://"))w=w.replace(/^file:\/\//,"");if(w.startsWith("~")){let Y=Z.env.HOME||"";if(Y)w=w.replace(/^~(?=$|\/)/,Y)}if(oH(w)||w.startsWith("./")||w.startsWith("../"))w=eH(w);else return null;return LU(w)?w:null}catch{return null}}buildOutputTexts($){let w=this.shouldStyleConsole()?this.formatMarkdown($):$,Y=$.replace(this.ANSI_PATTERN,"");return{consoleText:w,fileText:Y}}async log($,w,...Y){if(!this.shouldLog($))return;let A=new Date,U=this.formatConsoleTimestamp(A),X=this.formatFileTimestamp(A),J,W;if(w instanceof Error)J=w.message,W=w.stack;else J=this.formatMessage(w,Y);let{consoleText:f,fileText:B}=this.buildOutputTexts(J);if(this.shouldStyleConsole()){let z=this.options.showIcons===!1?"":JN[$],G=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",F;switch($){case"debug":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:c.gray(f),level:$}),console.error(F);break;case"info":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"success":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:c.green(f),level:$}),console.error(F);break;case"warning":F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.warn(F);break;case"error":if(F=this.formatConsoleMessage({timestamp:U,icon:z,tag:G,message:f,level:$}),console.error(F),W){let T=W.split(`
173
+ `);for(let K of T)if(K.trim()&&!K.includes(J))console.error(this.formatConsoleMessage({timestamp:U,message:c.gray(` ${K}`),level:$,showTimestamp:!1}))}break}}else if(!M0()){if(console.error(`${X} ${this.environment}.${$.toUpperCase()}: ${J}`),W)console.error(W)}let j=`${X} ${this.environment}.${$.toUpperCase()}: ${B}
172
174
  `;if(W)j+=`${W}
173
- `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let A={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return A;let Y=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:Y,lastRenderedLine:""},this.shouldStyleConsole()&&!I0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!I0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!I0()&&x.stdout.isTTY)x.stdout.write(`
174
- `);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!I0()&&x.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let A=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",Y=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:Y,icon:this.options.showIcons===!1?"":v.blue("◐"),tag:A,message:`${v.cyan($)}...`}))}return async(A)=>{if(!this.enabled)return;let Y=performance.now(),X=Math.round(Y-w),J=`${$} completed in ${X}ms`,U=new Date,W=this.formatConsoleTimestamp(U),B=`${this.formatFileTimestamp(U)} ${this.environment}.INFO: ${J}`;if(A)B+=` ${JSON.stringify(A)}`;if(B+=`
175
- `,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}${A?` ${JSON.stringify(A)}`:""}`}))}else if(!I0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,A=new Ow(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(A),A}createReadStream(){if(I0())throw Error("createReadStream is not supported in browser environments");if(!MX(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return O2(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let A=this.keys.get(this.currentKeyId);try{let Y=n$.isBuffer($)?$:n$.from($,"base64"),X=Y.subarray(0,16),J=Y.subarray(Y.length-16),U=Y.subarray(16,Y.length-16),W=QH("aes-256-gcm",A,X);W.setAuthTag(J);let f=W.update(U),B=W.final(),j=f.length+B.length,z=n$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(Y){throw Error(`Decryption failed: ${Y instanceof Error?Y.message:String(Y)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return I0()}isServerMode(){return!I0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,A=this.formatConsoleTimestamp(w),Y=this.formatFileTimestamp(w),{consoleText:X,fileText:J}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=X.split(`
176
- `),f=Math.max(...W.map((E)=>E.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((E)=>{return this.formatConsoleMessage({timestamp:A,message:v.cyan(E),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:A,message:v.cyan(B),showTimestamp:!1})),z.forEach((E)=>console.error(E)),console.error(this.formatConsoleMessage({timestamp:A,message:v.cyan(j),showTimestamp:!1}))}else if(!I0())console.error(`${Y} ${this.environment}.INFO: [BOX] ${J}`);let U=`${Y} ${this.environment}.INFO: [BOX] ${J}
177
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(U)}async prompt($){if(I0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${v.cyan("?")} ${$} (y/n) `);let A=(Y)=>{let X=Y.toString().trim().toLowerCase();x.stdin.removeListener("data",A);try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!1)}catch{}x.stdin.pause(),console.error(""),w(X==="y"||X==="yes")};try{if(typeof x.stdin.setRawMode==="function")x.stdin.setRawMode(!0)}catch{}x.stdin.resume(),x.stdin.once("data",A)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let A=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(A=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let E=w[B++];switch(z){case"s":return String(E);case"d":case"i":return Number(E).toString();case"j":case"o":return JSON.stringify(E,null,2);default:return j}}),B<w.length)A+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:Y,fileText:X}=this.buildOutputTexts(A);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?v.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${v.blue("◐")} `;console.error(`${B}${f} ${v.cyan(Y)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${X}
178
- `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!x.stdout.isTTY)return;let A=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),Y=Math.round($.barLength*A/100),X=$.barLength-Y,J=v.green("━".repeat(Y)),U=v.gray("━".repeat(X)),W=`[${J}${U}]`,f=`${A}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||A===100?v.green("✓"):v.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${v.gray(this.formatTag(this.name))}`:"",E=`\r${j}${z} ${W} ${f}${B}`,F=x.stdout.columns||80,T=" ".repeat(Math.max(0,F-E.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${E}${T}`,x.stdout.write($.lastRenderedLine),w)x.stdout.write(`
179
- `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||I0()||!x.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(I0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await IX(this.config.logDirectory),A=[];for(let Y of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(Y):Y.startsWith(this.name))||!Y.endsWith(".log"))continue;let J=I1(this.config.logDirectory,Y);if($.before)try{if((await M1(J)).mtime>=$.before)continue}catch(U){console.error(`Failed to get stats for file ${J}:`,U);continue}A.push(J)}if(A.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${A.length} log file(s)...`);for(let Y of A)try{await yX(Y),console.warn(`Deleted log file: ${Y}`)}catch(X){console.error(`Failed to delete log file ${Y}:`,X)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var lT,pT=($)=>$,rT=($,w)=>{for(var A in w)lT($,A,{get:w[A],enumerable:!0,configurable:!0,set:tT.bind(w,A)})},aT=($,w)=>()=>($&&(w=$($=0)),w),P2,p2,C1,BA,t2,a7,s7,H2,hX,sU,x0,a,o7,N2,e7,R2,$H,wH,cU,AH,q2,M2,vU,YH,XH,JH,UH,VX,r2,fH,P0,WH,BH,I2,LX,oU,M0,u,jH,y2,zH,C2,FH,EH,mU,GH,h2,V2,KH,dU,TH,HH,NH,RH,qH,OX,a2,MH,IH="0.15.6",Y$,PX,fA,eU,$f,bX,wf,Af,WA,Yf,Xf,Ew,s2,o2,C$,r$,e2,$z,yH,LH,wz,iX,Fh,V0,v,yh,uH,Ch,iH,hh,Vh,Z2,Lh,cH,vH,Oh,x2,Qh,Sh,_h,kh,Dh,pU,mH,Zh;var Ff=F0(()=>{lT=Object.defineProperty;P2={};rT(P2,{withErrorRecovery:()=>v2,tryLoadConfig:()=>l7,loadConfigWithResult:()=>g7,loadConfig:()=>l2,isRetryableError:()=>u7,isConfigNotFoundError:()=>b7,isBunfigError:()=>m2,globalPerformanceMonitor:()=>BA,globalCache:()=>C1,getEnvOrDefault:()=>i7,generateConfigTypes:()=>p7,defaultGeneratedDir:()=>$z,defaultConfigDir:()=>e2,deepMergeWithArrayStrategy:()=>Bf,deepMerge:()=>d2,createLibraryConfig:()=>t7,config:()=>n7,bunfigPlugin:()=>r7,applyEnvVarsToConfig:()=>JA,TypeGenerationError:()=>Af,SchemaValidationError:()=>WA,PluginError:()=>Xf,PerformanceMonitor:()=>Uf,FileSystemError:()=>wf,ErrorFactory:()=>Ew,EnvVarError:()=>bX,EnvProcessor:()=>cX,ConfigValidator:()=>jf,ConfigValidationError:()=>eU,ConfigNotFoundError:()=>PX,ConfigMergeError:()=>$f,ConfigLoader:()=>zf,ConfigLoadError:()=>fA,ConfigFileLoader:()=>vX,ConfigCache:()=>Jf,CacheUtils:()=>t2,BunfigError:()=>Y$,BrowserConfigError:()=>Yf,ArrayMergeStrategies:()=>s2});yH=aT(async()=>{p2=import.meta.require,C1=new Jf,BA=new Uf,t2={createKey:C7,isEquivalent:h7,estimateMemoryUsage:V7},a7=_X(rU.cwd(),"config"),s7=_X(rU.cwd(),"src/generated"),H2=SX.env.CLARITY_LOG_DIR||A7(Q7(),"logs"),hX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:H2,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},sU=await S7(),x0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},a=x0,o7=x0.red,N2=x0.green,e7=x0.yellow,R2=x0.blue,$H=x0.magenta,wH=x0.cyan,cU=x0.white,AH=x0.gray,q2=x0.bgRed,M2=x0.bgYellow,vU=x0.bold,YH=x0.dim,XH=x0.italic,JH=x0.underline,UH=x0.reset,VX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},r2={debug:"\uD83D\uDD0D",info:R2("ℹ"),success:N2("✓"),warning:M2(cU(vU(" WARN "))),error:q2(cU(vU(" ERROR ")))},fH=new DX("stacks"),P0=new DX("bunfig",{showTags:!0}),WH=d0(UA.cwd(),"config"),BH=d0(UA.cwd(),"src/generated"),I2=QX.env.CLARITY_LOG_DIR||$7(Z7(),"logs"),LX={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:I2,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 x7(),M0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},u=M0,jH=M0.red,y2=M0.green,zH=M0.yellow,C2=M0.blue,FH=M0.magenta,EH=M0.cyan,mU=M0.white,GH=M0.gray,h2=M0.bgRed,V2=M0.bgYellow,KH=M0.bgGray,dU=M0.bold,TH=M0.dim,HH=M0.italic,NH=M0.underline,RH=M0.strikethrough,qH=M0.reset,OX={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},a2={debug:"\uD83D\uDD0D",info:C2("ℹ"),success:y2("✓"),warning:V2(mU(dU(" WARN "))),error:h2(mU(dU(" ERROR ")))},MH=new xX("stacks"),Y$=class extends Error{timestamp;context;constructor(w,A={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=A,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([A,Y])=>`${A}: ${Y}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},PX=class extends Y${code="CONFIG_NOT_FOUND";constructor(w,A,Y){let X=Y?` or alias "${Y}"`:"";super(`Configuration "${w}"${X} not found`,{configName:w,alias:Y,searchPaths:A,searchPathCount:A.length})}},fA=class extends Y${code="CONFIG_LOAD_ERROR";constructor(w,A,Y){super(`Failed to load configuration from "${w}": ${A.message}`,{configPath:w,configName:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},eU=class extends Y${code="CONFIG_VALIDATION_ERROR";constructor(w,A,Y){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},$f=class extends Y${code="CONFIG_MERGE_ERROR";constructor(w,A,Y,X){super(`Failed to merge configuration from "${w}" with "${A}": ${Y.message}`,{sourcePath:w,targetPath:A,configName:X,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},bX=class extends Y${code="ENV_VAR_ERROR";constructor(w,A,Y,X){super(`Failed to parse environment variable "${w}" with value "${A}" as ${Y}`,{envKey:w,envValue:A,expectedType:Y,configName:X})}},wf=class extends Y${code="FILE_SYSTEM_ERROR";constructor(w,A,Y){super(`File system ${w} failed for "${A}": ${Y.message}`,{operation:w,path:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Af=class extends Y${code="TYPE_GENERATION_ERROR";constructor(w,A,Y){super(`Failed to generate types from "${w}" to "${A}": ${Y.message}`,{configDir:w,outputPath:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},WA=class extends Y${code="SCHEMA_VALIDATION_ERROR";constructor(w,A,Y){super(`Schema validation failed${Y?` for config "${Y}"`:""}`,{schemaPath:w,configName:Y,validationErrors:A,errorCount:A.length})}},Yf=class extends Y${code="BROWSER_CONFIG_ERROR";constructor(w,A,Y,X){super(`Failed to fetch configuration from "${w}": ${A} ${Y}`,{endpoint:w,status:A,statusText:Y,configName:X})}},Xf=class extends Y${code="PLUGIN_ERROR";constructor(w,A,Y){super(`Plugin "${w}" failed during ${A}: ${Y.message}`,{pluginName:w,operation:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},Ew={configNotFound($,w,A){return new PX($,w,A)},configLoad($,w,A){return new fA($,w,A)},configValidation($,w,A){return new eU($,w,A)},configMerge($,w,A,Y){return new $f($,w,A,Y)},envVar($,w,A,Y){return new bX($,w,A,Y)},fileSystem($,w,A){return new wf($,w,A)},typeGeneration($,w,A){return new Af($,w,A)},schemaValidation($,w,A){return new WA($,w,A)},browserConfig($,w,A,Y){return new Yf($,w,A,Y)},plugin($,w,A){return new Xf($,w,A)}},s2={replace:"replace",concat:"concat",smart:"smart"},o2=/^https?:\/\//,C$=new xX("bunfig",{showTags:!0}),r$=new zf,e2=g0(Lw.cwd(),"config"),$z=g0(Lw.cwd(),"src/generated")});LH=uX.env.CLARITY_LOG_DIR||CH(VH(),"logs"),wz={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:LH,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},iX={...wz},Fh=(async()=>{try{let{loadConfig:$}=await yH().then(()=>P2),w=await $({name:"clarity",alias:"logging",defaultConfig:wz,cwd:uX.cwd()});if(w)Object.assign(iX,w)}catch{}return iX})();V0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},v=V0,yh=V0.red,uH=V0.green,Ch=V0.yellow,iH=V0.blue,hh=V0.magenta,Vh=V0.cyan,Z2=V0.white,Lh=V0.gray,cH=V0.bgRed,vH=V0.bgYellow,Oh=V0.bgGray,x2=V0.bold,Qh=V0.dim,Sh=V0.italic,_h=V0.underline,kh=V0.strikethrough,Dh=V0.reset,pU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},mH={debug:"\uD83D\uDD0D",info:iH("ℹ"),success:uH("✓"),warning:vH(Z2(x2(" WARN "))),error:cH(Z2(x2(" ERROR ")))};Zh=new Ow("stacks")});var h1={};BW(h1,{shouldReusePort:()=>Sw,safeStringify:()=>E$,safeDeleteFile:()=>Tf,resolvePathRewrite:()=>Kf,redactSensitive:()=>mX,isValidRootCA:()=>Gf,isSingleProxyOptions:()=>zA,isSingleProxyConfig:()=>tH,isProcessElevated:()=>dX,isMultiProxyOptions:()=>_w,isMultiProxyConfig:()=>Jz,getSudoPassword:()=>Qw,getPrimaryDomain:()=>gX,extractHostname:()=>pH,execSudoSync:()=>jA,debugLog:()=>G});import{execSync as Ef}from"node:child_process";import*as Xz from"node:fs/promises";function Qw(){return process.env.SUDO_PASSWORD}function dX(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function jA($){if(dX())return Ef($,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let w=Qw(),A=$.replace(/'/g,"'\\''");if(w)return Ef(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return Ef(`sudo -n sh -c '${A}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function G($,w,A){if(A)dH.debug(`[rpx:${$}] ${w}`)}function Sw(){let $=process.env.RPX_REUSE_PORT;return $==="1"||$==="true"}function lH($){let w=$.toLowerCase();return gH.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function mX($){if(Array.isArray($))return $.map((A)=>mX(A));if(typeof $==="string")return nH.test($)?Yz:$;if(!$||typeof $!=="object")return $;let w={};for(let[A,Y]of Object.entries($)){if(lH(A)){w[A]=Yz;continue}w[A]=mX(Y)}return w}function E$($,w){return JSON.stringify(mX($),null,w)}function pH($){if(_w($))return $.proxies.map((w)=>{let A=w.to||"stacks.localhost";return A.startsWith("http")?new URL(A).hostname:A});if(zA($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function Gf($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function gX($){if(!$)return"stacks.localhost";if(_w($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(zA($))return $.to||"stacks.localhost";return"stacks.localhost"}function Jz($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function _w($){return"proxies"in $&&Array.isArray($.proxies)}function zA($){return"to"in $&&typeof $.to==="string"}function tH($){return!!($&&("to"in $)&&!("proxies"in $))}function Kf($,w){if(!w||w.length===0)return null;for(let A of w)if($===A.from||$.startsWith(`${A.from}/`)){let Y=A.to.startsWith("http")?new URL(A.to).host:A.to,X=A.stripPrefix===!0?$.slice(A.from.length)||"/":$;return{targetHost:Y,targetPath:X}}return null}async function Tf($,w){try{await Xz.unlink($),G("certificates",`Successfully deleted: ${$}`,w)}catch(A){if(A.code!=="ENOENT")G("certificates",`Warning: Could not delete ${$}: ${A}`,w)}}var dH,Yz="[redacted]",gH,nH;var f0=F0(()=>{Ff();dH=new Ow("rpx",{showTags:!1});gH=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),nH=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as nX}from"node:child_process";import{homedir as rH}from"node:os";import{join as aH}from"node:path";function lX(){return aH(rH(),"Library/Keychains/login.keychain-db")}function Nf(){return[L1,lX()]}function Uz($,w=Hf){let A=nX(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),Y=[];for(let X of A.split(`
180
- `)){let J=X.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(J)Y.push(J[1].toUpperCase())}return Y}function Rf($){if(process.platform!=="darwin")return;let w=zX($.caPath);if(!w)return;let A=$.commonName??Hf,Y=$.keychains??Nf();for(let X of Y)for(let J of Uz(X,A)){if(J===w)continue;try{if(X.startsWith("/Library"))jA(`security delete-certificate -Z ${J} "${X}"`);else nX(`security delete-certificate -Z ${J} "${X}"`,{stdio:"ignore"});G("ssl",`Removed stale Root CA ${J} from ${X}`,$.verbose)}catch{}}}function qf($,w,A){if(process.platform!=="darwin")return pX($,A);try{let X=nX(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return G("ssl",`verify-cert ${w}: ${X?"trusted":"not trusted"}`,A?.verbose),X}catch{return!1}}function pX($,w){let A=zX($);if(!A)return!1;for(let Y of Nf())try{let X=nX(`security find-certificate -a -Z "${Y}" 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()===A)return G("ssl",`Root CA fingerprint found in ${Y}`,w?.verbose),!0}}catch{}return!1}var V1="-d -r trustRoot -p ssl -p basic",L1="/Library/Keychains/System.keychain",Hf="rpx.localhost";var Mf=F0(()=>{QU();f0()});import{execSync as O1}from"node:child_process";import y0 from"node:fs/promises";import*as If from"node:os";import{homedir as Q1}from"node:os";import{join as E0}from"node:path";import*as Gw from"node:process";function yf($,w){return[...new Set($.filter(Boolean))].map((A)=>({serverName:A,cert:w.cert,key:w.key}))}function Cf($,w,A){let Y=E0(Q1(),".stacks","ssl"),X=[...new Set([w,...$,"rpx.localhost"])];return{https:{certPath:tX,keyPath:E0(Y,"rpx.localhost.key"),caCertPath:E0(Y,"rpx.localhost.ca.crt"),commonName:w},verbose:A,regenerateUntrustedCerts:!0,proxies:X.map((J)=>({from:"localhost:1",to:J,cleanUrls:!1}))}}function Bz($){return{caCertPath:E0($,oH),caKeyPath:E0($,eH)}}async function $N($,w){try{let[A,Y]=await Promise.all([y0.readFile($.caCertPath,"utf8"),y0.readFile($.caKeyPath,"utf8")]);if(!A.includes("-----BEGIN CERTIFICATE-----")||!Y.includes("PRIVATE KEY-----"))return G("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:A,privateKey:Y}}catch(A){return G("ssl",`No existing Root CA at ${$.caCertPath} (${A.code||A}), will create one`,w),null}}function fz($){let w=new Set;w.add($);let A=$.split(".");if(A.length>=2)w.add(`*.${A.slice(1).join(".")}`);return Array.from(w)}function jz($){let A=gX($).replace(/\*/g,"wildcard"),Y=E0(Q1(),".stacks","ssl"),X=Y;if(typeof $?.https==="object")return X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:Y,{caCertPath:$.https.caCertPath||E0(X,`${A}.ca.crt`),certPath:$.https.certPath||E0(X,`${A}.crt`),keyPath:$.https.keyPath||E0(X,`${A}.key`)};return{caCertPath:E0(X,`${A}.ca.crt`),certPath:E0(X,`${A}.crt`),keyPath:E0(X,`${A}.key`)}}function Wz($){let w=new Set;if(_w($))$.proxies.forEach((A)=>{let Y=A.to||"rpx.localhost";fz(Y).forEach((X)=>w.add(X))});else if(zA($)){let A=$.to||"rpx.localhost";fz(A).forEach((Y)=>w.add(Y))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function S1($){if(Kw&&!$.forceRegenerate){G("ssl","Using cached SSL configuration",$.verbose);return}rX();let w=_w($)?$.proxies.map((j)=>j.to):[$.to];G("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let A=FA($,$.verbose),Y=A.basePath||E0(Q1(),".stacks","ssl");await y0.mkdir(Y,{recursive:!0});let X=Bz(Y),J=await $N(X,$.verbose),U=!1;if(!J){if($.verbose)q.info("Generating Root CA certificate (one-time)...");J=await MU(A);try{await Promise.all([y0.writeFile(X.caCertPath,J.certificate),y0.writeFile(X.caKeyPath,J.privateKey,{mode:384})]),U=!0,G("ssl",`Persisted Root CA at ${X.caCertPath}`,$.verbose)}catch(j){throw G("ssl",`Error saving Root CA files: ${j}`,$.verbose),Error(`Failed to save Root CA files: ${j}`)}}else G("ssl",`Reusing existing Root CA from ${X.caCertPath}`,$.verbose);if($.verbose)q.info(`Generating host certificate for: ${w.join(", ")}`);let W=await IU({...A,rootCA:{certificate:J.certificate,privateKey:J.privateKey}});try{await Promise.all([y0.writeFile(A.certPath,W.certificate),y0.writeFile(A.keyPath,W.privateKey),y0.writeFile(A.caCertPath,J.certificate)]),G("ssl","Certificate files saved successfully",$.verbose)}catch(j){throw G("ssl",`Error saving certificate files: ${j}`,$.verbose),Error(`Failed to save certificate files: ${j}`)}if(U?!1:await Fz(X.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(G("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)q.success("Root CA is already trusted in system trust store");if(Kw={key:W.privateKey,cert:W.certificate,ca:J.certificate},$.verbose)q.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)q.info("Adding certificate to system trust store (may require sudo permission)...");let B=!1;if(Gw.platform==="darwin")try{Rf({caPath:X.caCertPath,verbose:$.verbose});let j=lX();try{O1(`security add-trusted-cert ${V1} -k "${j}" "${X.caCertPath}"`,{stdio:"ignore"})}catch{}if(jA(`security add-trusted-cert ${V1} -k ${L1} "${X.caCertPath}"`),$.verbose)q.success("Successfully added Root CA to system trust store");B=!0;let z=E0(Y,"trust-rpx-cert.sh"),E=`#!/bin/bash
175
+ `;if(j=j.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(j)}progress($,w=""){let Y={update:(W,f)=>{},finish:(W)=>{},interrupt:(W,f)=>{}};if(!this.enabled)return Y;let A=30;if(this.activeProgressBar={total:Math.max(1,$||1),current:0,message:w||"",barLength:A,lastRenderedLine:""},this.shouldStyleConsole()&&!M0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(W,f)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,W),this.activeProgressBar.total),f!==void 0)this.activeProgressBar.message=f;if(this.shouldStyleConsole()&&!M0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(W)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,W)},interrupt:(W,f="info")=>{if(!M0()&&Z.stdout.isTTY)Z.stdout.write(`
176
+ `);if(this[f==="warning"?"warn":f](W),this.activeProgressBar&&this.shouldStyleConsole()&&!M0()&&Z.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)}}}time($){let w=performance.now();if(this.shouldStyleConsole()){let Y=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",A=this.formatConsoleTimestamp(new Date);console.error(this.formatConsoleMessage({timestamp:A,icon:this.options.showIcons===!1?"":c.blue("◐"),tag:Y,message:`${c.cyan($)}...`}))}return async(Y)=>{if(!this.enabled)return;let A=performance.now(),U=Math.round(A-w),X=`${$} completed in ${U}ms`,J=new Date,W=this.formatConsoleTimestamp(J),B=`${this.formatFileTimestamp(J)} ${this.environment}.INFO: ${X}`;if(Y)B+=` ${JSON.stringify(Y)}`;if(B+=`
177
+ `,B=B.replace(this.ANSI_PATTERN,""),this.shouldStyleConsole()){let j=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"";console.error(this.formatConsoleMessage({timestamp:W,icon:this.options.showIcons===!1?"":c.green("✓"),tag:j,message:`${X}${Y?` ${JSON.stringify(Y)}`:""}`}))}else if(!M0())console.error(B.trim());if(this.shouldWriteToFile())await this.writeToFile(B)}}async debug($,...w){await this.log("debug",$,...w)}async info($,...w){await this.log("info",$,...w)}async success($,...w){await this.log("success",$,...w)}async warn($,...w){await this.log("warning",$,...w)}async error($,...w){await this.log("error",$,...w)}validateEncryptionConfig(){if(!this.config.rotation)return!1;if(typeof this.config.rotation==="boolean")return!1;let $=this.config.rotation,{encrypt:w}=$;return!!w}async only($){if(!this.enabled)return;return await $()}isEnabled(){return this.enabled}setEnabled($){this.enabled=$}extend($){let w=`${this.name}:${$}`,Y=new Ow(w,{...this.options,logDirectory:this.config.logDirectory,level:this.config.level,format:this.config.format,rotation:typeof this.config.rotation==="boolean"?void 0:this.config.rotation,timestamp:typeof this.config.timestamp==="boolean"?void 0:this.config.timestamp});return this.subLoggers.add(Y),Y}createReadStream(){if(M0())throw Error("createReadStream is not supported in browser environments");if(!LU(this.currentLogFile))throw Error(`Log file does not exist: ${this.currentLogFile}`);return b9(this.currentLogFile,{encoding:"utf8"})}async decrypt($){if(!this.validateEncryptionConfig())throw Error("Encryption is not configured");let w=this.config.rotation;if(!w.encrypt||typeof w.encrypt==="boolean")throw Error("Invalid encryption configuration");if(!this.currentKeyId||!this.keys.has(this.currentKeyId))throw Error("No valid encryption key available");let Y=this.keys.get(this.currentKeyId);try{let A=l$.isBuffer($)?$:l$.from($,"base64"),U=A.subarray(0,16),X=A.subarray(A.length-16),J=A.subarray(16,A.length-16),W=pH("aes-256-gcm",Y,U);W.setAuthTag(X);let f=W.update(J),B=W.final(),j=f.length+B.length,z=l$.allocUnsafe(j);return f.copy(z,0),B.copy(z,f.length),z.toString("utf8")}catch(A){throw Error(`Decryption failed: ${A instanceof Error?A.message:String(A)}`)}}getLevel(){return this.config.level}getLogDirectory(){return this.config.logDirectory}getFormat(){return this.config.format}getRotationConfig(){return this.config.rotation}isBrowserMode(){return M0()}isServerMode(){return!M0()}setTestEncryptionKey($,w){this.currentKeyId=$,this.keys.set($,w)}getTestCurrentKey(){if(!this.currentKeyId||!this.keys.has(this.currentKeyId))return null;return{id:this.currentKeyId,key:this.keys.get(this.currentKeyId)}}getConfig(){return this.config}async box($){if(!this.enabled)return;let w=new Date,Y=this.formatConsoleTimestamp(w),A=this.formatFileTimestamp(w),{consoleText:U,fileText:X}=this.buildOutputTexts($);if(this.shouldStyleConsole()){let W=U.split(`
178
+ `),f=Math.max(...W.map((G)=>G.length))+2,B=`┌${"─".repeat(f)}┐`,j=`└${"─".repeat(f)}┘`,z=W.map((G)=>{return this.formatConsoleMessage({timestamp:Y,message:c.cyan(G),showTimestamp:!1})});console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(B),showTimestamp:!1})),z.forEach((G)=>console.error(G)),console.error(this.formatConsoleMessage({timestamp:Y,message:c.cyan(j),showTimestamp:!1}))}else if(!M0())console.error(`${A} ${this.environment}.INFO: [BOX] ${X}`);let J=`${A} ${this.environment}.INFO: [BOX] ${X}
179
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(J)}async prompt($){if(M0())return Promise.resolve(!0);return new Promise((w)=>{console.error(`${c.cyan("?")} ${$} (y/n) `);let Y=(A)=>{let U=A.toString().trim().toLowerCase();Z.stdin.removeListener("data",Y);try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!1)}catch{}Z.stdin.pause(),console.error(""),w(U==="y"||U==="yes")};try{if(typeof Z.stdin.setRawMode==="function")Z.stdin.setRawMode(!0)}catch{}Z.stdin.resume(),Z.stdin.once("data",Y)})}setFancy($){this.fancy=$}isFancy(){return this.fancy}pause(){this.enabled=!1}resume(){this.enabled=!0}async start($,...w){if(!this.enabled)return;let Y=$;if(w&&w.length>0){let f=/%([sdijfo%])/g,B=0;if(Y=$.replace(f,(j,z)=>{if(z==="%")return"%";if(B>=w.length)return j;let G=w[B++];switch(z){case"s":return String(G);case"d":case"i":return Number(G).toString();case"j":case"o":return JSON.stringify(G,null,2);default:return j}}),B<w.length)Y+=` ${w.slice(B).map((j)=>typeof j==="object"?JSON.stringify(j,null,2):String(j)).join(" ")}`}let{consoleText:A,fileText:U}=this.buildOutputTexts(Y);if(this.shouldStyleConsole()){let f=this.options.showTags!==!1&&this.name?c.gray(this.formatTag(this.name)):"",B=this.options.showIcons===!1?"":`${c.blue("◐")} `;console.error(`${B}${f} ${c.cyan(A)}`)}let W=`[${new Date().toISOString()}] ${this.environment}.INFO: [START] ${U}
180
+ `.replace(this.ANSI_PATTERN,"");if(this.shouldWriteToFile())await this.writeToFile(W)}renderProgressBar($,w=!1){if(!this.enabled||!this.shouldStyleConsole()||!Z.stdout.isTTY)return;let Y=Math.min(100,Math.max(0,Math.round($.current/$.total*100))),A=Math.round($.barLength*Y/100),U=$.barLength-A,X=c.green("━".repeat(A)),J=c.gray("━".repeat(U)),W=`[${X}${J}]`,f=`${Y}%`.padStart(4),B=$.message?` ${$.message}`:"",j=this.options.showIcons===!1?"":w||Y===100?c.green("✓"):c.blue("▶"),z=this.options.showTags!==!1&&this.name?` ${c.gray(this.formatTag(this.name))}`:"",G=`\r${j}${z} ${W} ${f}${B}`,F=Z.stdout.columns||80,T=" ".repeat(Math.max(0,F-G.replace(this.ANSI_PATTERN,"").length));if($.lastRenderedLine=`${G}${T}`,Z.stdout.write($.lastRenderedLine),w)Z.stdout.write(`
181
+ `)}finishProgressBar($,w){if(!this.enabled||!this.fancy||M0()||!Z.stdout.isTTY){this.activeProgressBar=null;return}if($.current<$.total)$.current=$.total;if(w)$.message=w;this.renderProgressBar($,!0),this.activeProgressBar=null}async clear($={}){if(M0()){console.warn("Log clearing is not supported in browser environments.");return}try{console.warn("Clearing logs...",this.config.logDirectory);let w=await QU(this.config.logDirectory),Y=[];for(let A of w){if(!($.name?new RegExp($.name.replace("*",".*")).test(A):A.startsWith(this.name))||!A.endsWith(".log"))continue;let X=M1(this.config.logDirectory,A);if($.before)try{if((await R1(X)).mtime>=$.before)continue}catch(J){console.error(`Failed to get stats for file ${X}:`,J);continue}Y.push(X)}if(Y.length===0){console.warn("No log files matched the criteria for clearing.");return}console.warn(`Preparing to delete ${Y.length} log file(s)...`);for(let A of Y)try{await OU(A),console.warn(`Deleted log file: ${A}`)}catch(U){console.error(`Failed to delete log file ${A}:`,U)}console.warn("Log clearing process finished.")}catch(w){console.error("Error during log clearing process:",w)}}}var jT,zT=($)=>$,GT=($,w)=>{for(var Y in w)jT($,Y,{get:w[Y],enumerable:!0,configurable:!0,set:FT.bind(w,Y)})},ET=($,w)=>()=>($&&(w=$($=0)),w),l9,Y2,y1,GY,A2,EH,KH,V9,_U,Wf,D0,s,TH,L9,HH,Q9,NH,qH,sJ,RH,O9,S9,oJ,MH,IH,yH,CH,kU,U2,hH,Z0,VH,LH,_9,DU,Bf,R0,b,QH,k9,OH,D9,SH,_H,eJ,kH,Z9,x9,DH,$f,ZH,xH,PH,bH,uH,ZU,X2,iH,cH="0.15.6",$$,mU,zY,jf,zf,dU,Ff,Gf,FY,Ef,Kf,Gw,J2,f2,q$,r$,W2,B2,vH,lH,j2,lU,kh,C0,c,dh,YN,gh,AN,lh,nh,d9,ph,UN,XN,th,g9,rh,ah,sh,oh,eh,Uf,JN,$V;var yf=j0(()=>{jT=Object.defineProperty;l9={};GT(l9,{withErrorRecovery:()=>a9,tryLoadConfig:()=>jH,loadConfigWithResult:()=>WH,loadConfig:()=>w2,isRetryableError:()=>YH,isConfigNotFoundError:()=>wH,isBunfigError:()=>s9,globalPerformanceMonitor:()=>GY,globalCache:()=>y1,getEnvOrDefault:()=>AH,generateConfigTypes:()=>zH,defaultGeneratedDir:()=>B2,defaultConfigDir:()=>W2,deepMergeWithArrayStrategy:()=>Rf,deepMerge:()=>o9,createLibraryConfig:()=>FH,config:()=>BH,bunfigPlugin:()=>GH,applyEnvVarsToConfig:()=>BY,TypeGenerationError:()=>Gf,SchemaValidationError:()=>FY,PluginError:()=>Kf,PerformanceMonitor:()=>Hf,FileSystemError:()=>Ff,ErrorFactory:()=>Gw,EnvVarError:()=>dU,EnvProcessor:()=>nU,ConfigValidator:()=>Mf,ConfigValidationError:()=>jf,ConfigNotFoundError:()=>mU,ConfigMergeError:()=>zf,ConfigLoader:()=>If,ConfigLoadError:()=>zY,ConfigFileLoader:()=>pU,ConfigCache:()=>Tf,CacheUtils:()=>A2,BunfigError:()=>$$,BrowserConfigError:()=>Ef,ArrayMergeStrategies:()=>J2});vH=ET(async()=>{Y2=import.meta.require,y1=new Tf,GY=new Hf,A2={createKey:mT,isEquivalent:dT,estimateMemoryUsage:gT},EH=bU(Jf.cwd(),"config"),KH=bU(Jf.cwd(),"src/generated"),V9=PU.env.CLARITY_LOG_DIR||RT(pT(),"logs"),_U={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:V9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1},Wf=await tT(),D0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,reset:"\x1B[0m"},s=D0,TH=D0.red,L9=D0.green,HH=D0.yellow,Q9=D0.blue,NH=D0.magenta,qH=D0.cyan,sJ=D0.white,RH=D0.gray,O9=D0.bgRed,S9=D0.bgYellow,oJ=D0.bold,MH=D0.dim,IH=D0.italic,yH=D0.underline,CH=D0.reset,kU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},U2={debug:"\uD83D\uDD0D",info:Q9("ℹ"),success:L9("✓"),warning:S9(sJ(oJ(" WARN "))),error:O9(sJ(oJ(" ERROR ")))},hH=new iU("stacks"),Z0=new iU("bunfig",{showTags:!0}),VH=m0(jY.cwd(),"config"),LH=m0(jY.cwd(),"src/generated"),_9=xU.env.CLARITY_LOG_DIR||NT(oT(),"logs"),DU={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:_9,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},Bf=await eT(),R0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},b=R0,QH=R0.red,k9=R0.green,OH=R0.yellow,D9=R0.blue,SH=R0.magenta,_H=R0.cyan,eJ=R0.white,kH=R0.gray,Z9=R0.bgRed,x9=R0.bgYellow,DH=R0.bgGray,$f=R0.bold,ZH=R0.dim,xH=R0.italic,PH=R0.underline,bH=R0.strikethrough,uH=R0.reset,ZU={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},X2={debug:"\uD83D\uDD0D",info:D9("ℹ"),success:k9("✓"),warning:x9(eJ($f(" WARN "))),error:Z9(eJ($f(" ERROR ")))},iH=new vU("stacks"),$$=class extends Error{timestamp;context;constructor(w,Y={}){super(w);if(this.name=this.constructor.name,this.timestamp=new Date,this.context=Y,Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}toJSON(){return{name:this.name,code:this.code,message:this.message,timestamp:this.timestamp.toISOString(),context:this.context,stack:this.stack}}toString(){let w=Object.keys(this.context).length>0?` (${Object.entries(this.context).map(([Y,A])=>`${Y}: ${A}`).join(", ")})`:"";return`${this.name} [${this.code}]: ${this.message}${w}`}},mU=class extends $${code="CONFIG_NOT_FOUND";constructor(w,Y,A){let U=A?` or alias "${A}"`:"";super(`Configuration "${w}"${U} not found`,{configName:w,alias:A,searchPaths:Y,searchPathCount:Y.length})}},zY=class extends $${code="CONFIG_LOAD_ERROR";constructor(w,Y,A){super(`Failed to load configuration from "${w}": ${Y.message}`,{configPath:w,configName:A,originalError:Y.name,originalMessage:Y.message});this.cause=Y}},jf=class extends $${code="CONFIG_VALIDATION_ERROR";constructor(w,Y,A){super(`Configuration validation failed for "${w}"`,{configPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},zf=class extends $${code="CONFIG_MERGE_ERROR";constructor(w,Y,A,U){super(`Failed to merge configuration from "${w}" with "${Y}": ${A.message}`,{sourcePath:w,targetPath:Y,configName:U,originalError:A.name,originalMessage:A.message});this.cause=A}},dU=class extends $${code="ENV_VAR_ERROR";constructor(w,Y,A,U){super(`Failed to parse environment variable "${w}" with value "${Y}" as ${A}`,{envKey:w,envValue:Y,expectedType:A,configName:U})}},Ff=class extends $${code="FILE_SYSTEM_ERROR";constructor(w,Y,A){super(`File system ${w} failed for "${Y}": ${A.message}`,{operation:w,path:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Gf=class extends $${code="TYPE_GENERATION_ERROR";constructor(w,Y,A){super(`Failed to generate types from "${w}" to "${Y}": ${A.message}`,{configDir:w,outputPath:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},FY=class extends $${code="SCHEMA_VALIDATION_ERROR";constructor(w,Y,A){super(`Schema validation failed${A?` for config "${A}"`:""}`,{schemaPath:w,configName:A,validationErrors:Y,errorCount:Y.length})}},Ef=class extends $${code="BROWSER_CONFIG_ERROR";constructor(w,Y,A,U){super(`Failed to fetch configuration from "${w}": ${Y} ${A}`,{endpoint:w,status:Y,statusText:A,configName:U})}},Kf=class extends $${code="PLUGIN_ERROR";constructor(w,Y,A){super(`Plugin "${w}" failed during ${Y}: ${A.message}`,{pluginName:w,operation:Y,originalError:A.name,originalMessage:A.message});this.cause=A}},Gw={configNotFound($,w,Y){return new mU($,w,Y)},configLoad($,w,Y){return new zY($,w,Y)},configValidation($,w,Y){return new jf($,w,Y)},configMerge($,w,Y,A){return new zf($,w,Y,A)},envVar($,w,Y,A){return new dU($,w,Y,A)},fileSystem($,w,Y){return new Ff($,w,Y)},typeGeneration($,w,Y){return new Gf($,w,Y)},schemaValidation($,w,Y){return new FY($,w,Y)},browserConfig($,w,Y,A){return new Ef($,w,Y,A)},plugin($,w,Y){return new Kf($,w,Y)}},J2={replace:"replace",concat:"concat",smart:"smart"},f2=/^https?:\/\//,q$=new vU("bunfig",{showTags:!0}),r$=new If,W2=d0(Qw.cwd(),"config"),B2=d0(Qw.cwd(),"src/generated")});lH=gU.env.CLARITY_LOG_DIR||mH(gH(),"logs"),j2={level:"info",defaultName:"clarity",timestamp:!0,colors:!0,format:"text",maxLogSize:10485760,logDatePattern:"YYYY-MM-DD",logDirectory:lH,rotation:{frequency:"daily",maxSize:10485760,maxFiles:5,compress:!1,rotateHour:0,rotateMinute:0,rotateDayOfWeek:0,rotateDayOfMonth:1,encrypt:!1},verbose:!1,writeToFile:!1},lU={...j2},kh=(async()=>{try{let{loadConfig:$}=await vH().then(()=>l9),w=await $({name:"clarity",alias:"logging",defaultConfig:j2,cwd:gU.cwd()});if(w)Object.assign(lU,w)}catch{}return lU})();C0={red:($)=>`\x1B[31m${$}\x1B[0m`,green:($)=>`\x1B[32m${$}\x1B[0m`,yellow:($)=>`\x1B[33m${$}\x1B[0m`,blue:($)=>`\x1B[34m${$}\x1B[0m`,magenta:($)=>`\x1B[35m${$}\x1B[0m`,cyan:($)=>`\x1B[36m${$}\x1B[0m`,white:($)=>`\x1B[37m${$}\x1B[0m`,gray:($)=>`\x1B[90m${$}\x1B[0m`,bgRed:($)=>`\x1B[41m${$}\x1B[0m`,bgYellow:($)=>`\x1B[43m${$}\x1B[0m`,bgGray:($)=>`\x1B[100m${$}\x1B[0m`,bold:($)=>`\x1B[1m${$}\x1B[0m`,dim:($)=>`\x1B[2m${$}\x1B[0m`,italic:($)=>`\x1B[3m${$}\x1B[0m`,underline:($)=>`\x1B[4m${$}\x1B[0m`,strikethrough:($)=>`\x1B[9m${$}\x1B[0m`,reset:"\x1B[0m"},c=C0,dh=C0.red,YN=C0.green,gh=C0.yellow,AN=C0.blue,lh=C0.magenta,nh=C0.cyan,d9=C0.white,ph=C0.gray,UN=C0.bgRed,XN=C0.bgYellow,th=C0.bgGray,g9=C0.bold,rh=C0.dim,ah=C0.italic,sh=C0.underline,oh=C0.strikethrough,eh=C0.reset,Uf={activationLevel:"error",bufferSize:50,flushOnDeactivation:!0,stopBuffering:!1},JN={debug:"\uD83D\uDD0D",info:AN("ℹ"),success:YN("✓"),warning:XN(d9(g9(" WARN "))),error:UN(d9(g9(" ERROR ")))};$V=new Ow("stacks")});var h1={};RW(h1,{shouldReusePort:()=>C1,safeStringify:()=>R$,safeDeleteFile:()=>Lf,resolvePathRewrite:()=>Vf,redactSensitive:()=>tU,isValidRootCA:()=>hf,isSingleProxyOptions:()=>KY,isSingleProxyConfig:()=>FN,isProcessElevated:()=>rU,isMultiProxyOptions:()=>_w,isMultiProxyConfig:()=>E2,getSudoPassword:()=>Sw,getPrimaryDomain:()=>aU,extractHostname:()=>zN,execSudoSync:()=>EY,debugLog:()=>E});import{execSync as Cf}from"node:child_process";import*as G2 from"node:fs/promises";function Sw(){return process.env.SUDO_PASSWORD}function rU(){if(process.platform==="win32")return!1;try{return typeof process.getuid==="function"&&process.getuid()===0}catch{return!1}}function EY($){if(rU())return Cf($,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});let w=Sw(),Y=$.replace(/'/g,"'\\''");if(w)return Cf(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]});try{return Cf(`sudo -n sh -c '${Y}'`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}function E($,w,Y){if(Y)fN.debug(`[rpx:${$}] ${w}`)}function C1(){let $=process.env.RPX_REUSE_PORT;return $==="1"||$==="true"}function jN($){let w=$.toLowerCase();return WN.has(w)||w.endsWith("password")||w.includes("secret")||w.includes("token")}function tU($){if(Array.isArray($))return $.map((Y)=>tU(Y));if(typeof $==="string")return BN.test($)?F2:$;if(!$||typeof $!=="object")return $;let w={};for(let[Y,A]of Object.entries($)){if(jN(Y)){w[Y]=F2;continue}w[Y]=tU(A)}return w}function R$($,w){return JSON.stringify(tU($),null,w)}function zN($){if(_w($))return $.proxies.map((w)=>{let Y=w.to||"stacks.localhost";return Y.startsWith("http")?new URL(Y).hostname:Y});if(KY($)){let w=$.to||"stacks.localhost";return[w.startsWith("http")?new URL(w).hostname:w]}return["stacks.localhost"]}function hf($){return typeof $==="object"&&$!==null&&"certificate"in $&&"privateKey"in $&&typeof $.certificate==="string"&&typeof $.privateKey==="string"}function aU($){if(!$)return"stacks.localhost";if(_w($)&&$.proxies.length>0)return $.proxies[0].to||"stacks.localhost";if(KY($))return $.to||"stacks.localhost";return"stacks.localhost"}function E2($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}function _w($){return"proxies"in $&&Array.isArray($.proxies)}function KY($){return"to"in $&&typeof $.to==="string"}function FN($){return!!($&&("to"in $)&&!("proxies"in $))}function Vf($,w){if(!w||w.length===0)return null;for(let Y of w)if($===Y.from||$.startsWith(`${Y.from}/`)){let A=Y.to.startsWith("http")?new URL(Y.to).host:Y.to,U=Y.stripPrefix===!0?$.slice(Y.from.length)||"/":$;return{targetHost:A,targetPath:U}}return null}async function Lf($,w){try{await G2.unlink($),E("certificates",`Successfully deleted: ${$}`,w)}catch(Y){if(Y.code!=="ENOENT")E("certificates",`Warning: Could not delete ${$}: ${Y}`,w)}}var fN,F2="[redacted]",WN,BN;var f0=j0(()=>{yf();fN=new Ow("rpx",{showTags:!1});WN=new Set(["certificate","privatekey","key","cert","ca","rootca","password","sudo_password"]),BN=/-----BEGIN [A-Z ]+-----[\s\S]*?-----END [A-Z ]+-----/});import{execSync as sU}from"node:child_process";import{homedir as GN}from"node:os";import{join as EN}from"node:path";function oU(){return EN(GN(),"Library/Keychains/login.keychain-db")}function Of(){return[L1,oU()]}function K2($,w=Qf){let Y=sU(`security find-certificate -a -c "${w}" -Z "${$}" 2>/dev/null || true`,{encoding:"utf8"}),A=[];for(let U of Y.split(`
182
+ `)){let X=U.match(/SHA-256 hash:\s*([A-F0-9]+)/i);if(X)A.push(X[1].toUpperCase())}return A}function Sf($){if(process.platform!=="darwin")return;let w=Lw($.caPath);if(!w)return;let Y=$.commonName??Qf,A=$.keychains??Of();for(let U of A)for(let X of K2(U,Y)){if(X===w)continue;try{if(U.startsWith("/Library"))EY(`security delete-certificate -Z ${X} "${U}"`);else sU(`security delete-certificate -Z ${X} "${U}"`,{stdio:"ignore"});E("ssl",`Removed stale Root CA ${X} from ${U}`,$.verbose)}catch{}}}function _f($,w,Y){if(process.platform!=="darwin")return eU($,Y);try{let U=sU(`security verify-cert -c "${$}" -s "${w}" -l -L -R ssl 2>&1`,{encoding:"utf8"}).includes("successful");return E("ssl",`verify-cert ${w}: ${U?"trusted":"not trusted"}`,Y?.verbose),U}catch{return!1}}function eU($,w){let Y=Lw($);if(!Y)return!1;for(let A of Of())try{let U=sU(`security find-certificate -a -Z "${A}" 2>/dev/null || true`,{encoding:"utf8"});for(let X of U.split(`
183
+ `))if(X.toUpperCase().includes("SHA-256")){if(X.split("=").pop().replace(/SHA-256\s+hash:\s*/gi,"").replace(/:/g,"").trim().toUpperCase()===Y)return E("ssl",`Root CA fingerprint found in ${A}`,w?.verbose),!0}}catch{}return!1}var V1="-d -r trustRoot -p ssl -p basic",L1="/Library/Keychains/System.keychain",Qf="rpx.localhost";var kf=j0(()=>{NU();f0()});import{execSync as Df}from"node:child_process";import z0 from"node:fs/promises";import*as Zf from"node:os";import{homedir as Q1}from"node:os";import*as N2 from"node:path";import{join as F0}from"node:path";import*as Ew from"node:process";function xf($,w){return[...new Set($.filter(Boolean))].map((Y)=>({serverName:Y,cert:w.cert,key:w.key}))}function Pf($,w,Y){let A=F0(Q1(),".stacks","ssl"),U=[...new Set([w,...$,"rpx.localhost"])];return{https:{certPath:$X,keyPath:F0(A,"rpx.localhost.key"),caCertPath:F0(A,"rpx.localhost.ca.crt"),commonName:w},verbose:Y,regenerateUntrustedCerts:!0,proxies:U.map((X)=>({from:"localhost:1",to:X,cleanUrls:!1}))}}function q2($){return{caCertPath:F0($,TN),caKeyPath:F0($,HN)}}async function NN($,w){try{let[Y,A]=await Promise.all([z0.readFile($.caCertPath,"utf8"),z0.readFile($.caKeyPath,"utf8")]);if(!Y.includes("-----BEGIN CERTIFICATE-----")||!A.includes("PRIVATE KEY-----"))return E("ssl",`Root CA files at ${$.caCertPath} look malformed, will regenerate`,w),null;return{certificate:Y,privateKey:A}}catch(Y){return E("ssl",`No existing Root CA at ${$.caCertPath} (${Y.code||Y}), will create one`,w),null}}function T2($){let w=new Set;w.add($);let Y=$.split(".");if(Y.length>=2)w.add(`*.${Y.slice(1).join(".")}`);return Array.from(w)}function R2($){let Y=aU($).replace(/\*/g,"wildcard"),A=F0(Q1(),".stacks","ssl"),U=A;if(typeof $?.https==="object")return U=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:A,{caCertPath:$.https.caCertPath||F0(U,`${Y}.ca.crt`),certPath:$.https.certPath||F0(U,`${Y}.crt`),keyPath:$.https.keyPath||F0(U,`${Y}.key`)};return{caCertPath:F0(U,`${Y}.ca.crt`),certPath:F0(U,`${Y}.crt`),keyPath:F0(U,`${Y}.key`)}}function H2($){let w=new Set;if(_w($))$.proxies.forEach((Y)=>{let A=Y.to||"rpx.localhost";T2(A).forEach((U)=>w.add(U))});else if(KY($)){let Y=$.to||"rpx.localhost";T2(Y).forEach((A)=>w.add(A))}else w.add("rpx.localhost");return w.add("localhost"),w.add("*.localhost"),w}async function O1($){if(Kw&&!$.forceRegenerate){E("ssl","Using cached SSL configuration",$.verbose);return}wX();let w=_w($)?$.proxies.map((j)=>j.to):[$.to];E("ssl",`Generating certificate for domains: ${w.join(", ")}`,$.verbose);let Y=TY($,$.verbose),A=Y.basePath||F0(Q1(),".stacks","ssl");await z0.mkdir(A,{recursive:!0});let U=q2(A),X=await NN(U,$.verbose),J=!1;if(!X){if($.verbose)R.info("Generating Root CA certificate (one-time)...");X=await _J(Y);try{await Promise.all([z0.writeFile(U.caCertPath,X.certificate),z0.writeFile(U.caKeyPath,X.privateKey,{mode:384})]),J=!0,E("ssl",`Persisted Root CA at ${U.caCertPath}`,$.verbose)}catch(j){throw E("ssl",`Error saving Root CA files: ${j}`,$.verbose),Error(`Failed to save Root CA files: ${j}`)}}else E("ssl",`Reusing existing Root CA from ${U.caCertPath}`,$.verbose);if($.verbose)R.info(`Generating host certificate for: ${w.join(", ")}`);let W=await kJ({...Y,rootCA:{certificate:X.certificate,privateKey:X.privateKey}});try{await Promise.all([z0.writeFile(Y.certPath,W.certificate),z0.writeFile(Y.keyPath,W.privateKey),z0.writeFile(Y.caCertPath,X.certificate)]),E("ssl","Certificate files saved successfully",$.verbose)}catch(j){throw E("ssl",`Error saving certificate files: ${j}`,$.verbose),Error(`Failed to save certificate files: ${j}`)}if(J?!1:await I2(U.caCertPath,{verbose:$.verbose,regenerateUntrustedCerts:!0})){if(E("ssl","Root CA already trusted, skipping trust store update",$.verbose),$.verbose)R.success("Root CA is already trusted in system trust store");if(Kw={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);return}if($.verbose)R.info("Adding certificate to system trust store (may require sudo permission)...");let B=!1;if(Ew.platform==="darwin")try{Sf({caPath:U.caCertPath,verbose:$.verbose});let j=oU();try{Df(`security add-trusted-cert ${V1} -k "${j}" "${U.caCertPath}"`,{stdio:"ignore"})}catch{}if(EY(`security add-trusted-cert ${V1} -k ${L1} "${U.caCertPath}"`),$.verbose)R.success("Successfully added Root CA to system trust store");B=!0;let z=F0(A,"trust-rpx-cert.sh"),G=`#!/bin/bash
182
184
  echo "Trusting RPX Root CA"
183
- sudo security add-trusted-cert ${V1} -k ${L1} "${X.caCertPath}"
185
+ sudo security add-trusted-cert ${V1} -k ${L1} "${U.caCertPath}"
184
186
  echo "Root CA trusted! Please restart your browser."
185
187
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
186
- `;await y0.writeFile(z,E,{mode:493})}catch(j){if($.verbose)q.warn(`Could not add Root CA to trust store automatically: ${j}`);let z=E0(Y,"trust-rpx-cert.sh"),E=`#!/bin/bash
188
+ `;await z0.writeFile(z,G,{mode:493})}catch(j){if($.verbose)R.warn(`Could not add Root CA to trust store automatically: ${j}`);let z=F0(A,"trust-rpx-cert.sh"),G=`#!/bin/bash
187
189
  echo "Trusting RPX Root CA"
188
- sudo security add-trusted-cert ${V1} -k ${L1} "${X.caCertPath}"
190
+ sudo security add-trusted-cert ${V1} -k ${L1} "${U.caCertPath}"
189
191
  echo "Root CA trusted! Please restart your browser."
190
192
  echo "If you still see certificate warnings, type 'thisisunsafe' on the warning page in Chrome/Arc browsers."
191
- `;if(await y0.writeFile(z,E,{mode:493}),$.verbose)q.info(`Created a trust helper script at: ${z}`),q.info(`If you're still having certificate issues, run: sh ${z}`)}else if(Gw.platform==="linux")try{let{exec:j}=await import("node:child_process"),z="/usr/local/share/ca-certificates/rpx",E=`
193
+ `;if(await z0.writeFile(z,G,{mode:493}),$.verbose)R.info(`Created a trust helper script at: ${z}`),R.info(`If you're still having certificate issues, run: sh ${z}`)}else if(Ew.platform==="linux")try{let{exec:j}=await import("node:child_process"),z="/usr/local/share/ca-certificates/rpx",G=`
192
194
  mkdir -p "/usr/local/share/ca-certificates/rpx" 2>/dev/null || true
193
- cp "${X.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
195
+ cp "${U.caCertPath}" "/usr/local/share/ca-certificates/rpx/"
194
196
  update-ca-certificates
195
197
  echo "RPX Root CA installed. Please restart your browser."
196
- `,F=E0(If.tmpdir(),`rpx-trust-${Date.now()}.sh`);await y0.writeFile(F,E,{mode:493}),await new Promise((T)=>{j(`sudo bash "${F}"`,(K)=>{if(K){if($.verbose)q.warn(`Could not trust certificates: ${K}`);T(!1)}else{if($.verbose)q.success("Successfully added certificates to system trust store");T(!0)}})}),await y0.unlink(F).catch(()=>{}),B=!0}catch(j){if($.verbose)q.warn(`Failed to trust certificates: ${j}`)}else if(Gw.platform==="win32")try{let j=`
197
- $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${X.caCertPath.replace(/\//g,"\\")}")
198
+ `,F=F0(Zf.tmpdir(),`rpx-trust-${Date.now()}.sh`);await z0.writeFile(F,G,{mode:493}),await new Promise((T)=>{j(`sudo bash "${F}"`,(K)=>{if(K){if($.verbose)R.warn(`Could not trust certificates: ${K}`);T(!1)}else{if($.verbose)R.success("Successfully added certificates to system trust store");T(!0)}})}),await z0.unlink(F).catch(()=>{}),B=!0}catch(j){if($.verbose)R.warn(`Failed to trust certificates: ${j}`)}else if(Ew.platform==="win32")try{let j=`
199
+ $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("${U.caCertPath.replace(/\//g,"\\")}")
198
200
  $store = New-Object System.Security.Cryptography.X509Certificates.X509Store("ROOT", "LocalMachine")
199
201
  $store.Open("ReadWrite")
200
202
  $store.Add($cert)
201
203
  $store.Close()
202
204
  Write-Host "Root CA trusted successfully!"
203
- `,z=E0(If.tmpdir(),"rpx-trust.ps1");if(await y0.writeFile(z,j),O1(`powershell -ExecutionPolicy Bypass -File "${z}"`),$.verbose)q.success("Successfully added certificate to Windows trust store");B=!0}catch(j){if($.verbose)q.warn(`Could not trust certificate: ${j}`)}else try{await yU(W,J.certificate,A),B=!0}catch(j){if($.verbose)q.warn(`Could not add certificate to trust store: ${j}`)}if(Kw={key:W.privateKey,cert:W.certificate,ca:J.certificate},$.verbose)q.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!B&&$.verbose)q.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),q.warn("This will bypass the warning and you should only need to do it once")}function rX(){Kw=null}async function a$($){if(!$)return null;if(Kw)return Kw;let w=FA($);try{let[A,Y,X]=await Promise.all([y0.access(w.keyPath).then(()=>!0).catch(()=>!1),y0.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?y0.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!A||!Y)return G("ssl",`Certificate files don't exist: key=${A}, cert=${Y}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let J="regenerateUntrustedCerts"in $,U=$.regenerateUntrustedCerts,W=J?U!==!1:!0;G("ssl",`Trust check: hasFlag=${J}, flagValue=${U}, shouldCheckTrust=${W}`,$.verbose);let f=w.basePath||E0(Q1(),".stacks","ssl"),B=Bz(f);if(!(W?await Fz(B.caCertPath,$):!0))return G("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[z,E,F]=await Promise.all([y0.readFile(w.keyPath,"utf8"),y0.readFile(w.certPath,"utf8"),X&&w.caCertPath?y0.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return G("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(_w($))try{let{X509Certificate:T}=await import("node:crypto"),H=new T(E).subjectAltName||"",R=$.proxies.map((M)=>M.to).filter((M)=>!H.includes(`DNS:${M}`));if(R.length>0)return G("ssl",`Certificate missing SANs for: ${R.join(", ")}, will regenerate`,$.verbose),null}catch(T){G("ssl",`Could not verify cert SANs: ${T}`,$.verbose)}return G("ssl","Successfully loaded existing certificates",$.verbose),Kw={key:z,cert:E,ca:F},Kw}catch(A){return G("ssl",`Error checking existing certificates: ${A}`,$.verbose),null}}function FA($,w){let A=gX($);G("ssl",`Primary domain: ${A}`,w);let Y=jz($),X=E0(Q1(),".stacks","ssl");if(typeof $.https==="object"){let J=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:X,U={domain:A,hostCertCN:A,basePath:J,caCertPath:$.https.caCertPath||Y.caCertPath,certPath:$.https.certPath||Y.certPath,keyPath:$.https.keyPath||Y.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||A,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(Wz($)).map((W)=>({type:2,value:W}))};if(Gf($.https.rootCA))U.rootCA=$.https.rootCA;return U}return{domain:A,hostCertCN:A,basePath:X,...Y,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:A,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:w||!1,subjectAltNames:Array.from(Wz($)).map((J)=>({type:2,value:J}))}}async function zz($,w){let A=jz({to:$,verbose:w}),Y=[A.caCertPath,A.certPath,A.keyPath];G("certificates","Attempting to clean up relating certificates",w),await Promise.all(Y.map((X)=>Tf(X,w)))}async function Fz($,w){try{if(G("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),Gw.platform==="darwin"){if(w?.serverName)return qf($,w.serverName,{verbose:w?.verbose});return pX($,{verbose:w?.verbose})}else if(Gw.platform==="win32")try{let Y=O1(`openssl x509 -noout -subject -in "${$}"`).toString().trim().split("=").slice(1).join("=").trim()||"";if(!Y)return G("ssl","Could not extract certificate subject",w?.verbose),!1;let X=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(O1(X).toString().includes(Y))return G("ssl","Certificate found in trusted root store",w?.verbose),!0;return G("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(A){return G("ssl",`Error checking certificate trust on Windows: ${A}`,w?.verbose),!1}else if(Gw.platform==="linux")try{let Y=O1(`openssl x509 -noout -fingerprint -sha256 -in "${$}"`).toString().trim().split("=")[1]?.trim()||"",X=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let J of X)try{if(O1(`find ${J} -type f -exec openssl x509 -noout -fingerprint -sha256 -in {} \\; 2>/dev/null | grep "${Y}"`).toString().includes(Y))return G("ssl",`Certificate fingerprint found in ${J}`,w?.verbose),!0}catch{}return G("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(A){return G("ssl",`Error checking certificate trust on Linux: ${A}`,w?.verbose),!1}return G("ssl",`Platform ${Gw.platform} not supported for certificate trust check`,w?.verbose),!1}catch(A){return G("ssl",`Error checking if certificate is trusted: ${A}`,w?.verbose),!1}}var Kw=null,tX,oH="rpx-root-ca.crt",eH="rpx-root-ca.key";var aX=F0(()=>{CU();fw();OU();Mf();f0();Mf();QU();tX=E0(Q1(),".stacks","ssl","rpx.localhost.crt")});function AN(){let $=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite($)&&$>0?$:30000}function YN($){let w=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(w)&&w>0?w:$*8}function XN(){let $=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite($)&&$>0?$:0}function JN(){let $=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite($)&&$>0?$:256}class Nz{socket=null;buf=new Uint8Array(UN);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;waiter=null;drainWaiter=null;async writeAll($){let w=this.socket,A=w.write($);while(A<$.length){if(this.closed)throw sX;await new Promise((Y)=>{this.drainWaiter=Y}),A+=w.write($.subarray(A))}}wakeDrain(){let $=this.drainWaiter;if($)this.drainWaiter=null,$()}push($){if(this.bodyQueue){let w=$.length<=this.bodyRemaining?$.length:this.bodyRemaining;if(w>0)this.bodyQueue.push($.slice(0,w));if(this.bodyRemaining-=w,w<$.length)this.appendToBuf($.subarray(w));this.wake();return}this.appendToBuf($),this.wake()}appendToBuf($){let w=this.len+$.length;if(w>this.buf.length){let A=new Uint8Array(Math.max(this.buf.length*2,w));A.set(this.buf.subarray(0,this.len)),this.buf=A}this.buf.set($,this.len),this.len=w}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let $=this.waiter;if($)this.waiter=null,$()}waitForData($){if(this.len>$||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class Rz{host;port;maxTotal;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=AN();maxWaiters;constructor($,w,A){this.host=$;this.port=w;this.maxTotal=A;this.maxWaiters=YN(A)}dial(){let $=new Nz;return wN({hostname:this.host,port:this.port,socket:{data:(w,A)=>$.push(A),drain:()=>$.wakeDrain(),close:()=>$.markClosed(),end:()=>$.markClosed(),error:()=>$.markClosed(),connectError:()=>$.markClosed(),timeout:()=>$.markTimedOut()}}).then((w)=>{let A=w;A.setNoDelay?.(!0);let Y=XN();if(Y>0)A.timeout?.(Y);return $.socket=w,$})}acquireIdleSync(){while(this.idle.length){let $=this.idle.pop();if(!$.closed)return $.socket?.ref(),$.pos=0,$.len=0,$;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw _1;let $=await this.waitForSlot();if($===_1)throw _1;if($)return $.pos=0,$.len=0,$}this.open++;try{return await this.dial()}catch($){throw this.open--,this.wakeWaiter(),$}}waitForSlot(){return new Promise(($)=>{let w=!1,A=(J)=>{if(w)return;w=!0,clearTimeout(X),$(J)},Y=(J)=>A(J),X=setTimeout(()=>{let J=this.waiters.indexOf(Y);if(J!==-1)this.waiters.splice(J,1);A(_1)},this.queueWaitMs);X.unref?.(),this.waiters.push(Y)})}release($){if($.closed){this.open--,this.wakeWaiter();return}$.compact(),$.fresh=!1;let w=this.waiters.shift();if(w){$.socket?.ref(),w($);return}$.idleSince=Date.now(),$.socket?.unref(),this.idle.push($),this.ensureSweeper()}destroy($){$.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let $=this.waiters.shift();if($)$(null)}ensureSweeper(){if(this.sweeper)return;this.sweeper=setInterval(()=>this.sweep(),Ez),this.sweeper.unref?.()}sweep(){let $=Date.now()-Ez;if(this.idle.length){let w=[];for(let A of this.idle)if(A.closed||A.idleSince<=$)A.destroy(),this.open--;else w.push(A);this.idle=w}if(this.idle.length===0&&this.sweeper)clearInterval(this.sweeper),this.sweeper=null}}function FN($,w){let A=Gz.get($);if(!A){let Y=$.lastIndexOf(":"),X=Y===-1?$:$.slice(0,Y),J=Y===-1?80:Number($.slice(Y+1));A=new Rz(X,J,w),Gz.set($,A)}return A}function Kz($,w,A){for(let Y=A+3;Y<w;Y++)if($[Y]===10&&$[Y-1]===13&&$[Y-2]===10&&$[Y-3]===13)return Y-3;return-1}function EN($,w,A){let Y=Hz.decode($.subarray(w,A)),X=Y.indexOf(`\r
204
- `),J=X===-1?Y:Y.slice(0,X),U=J.indexOf(" "),W=Number.parseInt(J.slice(U+1,U+5),10),f=J.startsWith("HTTP/1.0"),B=[],j=-1,z=!1,E=f,F=!1,T=X===-1?Y.length:X+2;while(T<Y.length){let K=Y.indexOf(`\r
205
- `,T);if(K===-1)K=Y.length;let H=Y.slice(T,K);if(T=K+2,H==="")continue;let N=H.indexOf(":");if(N===-1)continue;let R=H.slice(0,N),M=H.slice(N+1).trim(),y=R.charCodeAt(0)|32;if(y===99||y===116||y===107){let I=R.toLowerCase();if(I==="content-length"){j=Number.parseInt(M,10);continue}if(I==="transfer-encoding"){if(M.toLowerCase().includes("chunked"))z=!0;continue}if(I==="connection"){let C=M.toLowerCase();if(C.includes("close"))E=!0;if(C.includes("keep-alive"))F=!0;continue}if(I==="keep-alive")continue}B.push([R,M])}if(f&&F)E=!1;return{status:W,headerEnd:A,headers:B,contentLength:j,chunked:z,closeConn:E}}function GN($,w){return w||$===204||$===304}async function qz($){let{hostPort:w,method:A,path:Y,reqHeaders:X,forwardedHost:J,originOverride:U,body:W}=$,f=A==="HEAD";if(X.get("expect")||X.get("upgrade"))throw EA;let B=null;if(W){let F=X.get("content-length"),T=F?Number.parseInt(F,10):Number.NaN;if(Number.isNaN(T)||T>Tz)throw EA;if(B=await MN(W),B===null)throw EA}let j=qN(A,Y,X,w,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 E=FN(w,$.maxPerHost??JN());for(let F=0;;F++){let T=E.acquireIdleSync()??await E.acquireOrDial();try{let K=T.socket.write(z);if(K<z.length)await T.writeAll(z.subarray(K));return await TN(E,T,f)}catch(K){let H=!T.fresh&&F===0&&K===sX;if(E.destroy(T),H)continue;if(K===sX)throw Error("upstream closed connection");throw K}}}async function KN($){let w=Kz($.buf,$.len,$.pos);while(w===-1){if($.closed){if($.timedOut)throw hf;if($.len===$.pos)throw sX;throw Error("upstream closed mid-header")}if($.len-$.pos>fN)throw Error("upstream header block too large");await $.waitForData($.len),w=Kz($.buf,$.len,$.pos)}return w}async function TN($,w,A){let Y;for(;;){let J=await KN(w);if(Y=EN(w.buf,w.pos,J),w.pos=J+4,Y.status>=100&&Y.status<200)continue;break}let X=Y.headers;if(GN(Y.status,A))return Mz($,w,Y.closeConn),new Response(null,{status:Y.status,headers:X});if(Y.chunked)return new Response(RN($,w,Y.closeConn),{status:Y.status,headers:X});if(Y.contentLength>=0){if(w.len-w.pos>=Y.contentLength){let U=w.pos+Y.contentLength,W=w.len>U,f=null;if(Y.contentLength>=WN)f=w.buf.subarray(w.pos,U),w.buf=new Uint8Array(BN);else if(Y.contentLength>0)f=w.buf.slice(w.pos,U);if(w.pos=0,w.len=0,Y.closeConn||W)$.destroy(w);else $.release(w);return new Response(f,{status:Y.status,headers:X})}return new Response(HN($,w,Y.contentLength,Y.closeConn),{status:Y.status,headers:X})}return new Response(NN(w),{status:Y.status,headers:X})}function Mz($,w,A){if(A||w.pos!==w.len)$.destroy(w);else $.release(w)}function HN($,w,A,Y){let X=w.len-w.pos,J=X>0?w.buf.slice(w.pos,w.len):null;w.pos=0,w.len=0,w.bodyQueue=[],w.bodyRemaining=A-X;let U=(W)=>{if(w.bodyQueue=null,Y||w.len>0)$.destroy(w);else $.release(w);W.close()};return new ReadableStream({start(W){if(J)W.enqueue(J);if(w.bodyRemaining===0&&w.bodyQueue.length===0)U(W)},async pull(W){for(;;){let f=w.bodyQueue;if(f&&f.length>0){if(W.enqueue(f.shift()),w.bodyRemaining===0&&f.length===0)U(W);return}if(w.bodyRemaining===0){if(w.bodyQueue)U(W);return}if(w.closed){w.bodyQueue=null,$.destroy(w),W.error(Error("upstream closed mid-body"));return}await w.waitForBody()}},cancel(){w.bodyQueue=null,$.destroy(w)}})}function NN($){return new ReadableStream({async pull(w){for(;;){if($.len>$.pos){w.enqueue($.buf.slice($.pos,$.len)),$.pos=$.len;return}if($.closed){$.destroy(),w.close();return}await $.waitForData($.len)}},cancel(){$.destroy()}})}function RN($,w,A){let Y=0,X=!1;async function J(){for(;;){for(let U=w.pos;U+1<w.len;U++)if(w.buf[U]===13&&w.buf[U+1]===10){let W=Hz.decode(w.buf.subarray(w.pos,U));return w.pos=U+2,W}if(w.closed)throw Error("upstream closed mid-chunk-header");await w.waitForData(w.len)}}return new ReadableStream({async pull(U){for(;;){if(Y>0){if(w.len===w.pos){if(w.closed){$.destroy(w),U.error(Error("upstream closed mid-chunk"));return}await w.waitForData(w.len);continue}let j=Math.min(Y,w.len-w.pos);if(U.enqueue(w.buf.slice(w.pos,w.pos+j)),w.pos+=j,Y-=j,Y===0)X=!0;return}if(X)await J(),X=!1;let W=await J(),f=W.indexOf(";"),B=Number.parseInt(f===-1?W:W.slice(0,f),16);if(B===0){for(;;)if(await J()==="")break;Mz($,w,A),U.close();return}Y=B}},cancel(){$.destroy(w)}})}function qN($,w,A,Y,X,J,U){let W=`${$} ${w} HTTP/1.1\r
206
- host: ${Y}\r
205
+ `,z=F0(Zf.tmpdir(),"rpx-trust.ps1");if(await z0.writeFile(z,j),Df(`powershell -ExecutionPolicy Bypass -File "${z}"`),$.verbose)R.success("Successfully added certificate to Windows trust store");B=!0}catch(j){if($.verbose)R.warn(`Could not trust certificate: ${j}`)}else try{await xJ(W,X.certificate,Y),B=!0}catch(j){if($.verbose)R.warn(`Could not add certificate to trust store: ${j}`)}if(Kw={key:W.privateKey,cert:W.certificate,ca:X.certificate},$.verbose)R.success(`Certificate generated successfully for ${w.length} domain${w.length>1?"s":""}`);if(!B&&$.verbose)R.warn('If you see certificate warnings in Chrome/Arc, type "thisisunsafe" on the warning page'),R.warn("This will bypass the warning and you should only need to do it once")}function wX(){Kw=null}async function a$($){if(!$)return null;if(Kw)return Kw;let w=TY($);try{let[Y,A,U]=await Promise.all([z0.access(w.keyPath).then(()=>!0).catch(()=>!1),z0.access(w.certPath).then(()=>!0).catch(()=>!1),w.caCertPath?z0.access(w.caCertPath).then(()=>!0).catch(()=>!1):Promise.resolve(!1)]);if(!Y||!A)return E("ssl",`Certificate files don't exist: key=${Y}, cert=${A}, paths: ${w.keyPath}, ${w.certPath}`,$.verbose),null;let X="regenerateUntrustedCerts"in $,J=$.regenerateUntrustedCerts,W=X?J!==!1:!0;E("ssl",`Trust check: hasFlag=${X}, flagValue=${J}, shouldCheckTrust=${W}`,$.verbose);let f=w.basePath||F0(Q1(),".stacks","ssl"),B=q2(f);if(!(W?await I2(B.caCertPath,$):!0))return E("ssl","Root CA exists but is not trusted, will regenerate",$.verbose),null;let[z,G,F]=await Promise.all([z0.readFile(w.keyPath,"utf8"),z0.readFile(w.certPath,"utf8"),U&&w.caCertPath?z0.readFile(w.caCertPath,"utf8"):Promise.resolve(void 0)]);if(F&&!F.includes("-----BEGIN CERTIFICATE-----"))return E("ssl","Invalid root CA certificate content, will regenerate",$.verbose),null;if(_w($))try{let{X509Certificate:T}=await import("node:crypto"),H=new T(G).subjectAltName||"",M=$.proxies.map((I)=>I.to).filter((I)=>!H.includes(`DNS:${I}`));if(M.length>0)return E("ssl",`Certificate missing SANs for: ${M.join(", ")}, will regenerate`,$.verbose),null}catch(T){E("ssl",`Could not verify cert SANs: ${T}`,$.verbose)}return E("ssl","Successfully loaded existing certificates",$.verbose),Kw={key:z,cert:G,ca:F},Kw}catch(Y){return E("ssl",`Error checking existing certificates: ${Y}`,$.verbose),null}}function TY($,w){let Y=aU($);E("ssl",`Primary domain: ${Y}`,w);let A=R2($),U=F0(Q1(),".stacks","ssl");if(typeof $.https==="object"){let X=$.https.basePath&&$.https.basePath.trim()!==""?$.https.basePath:U,J={domain:Y,hostCertCN:Y,basePath:X,caCertPath:$.https.caCertPath||A.caCertPath,certPath:$.https.certPath||A.certPath,keyPath:$.https.keyPath||A.keyPath,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:$.https.commonName||Y,organizationName:$.https.organizationName||"Local Development",countryName:$.https.countryName||"US",stateName:$.https.stateName||"California",localityName:$.https.localityName||"Playa Vista",validityDays:$.https.validityDays||825,verbose:w||!1,subjectAltNames:Array.from(H2($)).map((W)=>({type:2,value:W}))};if(hf($.https.rootCA))J.rootCA=$.https.rootCA;return J}return{domain:Y,hostCertCN:Y,basePath:U,...A,altNameIPs:["127.0.0.1","::1"],altNameURIs:[],commonName:Y,organizationName:"Local Development",countryName:"US",stateName:"California",localityName:"Playa Vista",validityDays:825,verbose:w||!1,subjectAltNames:Array.from(H2($)).map((X)=>({type:2,value:X}))}}async function M2($,w){let Y=R2({to:$,verbose:w}),A=[Y.caCertPath,Y.certPath,Y.keyPath];E("certificates","Attempting to clean up relating certificates",w),await Promise.all(A.map((U)=>Lf(U,w)))}async function I2($,w){try{if(E("ssl",`Checking if certificate is trusted: ${$}`,w?.verbose),Ew.platform==="darwin"){if(w?.serverName)return _f($,w.serverName,{verbose:w?.verbose});return eU($,{verbose:w?.verbose})}else if(Ew.platform==="win32")try{let Y=cJ($)||"";if(!Y)return E("ssl","Could not extract certificate subject",w?.verbose),!1;let A=`powershell -Command "Get-ChildItem -Path Cert:\\LocalMachine\\Root | Where-Object { $_.Subject -like '*${Y}*' } | Select-Object Subject"`;if(Df(A).toString().includes(Y))return E("ssl","Certificate found in trusted root store",w?.verbose),!0;return E("ssl","Certificate not found in trusted root store",w?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Windows: ${Y}`,w?.verbose),!1}else if(Ew.platform==="linux")try{let Y=Lw($);if(!Y)return E("ssl","Could not extract certificate fingerprint",w?.verbose),!1;let A=["/etc/ssl/certs","/etc/pki/tls/certs"];for(let U of A){let X;try{X=await z0.readdir(U)}catch{continue}for(let J of X){let W=Lw(N2.join(U,J));if(W&&W===Y)return E("ssl",`Certificate fingerprint found in ${U}`,w?.verbose),!0}}return E("ssl","Certificate not found in system trust stores",w?.verbose),!1}catch(Y){return E("ssl",`Error checking certificate trust on Linux: ${Y}`,w?.verbose),!1}return E("ssl",`Platform ${Ew.platform} not supported for certificate trust check`,w?.verbose),!1}catch(Y){return E("ssl",`Error checking if certificate is trusted: ${Y}`,w?.verbose),!1}}var Kw=null,$X,TN="rpx-root-ca.crt",HN="rpx-root-ca.key";var YX=j0(()=>{TU();fw();iJ();kf();f0();kf();NU();NU();$X=F0(Q1(),".stacks","ssl","rpx.localhost.crt")});function MN($){return RN.has($.toUpperCase())}function IN(){let $=Number.parseInt(process.env.RPX_QUEUE_WAIT_MS??"",10);return Number.isFinite($)&&$>0?$:30000}function yN($){let w=Number.parseInt(process.env.RPX_MAX_QUEUED??"",10);return Number.isFinite(w)&&w>0?w:$*8}function CN(){let $=Number.parseInt(process.env.RPX_CHECKOUT_IDLE_MS??"",10);return Number.isFinite($)&&$>0?$:0}function hN(){let $=Number.parseInt(process.env.RPX_UPSTREAM_TIMEOUT??"",10);return Number.isFinite($)&&$>0?$:0}function VN(){let $=Number.parseInt(process.env.RPX_MAX_UPSTREAM_CONNS??"",10);return Number.isFinite($)&&$>0?$:256}class Q2{socket=null;buf=new Uint8Array(LN);len=0;pos=0;closed=!1;fresh=!0;timedOut=!1;idleSince=0;bodyQueue=null;bodyRemaining=0;queuedBytes=0;streamingBody=!1;paused=!1;lastActivityAt=0;waiter=null;drainWaiter=null;async writeAll($){let w=this.socket,Y=w.write($);while(Y<$.length){if(this.closed)throw AX;await new Promise((A)=>{this.drainWaiter=A}),Y+=w.write($.subarray(Y))}}wakeDrain(){let $=this.drainWaiter;if($)this.drainWaiter=null,$()}push($){if(this.bodyQueue){let w=$.length<=this.bodyRemaining?$.length:this.bodyRemaining;if(w>0)this.bodyQueue.push($.slice(0,w)),this.queuedBytes+=w;if(this.bodyRemaining-=w,w<$.length)this.appendToBuf($.subarray(w));this.maybePause(),this.lastActivityAt=Date.now(),this.wake();return}this.appendToBuf($),this.maybePause(),this.lastActivityAt=Date.now(),this.wake()}bufferedBodyBytes(){return this.bodyQueue?this.queuedBytes:this.len-this.pos}maybePause(){if(this.streamingBody&&!this.paused&&this.bufferedBodyBytes()>QN)this.paused=!0,this.socket?.pause?.()}resumeIfDrained(){if(this.lastActivityAt=Date.now(),this.paused&&this.bufferedBodyBytes()<=ON)this.paused=!1,this.socket?.resume?.()}clearStreaming(){if(this.streamingBody=!1,this.queuedBytes=0,this.paused)this.paused=!1,this.socket?.resume?.()}appendToBuf($){let w=this.len+$.length;if(w>this.buf.length){let Y=new Uint8Array(Math.max(this.buf.length*2,w));Y.set(this.buf.subarray(0,this.len)),this.buf=Y}this.buf.set($,this.len),this.len=w}markClosed(){this.closed=!0,this.wake(),this.wakeDrain()}markTimedOut(){this.timedOut=!0,this.markClosed()}wake(){let $=this.waiter;if($)this.waiter=null,$()}waitForData($){if(this.len>$||this.closed)return Promise.resolve();return new Promise((w)=>{this.waiter=w})}waitForBody(){if(this.bodyQueue!==null&&this.bodyQueue.length>0||this.closed)return Promise.resolve();return new Promise(($)=>{this.waiter=$})}compact(){if(this.pos===0)return;if(this.pos===this.len){this.pos=0,this.len=0;return}this.buf.copyWithin(0,this.pos,this.len),this.len-=this.pos,this.pos=0}destroy(){this.closed=!0;try{this.socket?.end()}catch{}this.socket=null}}class O2{host;port;maxTotal;idle=[];waiters=[];open=0;sweeper=null;queueWaitMs=IN();maxWaiters;checkoutIdleMs=CN();inUse=new Set;constructor($,w,Y){this.host=$;this.port=w;this.maxTotal=Y;this.maxWaiters=yN(Y)}trackCheckout($){if($.lastActivityAt=Date.now(),this.checkoutIdleMs>0)this.inUse.add($),this.ensureSweeper()}dial(){let $=new Q2;return qN({hostname:this.host,port:this.port,socket:{data:(w,Y)=>$.push(Y),drain:()=>$.wakeDrain(),close:()=>$.markClosed(),end:()=>$.markClosed(),error:()=>$.markClosed(),connectError:()=>$.markClosed(),timeout:()=>$.markTimedOut()}}).then((w)=>{let Y=w;Y.setNoDelay?.(!0);let A=hN();if(A>0)Y.timeout?.(A);return $.socket=w,$})}acquireIdleSync(){while(this.idle.length){let $=this.idle.pop();if(!$.closed)return $.socket?.ref(),$.pos=0,$.len=0,this.trackCheckout($),$;this.open--}return null}async acquireOrDial(){if(this.open>=this.maxTotal){if(this.waiters.length>=this.maxWaiters)throw kw;let $=await this.waitForSlot();if($===kw)throw kw;if($)return $.pos=0,$.len=0,this.trackCheckout($),$}this.open++;try{let $=await this.dial();return this.trackCheckout($),$}catch($){throw this.open--,this.wakeWaiter(),$}}waitForSlot(){return new Promise(($)=>{let w=!1,Y=(X)=>{if(w)return;w=!0,clearTimeout(U),$(X)},A=(X)=>Y(X),U=setTimeout(()=>{let X=this.waiters.indexOf(A);if(X!==-1)this.waiters.splice(X,1);Y(kw)},this.queueWaitMs);U.unref?.(),this.waiters.push(A)})}release($){if(this.inUse.delete($),$.closed){this.open--,this.wakeWaiter();return}$.clearStreaming(),$.compact(),$.fresh=!1;let w=this.waiters.shift();if(w){$.socket?.ref(),this.trackCheckout($),w($);return}$.idleSince=Date.now(),$.socket?.unref(),this.idle.push($),this.ensureSweeper()}destroy($){this.inUse.delete($),$.destroy(),this.open--,this.wakeWaiter()}wakeWaiter(){let $=this.waiters.shift();if($)$(null)}ensureSweeper(){if(this.sweeper)return;let $=this.checkoutIdleMs>0?Math.min(bf,this.checkoutIdleMs):bf;this.sweeper=setInterval(()=>this.sweep(),$),this.sweeper.unref?.()}sweep(){let $=Date.now(),w=$-bf;if(this.idle.length){let Y=[];for(let A of this.idle)if(A.closed||A.idleSince<=w)A.destroy(),this.open--;else Y.push(A);this.idle=Y}if(this.checkoutIdleMs>0&&this.inUse.size){let Y=$-this.checkoutIdleMs;for(let A of this.inUse)if(!A.closed&&A.lastActivityAt>0&&A.lastActivityAt<=Y)A.markTimedOut()}if(this.idle.length===0&&this.inUse.size===0&&this.sweeper)clearInterval(this.sweeper),this.sweeper=null}}function ZN($,w){let Y=y2.get($);if(!Y){let A=$.lastIndexOf(":"),U=A===-1?$:$.slice(0,A),X=A===-1?80:Number($.slice(A+1));Y=new O2(U,X,w),y2.set($,Y)}return Y}function C2($,w,Y){for(let A=Y+3;A<w;A++)if($[A]===10&&$[A-1]===13&&$[A-2]===10&&$[A-3]===13)return A-3;return-1}function xN($,w,Y){let A=L2.decode($.subarray(w,Y)),U=A.indexOf(`\r
206
+ `),X=U===-1?A:A.slice(0,U),J=X.indexOf(" "),W=Number.parseInt(X.slice(J+1,J+5),10),f=X.startsWith("HTTP/1.0"),B=[],j=-1,z=!1,G=f,F=!1,T=!1,K=U===-1?A.length:U+2;while(K<A.length){let H=A.indexOf(`\r
207
+ `,K);if(H===-1)H=A.length;let q=A.slice(K,H);if(K=H+2,q==="")continue;let M=q.indexOf(":");if(M===-1)continue;let I=q.slice(0,M),h=q.slice(M+1).trim(),N=I.charCodeAt(0)|32;if(N===99||N===116||N===107){let C=I.toLowerCase();if(C==="content-length"){let O=/^\d+$/.test(h)?Number(h):Number.NaN;if(!Number.isSafeInteger(O)||j>=0&&j!==O)T=!0;else j=O;continue}if(C==="transfer-encoding"){if(h.toLowerCase().includes("chunked"))z=!0;continue}if(C==="connection"){let O=h.toLowerCase();if(O.includes("close"))G=!0;if(O.includes("keep-alive"))F=!0;continue}if(C==="keep-alive")continue}B.push([I,h])}if(f&&F)G=!1;if(z&&j>=0)j=-1;return{status:W,headerEnd:Y,headers:B,contentLength:j,chunked:z,closeConn:G,malformed:T}}function PN($,w){return w||$===204||$===304}async function S2($){let{hostPort:w,method:Y,path:A,reqHeaders:U,forwardedHost:X,originOverride:J,body:W}=$,f=Y==="HEAD";if(U.get("expect")||U.get("upgrade"))throw HY;let B=null;if(W){let F=U.get("content-length"),T=F?Number.parseInt(F,10):Number.NaN;if(Number.isNaN(T)||T>h2)throw HY;if(B=await dN(W),B===null)throw HY}let j=mN(Y,A,U,w,X,J,B),z=j;if(B&&B.length)z=new Uint8Array(j.length+B.length),z.set(j),z.set(B,j.length);let G=ZN(w,$.maxPerHost??VN());for(let F=0;;F++){if(F>0)await new Promise((K)=>{setTimeout(K,F)});let T;try{T=G.acquireIdleSync()??await G.acquireOrDial()}catch(K){if(K!==kw&&F<4)continue;throw K}try{let K=T.socket.write(z);if(K<z.length)await T.writeAll(z.subarray(K));return await uN(G,T,f)}catch(K){let H=K===AX&&F<4&&(T.fresh||MN(Y));if(G.destroy(T),H)continue;if(K===AX)throw Error("upstream closed connection");throw K}}}async function bN($){let w=C2($.buf,$.len,$.pos);while(w===-1){if($.closed){if($.timedOut)throw uf;if($.len===$.pos)throw AX;throw Error("upstream closed mid-header")}if($.len-$.pos>V2)throw Error("upstream header block too large");await $.waitForData($.len),w=C2($.buf,$.len,$.pos)}return w}async function uN($,w,Y){let A;for(;;){let X=await bN(w);if(A=xN(w.buf,w.pos,X),w.pos=X+4,A.status>=100&&A.status<200)continue;break}if(A.malformed)throw $.destroy(w),Error("upstream sent malformed response framing");let U=A.headers;if(PN(A.status,Y))return _2($,w,A.closeConn),new Response(null,{status:A.status,headers:U});if(A.chunked)return new Response(vN($,w,A.closeConn),{status:A.status,headers:U});if(A.contentLength>=0){if(w.len-w.pos>=A.contentLength){let J=w.pos+A.contentLength,W=w.len>J,f=null;if(A.contentLength>=SN)f=w.buf.subarray(w.pos,J),w.buf=new Uint8Array(_N);else if(A.contentLength>0)f=w.buf.slice(w.pos,J);if(w.pos=0,w.len=0,A.closeConn||W)$.destroy(w);else $.release(w);return new Response(f,{status:A.status,headers:U})}return new Response(iN($,w,A.contentLength,A.closeConn),{status:A.status,headers:U})}return new Response(cN(w),{status:A.status,headers:U})}function _2($,w,Y){if(Y||w.pos!==w.len)$.destroy(w);else $.release(w)}function iN($,w,Y,A){let U=w.len-w.pos,X=U>0?w.buf.slice(w.pos,w.len):null;w.pos=0,w.len=0,w.bodyQueue=[],w.bodyRemaining=Y-U,w.queuedBytes=0,w.streamingBody=!0;let J=(W)=>{if(w.bodyQueue=null,A||w.len>0)$.destroy(w);else $.release(w);W.close()};return new ReadableStream({start(W){if(X)W.enqueue(X);if(w.bodyRemaining===0&&w.bodyQueue.length===0)J(W)},async pull(W){for(;;){let f=w.bodyQueue;if(f&&f.length>0){let B=f.shift();if(w.queuedBytes-=B.length,w.resumeIfDrained(),W.enqueue(B),w.bodyRemaining===0&&f.length===0)J(W);return}if(w.bodyRemaining===0){if(w.bodyQueue)J(W);return}if(w.closed){w.bodyQueue=null,$.destroy(w),W.error(Error("upstream closed mid-body"));return}await w.waitForBody()}},cancel(){w.bodyQueue=null,$.destroy(w)}})}function cN($){return $.streamingBody=!0,new ReadableStream({async pull(w){for(;;){if($.len>$.pos){w.enqueue($.buf.slice($.pos,$.len)),$.pos=$.len,$.resumeIfDrained();return}if($.closed){$.destroy(),w.close();return}await $.waitForData($.len)}},cancel(){$.destroy()}})}function vN($,w,Y){w.streamingBody=!0;let A=0,U=!1;async function X(){for(;;){for(let J=w.pos;J+1<w.len;J++)if(w.buf[J]===13&&w.buf[J+1]===10){let W=L2.decode(w.buf.subarray(w.pos,J));return w.pos=J+2,W}if(w.closed)throw Error("upstream closed mid-chunk-header");if(w.len-w.pos>V2)throw Error("upstream chunk header too large");await w.waitForData(w.len)}}return new ReadableStream({async pull(J){for(;;){if(A>0){if(w.len===w.pos){if(w.closed){$.destroy(w),J.error(Error("upstream closed mid-chunk"));return}await w.waitForData(w.len);continue}let j=Math.min(A,w.len-w.pos);if(J.enqueue(w.buf.slice(w.pos,w.pos+j)),w.pos+=j,A-=j,w.resumeIfDrained(),A===0)U=!0;return}if(U)await X(),U=!1;let W=await X(),f=W.indexOf(";"),B=Number.parseInt(f===-1?W:W.slice(0,f),16);if(!Number.isInteger(B)||B<0){$.destroy(w),J.error(Error("upstream sent malformed chunk size"));return}if(B===0){for(;;)if(await X()==="")break;_2($,w,Y),J.close();return}A=B}},cancel(){$.destroy(w)}})}function mN($,w,Y,A,U,X,J){let W=`${$} ${w} HTTP/1.1\r
208
+ host: ${A}\r
207
209
  x-forwarded-for: 127.0.0.1\r
208
210
  x-forwarded-proto: https\r
209
- x-forwarded-host: ${X}\r
210
- `;if(J!==void 0)W+=`origin: ${J}\r
211
- `;let f=!1;for(let[B,j]of A){let z=B.toLowerCase();if(zN.has(z))continue;if(J!==void 0&&z==="origin")continue;if(z==="content-length")f=!0;W+=`${B}: ${j}\r
211
+ x-forwarded-host: ${U}\r
212
+ `;if(X!==void 0)W+=`origin: ${X}\r
213
+ `;let f=!1;for(let[B,j]of Y){let z=B.toLowerCase();if(DN.has(z))continue;if(X!==void 0&&z==="origin")continue;if(z==="content-length")f=!0;W+=`${B}: ${j}\r
212
214
  `}if(W+=`connection: keep-alive\r
213
- `,U&&!f)W+=`content-length: ${U.length}\r
215
+ `,J&&!f)W+=`content-length: ${J.length}\r
214
216
  `;return W+=`\r
215
- `,jN.encode(W)}async function MN($){let w=$.getReader(),A=[],Y=0;for(;;){let{done:U,value:W}=await w.read();if(U)break;if(W){if(Y+=W.length,Y>Tz)return w.cancel().catch(()=>{}),null;A.push(W)}}if(A.length===1)return A[0];let X=new Uint8Array(Y),J=0;for(let U of A)X.set(U,J),J+=U.length;return X}var wN,EA,sX,hf,_1,Tz=1048576,Ez=30000,UN=16384,fN=262144,WN=8192,BN=4096,jN,Hz,zN,Gz;var Iz=F0(()=>{({connect:wN}=Bun),EA=Symbol("rpx.pool.fallback"),sX=Symbol("rpx.pool.stale"),hf=Symbol("rpx.pool.timeout"),_1=Symbol("rpx.pool.busy");jN=new TextEncoder,Hz=new TextDecoder,zN=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);Gz=new Map});import*as G$ from"node:path";function GA($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function yN($){let w=G$.extname($).toLowerCase();return IN[w]??"application/octet-stream"}function CN($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let A=G$.posix.normalize(`/${w}`);if(A.includes(".."))return null;return A.replace(/^\/+/,"")}function hN($,w){let A=CN($);if(A===null)return null;let Y=G$.posix.extname(A);if(w.cleanUrls&&Y===".html"){let X=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:G$.join(w.dir,A),redirectTo:X||"/"}}if(A===""||$.endsWith("/"))return{filePath:G$.join(w.dir,A,"index.html")};if(Y!=="")return{filePath:G$.join(w.dir,A)};if(w.pathRewriteStyle==="flat")return{filePath:G$.join(w.dir,`${A}.html`)};return{filePath:G$.join(w.dir,A,"index.html")}}async function yz($,w){let A=hN($,w);if(!A)return new Response("Forbidden",{status:403});if(A.redirectTo)return new Response(null,{status:301,headers:{Location:A.redirectTo}});let Y=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",X=Bun.file(A.filePath);if(await X.exists())return new Response(X,{status:200,headers:{"Content-Type":yN(A.filePath),"Cache-Control":Y}});if(w.spa){let J=G$.join(w.dir,"index.html"),U=Bun.file(J);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var IN;var KA=F0(()=>{IN={".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 LN($){let w=$.headers.get("host")||"",A=w.indexOf(":");return A===-1?w:w.slice(0,A)}function hz($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let A=$.slice(w.length);return A===""?"/":A}return $}function Cz($,w,A){let Y=w.sourceHost??"",J=w.stripBasePathPrefix??!1?hz($,w.basePath):$,U=Kf(J,w.pathRewrites);if(U)Y=U.targetHost,J=U.targetPath,G("request",`Path rewrite: ${$} → ${Y}${J}`,A);return{targetHost:Y,targetPath:J}}function ON($){let w=$.indexOf("://"),A=w===-1?$.indexOf("/"):$.indexOf("/",w+3);if(A===-1)return{pathname:"/",search:""};let Y=$.indexOf("?",A);if(Y===-1)return{pathname:$.slice(A),search:""};return{pathname:$.slice(A,Y),search:$.slice(Y)}}function k1($,w){let A=async(Y,X)=>{let{pathname:J,search:U}=ON(Y.url),W=LN(Y),f=$(W,J);if(!f)return G("request",`No route found for host: ${W}`,w),new Response(`No proxy configured for ${W}`,{status:404});if(f.static){let T=f.stripBasePathPrefix??!0?hz(J,f.basePath):J;return yz(T,f.static)}if(Y.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!X||!f.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:F,targetPath:T}=Cz(J,f,w),K=`ws://${F}${T}${U}`,H={};for(let[M,y]of Y.headers)if(!VN.has(M.toLowerCase())&&M.toLowerCase()!=="host")H[M]=y;H.host=F,H["x-forwarded-for"]="127.0.0.1",H["x-forwarded-proto"]="https",H["x-forwarded-host"]=W;let N={targetUrl:K,forwardHeaders:H};if(X.upgrade(Y,{data:N})){G("ws",`upgraded ${W}${T} → ${K}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!f.sourceHost)return new Response(`No upstream configured for ${W}`,{status:502});if(f.cleanUrls&&J.endsWith(".html")){let F=J.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:F}})}let{targetHost:B,targetPath:j}=Cz(J,f,w),z=f.changeOrigin?`http://${f.sourceHost}`:void 0,E=Y.body!=null&&Y.method!=="GET"&&Y.method!=="HEAD";try{return await qz({hostPort:B,method:Y.method,path:`${j}${U}`,reqHeaders:Y.headers,forwardedHost:W,originOverride:z,body:Y.body})}catch(F){if(F===hf)return G("request",`Upstream timeout for ${W}`,w),new Response("Gateway Timeout",{status:504});if(F===_1)return G("request",`Upstream pool saturated for ${W}`,w),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(F===EA||!E)try{let T=new Headers(Y.headers);if(T.set("host",B),T.set("x-forwarded-for","127.0.0.1"),T.set("x-forwarded-proto","https"),T.set("x-forwarded-host",W),z!==void 0)T.set("origin",z);return await fetch(`http://${B}${j}${U}`,{method:Y.method,headers:T,body:Y.body,redirect:"manual"})}catch(T){return G("request",`Proxy error for ${W}: ${T}`,w),new Response(`Proxy Error: ${T}`,{status:502})}return G("request",`Proxy error for ${W}: ${F}`,w),new Response(`Proxy Error: ${F}`,{status:502})}};return async(Y,X)=>{try{return await A(Y,X)}catch(J){return G("request",`Unhandled proxy handler error: ${J}`,w),new Response("Bad Gateway",{status:502})}}}function D1($){let w=new WeakMap;return{open(A){let{targetUrl:Y,forwardHeaders:X}=A.data,J;try{J=new WebSocket(Y,{headers:X})}catch(W){G("ws",`failed to open upstream ${Y}: ${W}`,$),A.close(1011,"upstream connect failed");return}J.binaryType="arraybuffer";let U={upstream:J,upstreamOpen:!1,pending:[]};w.set(A,U),J.addEventListener("open",()=>{U.upstreamOpen=!0;for(let W of U.pending)J.send(W);U.pending=[]}),J.addEventListener("message",(W)=>{A.send(W.data)}),J.addEventListener("close",(W)=>{try{A.close(W.code||1000,W.reason||"")}catch{}}),J.addEventListener("error",()=>{G("ws",`upstream error for ${Y}`,$);try{A.close(1011,"upstream error")}catch{}})},message(A,Y){let X=w.get(A);if(!X)return;let J=typeof Y==="string"?Y:new Uint8Array(Y);if(X.upstreamOpen)X.upstream.send(J);else X.pending.push(J)},close(A,Y,X){let J=w.get(A);if(!J)return;w.delete(A);try{J.upstream.close(Y||1000,X||"")}catch{}}}}var VN;var oX=F0(()=>{Iz();KA();f0();VN=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function TA($){return $.startsWith("*.")}function eX($,w){if(!TA(w))return!1;let A=w.slice(1);return $.length>A.length&&$.endsWith(A)}function Z1($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function SN($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function x1($){let w=new Map;for(let Y of $){let X=Z1(Y.path),J=w.get(Y.host);if(!J)J=new Map,w.set(Y.host,J);J.set(X,Y.route)}let A=new Map;for(let[Y,X]of w){let J=[];for(let[U,W]of X)J.push({path:U,route:W});J.sort((U,W)=>W.path.length-U.path.length),A.set(Y,J)}return A}function _N($,w){let A=$.get(w);if(A!==void 0)return A;let Y,X=-1;for(let[J,U]of $){if(!TA(J))continue;if(eX(w,J)){let W=J.length-1;if(W>X)X=W,Y=U}}return Y}function P1($,w,A){let Y=_N($,w);if(!Y)return;for(let X of Y)if(SN(A,X.path))return X.route;return}var $8=()=>{};import*as HA from"node:fs/promises";import*as Vf from"node:path";function kN($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function DN($,w,A,Y){try{let[X,J]=await Promise.all([HA.readFile(w,"utf8"),HA.readFile(A,"utf8")]);return{serverName:$,cert:X,key:J}}catch(X){return G("sni",`skipping ${$}: ${X.message}`,Y),null}}async function w8($,w){let A=new Map;if($.certsDir){let X=[];try{X=await HA.readdir($.certsDir)}catch(J){G("sni",`certsDir read failed (${$.certsDir}): ${J.message}`,w)}for(let J of X){let U=kN(J);if(!U)continue;let W=J.slice(0,-4);A.set(U,{certPath:Vf.join($.certsDir,J),keyPath:Vf.join($.certsDir,`${W}.key`)})}}if($.domains)for(let[X,J]of Object.entries($.domains))A.set(X,J);let Y=[];for(let[X,J]of A){let U=await DN(X,J.certPath,J.keyPath,w);if(U)Y.push(U)}return Y}var Lf=F0(()=>{f0()});import*as Tw from"node:fs/promises";import*as Of from"node:path";function xN($,w){if(!w||w.length===0)return!1;return w.some((A)=>{let Y=A.startsWith(".")?A.slice(1):A;return $===Y||$.endsWith(`.${Y}`)})}function PN($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class NA{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??JX,this.issuer=$.issuer??fU,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??ZN;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!PN($))return!1;if(xN($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return G("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;let w=this.inFlight.get($);if(w)return w;let A=this.negativeCache.get($);if(A!==void 0&&Date.now()<A)return G("on-demand",`${$} negatively cached for ${A-Date.now()}ms`,this.verbose),!1;let Y=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,Y),Y}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return G("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),!1;try{G("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let A={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,A),this.negativeCache.delete($),G("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.negativeCache.set($,Date.now()+this.negativeCacheMs),G("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}async loadFromDisk($){let{certPath:w,keyPath:A}=this.pathsFor($);try{let[Y,X]=await Promise.all([Tw.readFile(w,"utf8"),Tw.readFile(A,"utf8")]),J={serverName:$,cert:Y,key:X};return this.certs.set($,J),G("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:Of.join(this.certsDir,`${$}.crt`),keyPath:Of.join(this.certsDir,`${$}.key`)}}async persist($,w,A){await Tw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:Y,keyPath:X}=this.pathsFor($);await Promise.all([Tw.writeFile(Y,w,"utf8"),Tw.writeFile(X,A,{encoding:"utf8",mode:384})])}}var ZN=60000;var Qf=F0(()=>{CU();f0()});import*as A8 from"node:fs";import*as n0 from"node:fs/promises";import{homedir as bN}from"node:os";import*as Sf from"node:path";import*as Y8 from"node:process";function Hw(){return Sf.join(bN(),".stacks","rpx","registry.d")}function RA($){return typeof $==="string"&&$.length>0&&$.length<=128&&uN.test($)}function _f($,w){if(!RA(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return Sf.join($,`${w}.json`)}function a0($){if(!Number.isInteger($)||$<=0)return!1;try{return Y8.kill($,0),!0}catch(w){return w.code==="EPERM"}}function Vz($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&RA(w.id)&&(Y||X)&&typeof w.to==="string"&&w.to.length>0&&J&&A&&typeof w.createdAt==="string"}async function iN($){await n0.mkdir($,{recursive:!0})}async function Lz($,w=Hw(),A){if(!Vz($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await iN(w);let Y=_f(w,$.id),X=`${Y}.tmp.${Y8.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await n0.writeFile(X,J,{encoding:"utf8",mode:420}),await n0.rename(X,Y),G("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await n0.unlink(X).catch(()=>{}),U}}async function kf($,w=Hw(),A){let Y=_f(w,$);try{await n0.unlink(Y),G("registry",`removed entry ${$}`,A)}catch(X){if(X.code!=="ENOENT")throw X}}async function cN($,w=Hw(),A){let Y=_f(w,$);try{let X=await n0.readFile(Y,"utf8"),J=JSON.parse(X);if(!Vz(J))return G("registry",`entry ${$} failed validation, removing`,A),await n0.unlink(Y).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return G("registry",`entry ${$} has invalid JSON, removing`,A),await n0.unlink(Y).catch(()=>{}),null;throw X}}async function s$($=Hw(),w){let A;try{A=await n0.readdir($)}catch(X){if(X.code==="ENOENT")return[];throw X}let Y=[];for(let X of A){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!RA(J))continue;let U=await cN(J,$,w);if(U)Y.push(U)}return Y}async function b1($=Hw(),w){let A=await s$($,w),Y=0;for(let X of A){if(X.pid===void 0)continue;if(!a0(X.pid))G("registry",`GC: pid ${X.pid} for ${X.id} is dead, removing`,w),await kf(X.id,$,w).catch(()=>{}),Y++}return Y}function qA($,w={}){let A=w.dir??Hw(),Y=w.debounceMs??100,X=w.pollMs??Math.max(Y*2,250),J=w.verbose;A8.mkdirSync(A,{recursive:!0});let U=null,W=!1,f=null,B=!1,j=(H)=>{return JSON.stringify(H.map((N)=>({id:N.id,from:N.from,to:N.to,path:N.path,pid:N.pid,pathRewrites:N.pathRewrites,cleanUrls:N.cleanUrls,changeOrigin:N.changeOrigin,static:N.static})).sort((N,R)=>N.id.localeCompare(R.id)))},z=()=>{if(U=null,W)return;s$(A,J).then((H)=>{return f=j(H),$(H)}).catch((H)=>{G("registry",`watcher onChange failed: ${H}`,J)})},E=()=>{if(W)return;if(U)clearTimeout(U);U=setTimeout(z,Y)},T=setInterval(()=>{if(W||B)return;B=!0,s$(A,J).then((H)=>{if(j(H)!==f)E()}).catch((H)=>{G("registry",`watcher poll failed: ${H}`,J)}).finally(()=>{B=!1})},X),K=A8.watch(A,{persistent:!0},(H,N)=>{if(N&&/\.tmp\.\d+\.\d+$/.test(N))return;E()});return K.on("error",(H)=>{G("registry",`watcher error: ${H}`,J)}),E(),{close:()=>{if(W=!0,U)clearTimeout(U);clearInterval(T),K.close()}}}var uN;var MA=F0(()=>{f0();uN=/^[a-zA-Z0-9._-]+$/});import{spawn as vN}from"node:child_process";import*as o$ from"node:fs/promises";import{homedir as mN}from"node:os";import*as IA from"node:path";import*as L0 from"node:process";function e$(){return IA.join(mN(),".stacks","rpx")}function Qz($=e$()){return IA.join($,"daemon.pid")}async function Oz($=e$()){try{let w=await o$.readFile(Qz($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function dN($=e$()){await o$.unlink(Qz($)).catch(()=>{})}function gN(){let $=L0.execPath,w=IA.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&L0.argv[1])return[$,L0.argv[1],"daemon:start"];return[$,"daemon:start"]}async function Sz($={}){let w=$.rpxDir??e$(),A=$.verbose??!1;await $w({rpxDir:w,verbose:A}).catch((j)=>{G("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,A)});let Y=await Oz(w);if(Y!==null&&a0(Y))return G("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)G("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await dN(w);await o$.mkdir(w,{recursive:!0});let X=$.spawnCommand??gN();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");G("daemon",`spawning daemon: ${X.join(" ")}`,A);let J=vN(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??L0.cwd(),env:$.spawnEnv?{...L0.env,...$.spawnEnv}:L0.env});J.unref();let U=null;J.once("error",(j)=>{U=j});let W=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let j=await Oz(w);if(j!==null&&a0(j))return G("daemon",`daemon registered with pid=${j}`,A),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,f))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var Df=F0(()=>{fw();aX();oX();$8();Lf();Qf();KA();MA();u1();f0()});import*as Rw from"node:fs/promises";import{homedir as nN}from"node:os";import*as Zf from"node:path";function kz(){return Zf.join(nN(),".stacks","rpx")}function xf($=kz()){return Zf.join($,lN)}async function J8($=kz()){try{let w=await Rw.readFile(xf($),"utf8"),A=JSON.parse(w);if(A.version!==X8||!Array.isArray(A.resolvers))return null;return{version:X8,resolvers:A.resolvers.filter((Y)=>typeof Y==="string"),domains:Array.isArray(A.domains)?A.domains.filter((Y)=>typeof Y==="string"):[],ownerPid:typeof A.ownerPid==="number"?A.ownerPid:null,updatedAt:typeof A.updatedAt==="string"?A.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function Dz($,w){await Rw.mkdir($,{recursive:!0}),await Rw.writeFile(xf($),`${JSON.stringify(w,null,2)}
216
- `,"utf8")}async function Pf($){await Rw.rm(xf($),{force:!0})}function Zz($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;return w}function pN($){let w=Zz($);if(!w)return null;let A=w.split(".");if(A.length<2)return null;return A.slice(-2).join(".")}function bf($){let w=new Set;for(let A of $){let Y=pN(A);if(Y)w.add(Y)}return Array.from(w).sort()}function uf($){let w=new Set;for(let A of $){let Y=Zz(A);if(Y)w.add(Y)}return Array.from(w).sort()}var X8=1,lN="dns-state.json",_z;var xz=F0(()=>{_z=["com","test","dev","app","page","local","localhost","example","invalid"]});var f8={};BW(f8,{tearDownDevelopmentDns:()=>Nw,syncDevelopmentDnsFromRegistry:()=>kw,stopDnsServer:()=>cf,startDnsServer:()=>dz,setupResolver:()=>YR,setupDevelopmentDns:()=>gf,resolverFilePath:()=>i1,removeResolver:()=>JR,removeLegacyTldResolvers:()=>df,reconcileStaleDevelopmentDns:()=>$w,isRpxDevelopmentDnsAnswering:()=>gz,isDnsServerRunning:()=>sN,contentLooksLikeRpxResolver:()=>nz,RPX_RESOLVER_MARKER:()=>iz,DNS_PORT:()=>CA});import Pz from"node:dgram";import*as bz from"node:fs/promises";import*as uz from"node:path";import*as ww from"node:process";function vz($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function mz($,w){let A=[],Y=w;while(!0){let X=$[Y];if(X===0){Y++;break}if((X&192)===192){let J=$.readUInt16BE(Y)&16383,{name:U}=mz($,J);A.push(U),Y+=2;break}Y++,A.push($.subarray(Y,Y+X).toString("ascii")),Y+=X}return{name:A.join("."),newOffset:Y}}function tN($,w){let{name:A,newOffset:Y}=mz($,w),X=$.readUInt16BE(Y),J=$.readUInt16BE(Y+2);return{question:{name:A,type:X,class:J},newOffset:Y+4}}function yA($){let w=$.split("."),A=[];for(let Y of w)A.push(Buffer.from([Y.length])),A.push(Buffer.from(Y,"ascii"));return A.push(Buffer.from([0])),Buffer.concat(A)}function rN($,w,A){let Y=[],X=Buffer.alloc(12);X.writeUInt16BE($,0),X.writeUInt16BE(33152,2),X.writeUInt16BE(1,4),X.writeUInt16BE(1,6),X.writeUInt16BE(0,8),X.writeUInt16BE(0,10),Y.push(X),Y.push(yA(w.name));let J=Buffer.alloc(4);J.writeUInt16BE(w.type,0),J.writeUInt16BE(w.class,2),Y.push(J),Y.push(yA(w.name));let U=Buffer.alloc(10);if(U.writeUInt16BE(w.type,0),U.writeUInt16BE(1,2),U.writeUInt32BE(300,4),w.type===1){U.writeUInt16BE(4,8),Y.push(U);let W=A.split(".").map((f)=>Number.parseInt(f,10));Y.push(Buffer.from(W))}else if(w.type===28)U.writeUInt16BE(16,8),Y.push(U),Y.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,yA(w.name),J]);return Buffer.concat(Y)}function aN($,w){let A=[],Y=Buffer.alloc(12);Y.writeUInt16BE($,0),Y.writeUInt16BE(33155,2),Y.writeUInt16BE(1,4),Y.writeUInt16BE(0,6),Y.writeUInt16BE(0,8),Y.writeUInt16BE(0,10),A.push(Y),A.push(yA(w.name));let X=Buffer.alloc(4);return X.writeUInt16BE(w.type,0),X.writeUInt16BE(w.class,2),A.push(X),Buffer.concat(A)}async function dz($,w){if(ww.platform!=="darwin")return!1;let A=uf($);if(A.length===0)return!1;if(s0){for(let Y of A)U8.add(Y);return G("dns","DNS server already running — merged domains",w),!0}return U8=new Set(A),new Promise((Y)=>{s0=Pz.createSocket("udp4"),s0.on("error",(X)=>{G("dns",`DNS server error: ${X.message}`,w),s0?.close(),s0=null,Y(!1)}),s0.on("message",(X,J)=>{try{let U=vz(X),{question:W}=tN(X,12);G("dns",`Query for ${W.name} type ${W.type} from ${J.address}`,w);let f=W.name.toLowerCase(),B=!1;for(let z of U8)if(f===z||f.endsWith(`.${z}`)){B=!0;break}let j;if(B&&(W.type===1||W.type===28))j=rN(U.id,W,"127.0.0.1"),G("dns",`Responding with localhost for ${W.name}`,w);else j=aN(U.id,W),G("dns",`NXDOMAIN for ${W.name}`,w);s0?.send(j,J.port,J.address)}catch(U){G("dns",`Error processing DNS query: ${U}`,w)}}),s0.on("listening",()=>{let X=s0?.address();G("dns",`DNS server listening on ${X?.address}:${X?.port}`,w),Y(!0)});try{s0.bind(CA,"127.0.0.1")}catch(X){G("dns",`Failed to bind DNS server: ${X}`,w),Y(!1)}})}function cf($){if(s0)G("dns","Stopping DNS server",$),s0.close(),s0=null,U8=new Set}function sN(){return s0!==null}async function gz($,w=500){let A=$.trim().toLowerCase().replace(/\.$/,"");if(!A)return!1;return new Promise((Y)=>{let X=Pz.createSocket("udp4"),J=setTimeout(()=>{X.close(),Y(!1)},w);X.on("message",(W)=>{clearTimeout(J),X.close();try{let f=vz(W);Y(f.ancount>0)}catch{Y(!1)}}),X.on("error",()=>{clearTimeout(J),X.close(),Y(!1)});let U=oN(A,1);X.send(U,CA,"127.0.0.1",(W)=>{if(W)clearTimeout(J),X.close(),Y(!1)})})}function oN($,w){let A=Buffer.alloc(12);A.writeUInt16BE(1,0),A.writeUInt16BE(256,2),A.writeUInt16BE(1,4);let Y=Buffer.concat([yA($),Buffer.from([0,w,0,1])]);return Buffer.concat([A,Y])}function eN(){return`${iz}
217
+ `,kN.encode(W)}async function dN($){let w=$.getReader(),Y=[],A=0;for(;;){let{done:J,value:W}=await w.read();if(J)break;if(W){if(A+=W.length,A>h2)return w.cancel().catch(()=>{}),null;Y.push(W)}}if(Y.length===1)return Y[0];let U=new Uint8Array(A),X=0;for(let J of Y)U.set(J,X),X+=J.length;return U}var qN,HY,AX,RN,uf,kw,h2=1048576,bf=30000,LN=16384,V2=262144,QN=2097152,ON=524288,SN=8192,_N=4096,kN,L2,DN,y2;var k2=j0(()=>{({connect:qN}=Bun),HY=Symbol("rpx.pool.fallback"),AX=Symbol("rpx.pool.stale"),RN=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);uf=Symbol("rpx.pool.timeout"),kw=Symbol("rpx.pool.busy");kN=new TextEncoder,L2=new TextDecoder,DN=new Set(["host","connection","keep-alive","proxy-connection","transfer-encoding","x-forwarded-for","x-forwarded-proto","x-forwarded-host"]);y2=new Map});import*as B$ from"node:path";function NY($,w){if(typeof $==="string")return{dir:$,spa:!1,pathRewriteStyle:"directory",maxAge:0,cleanUrls:w};return{dir:$.dir,spa:$.spa??!1,pathRewriteStyle:$.pathRewriteStyle??"directory",maxAge:$.maxAge??0,cleanUrls:w}}function lN($){let w=B$.extname($).toLowerCase();return gN[w]??"application/octet-stream"}function nN($){let w;try{w=decodeURIComponent($)}catch{return null}if(w.includes("\x00")||w.includes("\\"))return null;let Y=B$.posix.normalize(`/${w}`);if(Y.includes(".."))return null;return Y.replace(/^\/+/,"")}function pN($,w){let Y=nN($);if(Y===null)return null;let A=B$.posix.extname(Y);if(w.cleanUrls&&A===".html"){let U=$.replace(/\/index\.html$/i,"/").replace(/\.html$/i,"");return{filePath:B$.join(w.dir,Y),redirectTo:U||"/"}}if(Y===""||$.endsWith("/"))return{filePath:B$.join(w.dir,Y,"index.html")};if(A!=="")return{filePath:B$.join(w.dir,Y)};if(w.pathRewriteStyle==="flat")return{filePath:B$.join(w.dir,`${Y}.html`)};return{filePath:B$.join(w.dir,Y,"index.html")}}async function D2($,w){let Y=pN($,w);if(!Y)return new Response("Forbidden",{status:403});if(Y.redirectTo)return new Response(null,{status:301,headers:{Location:Y.redirectTo}});let A=w.maxAge>0?`public, max-age=${w.maxAge}`:"no-cache",U=Bun.file(Y.filePath);if(await U.exists())return new Response(U,{status:200,headers:{"Content-Type":lN(Y.filePath),"Cache-Control":A}});if(w.spa){let X=B$.join(w.dir,"index.html"),J=Bun.file(X);if(await J.exists())return new Response(J,{status:200,headers:{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-cache"}})}return new Response("Not Found",{status:404})}var gN;var qY=j0(()=>{gN={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".map":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject",".txt":"text/plain; charset=utf-8",".xml":"application/xml; charset=utf-8",".pdf":"application/pdf",".wasm":"application/wasm",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav"}});function rN($){let w=$.headers.get("host")||"",Y=w.indexOf(":");return Y===-1?w:w.slice(0,Y)}function x2($,w){if(!w||w==="/")return $;if($===w)return"/";if($.startsWith(`${w}/`)){let Y=$.slice(w.length);return Y===""?"/":Y}return $}function Z2($,w,Y){let A=w.sourceHost??"",X=w.stripBasePathPrefix??!1?x2($,w.basePath):$,J=Vf(X,w.pathRewrites);if(J)A=J.targetHost,X=J.targetPath,E("request",`Path rewrite: ${$} → ${A}${X}`,Y);return{targetHost:A,targetPath:X}}function aN($){let w=$.indexOf("://"),Y=w===-1?$.indexOf("/"):$.indexOf("/",w+3);if(Y===-1)return{pathname:"/",search:""};let A=$.indexOf("?",Y);if(A===-1)return{pathname:$.slice(Y),search:""};return{pathname:$.slice(Y,A),search:$.slice(A)}}function S1($,w){let Y=async(A,U)=>{let{pathname:X,search:J}=aN(A.url),W=rN(A),f=$(W,X);if(!f)return E("request",`No route found for host: ${W}`,w),new Response(`No proxy configured for ${W}`,{status:404});if(f.static){let T=f.stripBasePathPrefix??!0?x2(X,f.basePath):X;return D2(T,f.static)}if(A.headers.get("upgrade")?.toLowerCase()==="websocket"){if(!U||!f.sourceHost)return new Response("WebSocket upgrade not supported here",{status:400});let{targetHost:F,targetPath:T}=Z2(X,f,w),K=`ws://${F}${T}${J}`,H={};for(let[I,h]of A.headers)if(!tN.has(I.toLowerCase())&&I.toLowerCase()!=="host")H[I]=h;H.host=F,H["x-forwarded-for"]="127.0.0.1",H["x-forwarded-proto"]="https",H["x-forwarded-host"]=W;let q={targetUrl:K,forwardHeaders:H};if(U.upgrade(A,{data:q})){E("ws",`upgraded ${W}${T} → ${K}`,w);return}return new Response("WebSocket upgrade failed",{status:400})}if(!f.sourceHost)return new Response(`No upstream configured for ${W}`,{status:502});if(f.cleanUrls&&X.endsWith(".html")){let F=X.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:F}})}let{targetHost:B,targetPath:j}=Z2(X,f,w),z=f.changeOrigin?`http://${f.sourceHost}`:void 0,G=A.body!=null&&A.method!=="GET"&&A.method!=="HEAD";try{return await S2({hostPort:B,method:A.method,path:`${j}${J}`,reqHeaders:A.headers,forwardedHost:W,originOverride:z,body:A.body})}catch(F){if(F===uf)return E("request",`Upstream timeout for ${W}`,w),new Response("Gateway Timeout",{status:504});if(F===kw)return E("request",`Upstream pool saturated for ${W}`,w),new Response("Service Unavailable",{status:503,headers:{"retry-after":"1"}});if(F===HY||!G)try{let T=new Headers(A.headers);if(T.set("host",B),T.set("x-forwarded-for","127.0.0.1"),T.set("x-forwarded-proto","https"),T.set("x-forwarded-host",W),z!==void 0)T.set("origin",z);return await fetch(`http://${B}${j}${J}`,{method:A.method,headers:T,body:A.body,redirect:"manual"})}catch(T){return E("request",`Proxy error for ${W}: ${T}`,w),new Response(`Proxy Error: ${T}`,{status:502})}return E("request",`Proxy error for ${W}: ${F}`,w),new Response(`Proxy Error: ${F}`,{status:502})}};return async(A,U)=>{try{return await Y(A,U)}catch(X){return E("request",`Unhandled proxy handler error: ${X}`,w),new Response("Bad Gateway",{status:502})}}}function _1($){let w=new WeakMap;return{open(Y){let{targetUrl:A,forwardHeaders:U}=Y.data,X;try{X=new WebSocket(A,{headers:U})}catch(W){E("ws",`failed to open upstream ${A}: ${W}`,$),Y.close(1011,"upstream connect failed");return}X.binaryType="arraybuffer";let J={upstream:X,upstreamOpen:!1,pending:[]};w.set(Y,J),X.addEventListener("open",()=>{J.upstreamOpen=!0;for(let W of J.pending)X.send(W);J.pending=[]}),X.addEventListener("message",(W)=>{Y.send(W.data)}),X.addEventListener("close",(W)=>{try{Y.close(W.code||1000,W.reason||"")}catch{}}),X.addEventListener("error",()=>{E("ws",`upstream error for ${A}`,$);try{Y.close(1011,"upstream error")}catch{}})},message(Y,A){let U=w.get(Y);if(!U)return;let X=typeof A==="string"?A:new Uint8Array(A);if(U.upstreamOpen)U.upstream.send(X);else U.pending.push(X)},close(Y,A,U){let X=w.get(Y);if(!X)return;w.delete(Y);try{X.upstream.close(A||1000,U||"")}catch{}}}}var tN;var UX=j0(()=>{k2();qY();f0();tN=new Set(["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade","sec-websocket-key","sec-websocket-version","sec-websocket-extensions"])});function RY($){return $.startsWith("*.")}function XX($,w){if(!RY(w))return!1;let Y=w.slice(1);return $.length>Y.length&&$.endsWith(Y)}function k1($){if(!$||$==="/")return"/";let w=$.trim();if(!w.startsWith("/"))w=`/${w}`;return w=w.replace(/\/+$/,""),w===""?"/":w}function oN($,w){if(w==="/")return!0;if($===w)return!0;return $.startsWith(`${w}/`)}function D1($){let w=new Map;for(let A of $){let U=k1(A.path),X=w.get(A.host);if(!X)X=new Map,w.set(A.host,X);X.set(U,A.route)}let Y=new Map;for(let[A,U]of w){let X=[];for(let[J,W]of U)X.push({path:J,route:W});X.sort((J,W)=>W.path.length-J.path.length),Y.set(A,X)}return Y}function eN($,w){let Y=$.get(w);if(Y!==void 0)return Y;let A,U=-1;for(let[X,J]of $){if(!RY(X))continue;if(XX(w,X)){let W=X.length-1;if(W>U)U=W,A=J}}return A}function Z1($,w,Y){let A=eN($,w);if(!A)return;for(let U of A)if(oN(Y,U.path))return U.route;return}var JX=()=>{};import*as MY from"node:fs/promises";import*as cf from"node:path";function $q($){if(!$.endsWith(".crt"))return null;let w=$.slice(0,-4);if(w.length===0)return null;if(w.startsWith("_wildcard."))return`*.${w.slice(10)}`;return w}async function wq($,w,Y,A){try{let[U,X]=await Promise.all([MY.readFile(w,"utf8"),MY.readFile(Y,"utf8")]);return{serverName:$,cert:U,key:X}}catch(U){return E("sni",`skipping ${$}: ${U.message}`,A),null}}async function x1($,w){let Y=new Map;if($.certsDir){let U=[];try{U=await MY.readdir($.certsDir)}catch(X){E("sni",`certsDir read failed (${$.certsDir}): ${X.message}`,w)}for(let X of U){let J=$q(X);if(!J)continue;let W=X.slice(0,-4);Y.set(J,{certPath:cf.join($.certsDir,X),keyPath:cf.join($.certsDir,`${W}.key`)})}}if($.domains)for(let[U,X]of Object.entries($.domains))Y.set(U,X);let A=[];for(let[U,X]of Y){let J=await wq(U,X.certPath,X.keyPath,w);if(J)A.push(J)}return A}var fX=j0(()=>{f0()});import*as Tw from"node:fs/promises";import*as vf from"node:path";function Aq($,w){if(!w||w.length===0)return!1;return w.some((Y)=>{let A=Y.startsWith(".")?Y.slice(1):Y;return $===A||$.endsWith(`.${A}`)})}function b2($){if(!$||$.length>253)return!1;if($.includes("/")||$.includes(":")||$.includes(" "))return!1;if($.startsWith("*"))return!1;return/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test($)}class IY{config;certsDir;onCertAdded;http01Store;issuer;verbose;negativeCacheMs;certs=new Map;inFlight=new Map;negativeCache=new Map;constructor($){this.config=$.config,this.certsDir=$.certsDir,this.onCertAdded=$.onCertAdded,this.http01Store=$.http01Store??WU,this.issuer=$.issuer??HJ,this.verbose=$.verbose??!1,this.negativeCacheMs=$.negativeCacheMs??Yq;for(let w of $.initial??[])this.certs.set(w.serverName,w)}get challengeStore(){return this.http01Store}sniEntries(){return Array.from(this.certs.values())}hasCert($){return this.certs.has($)}async isApproved($){if(!b2($))return!1;if(Aq($,this.config.allowedSuffixes))return!0;if(this.config.ask)try{return await this.config.ask($)}catch(w){return E("on-demand",`ask(${$}) threw: ${w.message}`,this.verbose),!1}return!1}async ensureCert($){if(!this.config.enabled)return!1;if(this.certs.has($))return!0;if(!b2($))return!1;let w=this.inFlight.get($);if(w)return w;let Y=this.negativeCache.get($);if(Y!==void 0&&Date.now()<Y)return E("on-demand",`${$} negatively cached for ${Y-Date.now()}ms`,this.verbose),!1;let A=this.issue($).finally(()=>{this.inFlight.delete($)});return this.inFlight.set($,A),A}async issue($){if(this.certs.has($))return!0;if(await this.loadFromDisk($))return!0;if(!await this.isApproved($))return E("on-demand",`refused issuance for ${$} (not approved)`,this.verbose),this.cacheNegative($),!1;try{E("on-demand",`issuing cert for ${$} (staging=${this.config.staging??!1})`,this.verbose);let w=await this.issuer({domains:[$],method:"http-01",http01Store:this.http01Store,email:this.config.email,staging:this.config.staging});await this.persist($,w.fullChainPem,w.keyPem);let Y={serverName:$,cert:w.fullChainPem,key:w.keyPem};return this.certs.set($,Y),this.negativeCache.delete($),E("on-demand",`issued + installed cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch(w){return this.cacheNegative($),E("on-demand",`issuance for ${$} failed: ${w.message}`,this.verbose),!1}}cacheNegative($){if(this.negativeCache.size>=P2){let w=Date.now();for(let[Y,A]of this.negativeCache)if(A<=w)this.negativeCache.delete(Y);if(this.negativeCache.size>=P2){let Y=this.negativeCache.keys().next().value;if(Y!==void 0)this.negativeCache.delete(Y)}}this.negativeCache.set($,Date.now()+this.negativeCacheMs)}async loadFromDisk($){let{certPath:w,keyPath:Y}=this.pathsFor($);try{let[A,U]=await Promise.all([Tw.readFile(w,"utf8"),Tw.readFile(Y,"utf8")]),X={serverName:$,cert:A,key:U};return this.certs.set($,X),E("on-demand",`adopted existing on-disk cert for ${$}`,this.verbose),await this.onCertAdded?.(this.sniEntries()),!0}catch{return!1}}pathsFor($){return{certPath:vf.join(this.certsDir,`${$}.crt`),keyPath:vf.join(this.certsDir,`${$}.key`)}}async persist($,w,Y){await Tw.mkdir(this.certsDir,{recursive:!0}).catch(()=>{});let{certPath:A,keyPath:U}=this.pathsFor($);await Promise.all([Tw.writeFile(A,w,"utf8"),Tw.writeFile(U,Y,{encoding:"utf8",mode:384})])}}var Yq=60000,P2=4096;var mf=j0(()=>{TU();f0()});import*as WX from"node:fs";import*as g0 from"node:fs/promises";import{homedir as Uq}from"node:os";import*as df from"node:path";import*as BX from"node:process";function Hw(){return df.join(Uq(),".stacks","rpx","registry.d")}function yY($){return typeof $==="string"&&$.length>0&&$.length<=128&&Xq.test($)}function gf($,w){if(!yY(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return df.join($,`${w}.json`)}function p0($){if(!Number.isInteger($)||$<=0)return!1;try{return BX.kill($,0),!0}catch(w){return w.code==="EPERM"}}function u2($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0,U=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&yY(w.id)&&(A||U)&&typeof w.to==="string"&&w.to.length>0&&X&&Y&&typeof w.createdAt==="string"}async function Jq($){await g0.mkdir($,{recursive:!0})}async function i2($,w=Hw(),Y){if(!u2($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await Jq(w);let A=gf(w,$.id),U=`${A}.tmp.${BX.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await g0.writeFile(U,X,{encoding:"utf8",mode:420}),await g0.rename(U,A),E("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(J){throw await g0.unlink(U).catch(()=>{}),J}}async function lf($,w=Hw(),Y){let A=gf(w,$);try{await g0.unlink(A),E("registry",`removed entry ${$}`,Y)}catch(U){if(U.code!=="ENOENT")throw U}}async function fq($,w=Hw(),Y){let A=gf(w,$);try{let U=await g0.readFile(A,"utf8"),X=JSON.parse(U);if(!u2(X))return E("registry",`entry ${$} failed validation, removing`,Y),await g0.unlink(A).catch(()=>{}),null;return X}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return E("registry",`entry ${$} has invalid JSON, removing`,Y),await g0.unlink(A).catch(()=>{}),null;throw U}}async function s$($=Hw(),w){let Y;try{Y=await g0.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let A=[];for(let U of Y){if(!U.endsWith(".json"))continue;let X=U.slice(0,-5);if(!yY(X))continue;let J=await fq(X,$,w);if(J)A.push(J)}return A}async function P1($=Hw(),w){let Y=await s$($,w),A=0;for(let U of Y){if(U.pid===void 0)continue;if(!p0(U.pid))E("registry",`GC: pid ${U.pid} for ${U.id} is dead, removing`,w),await lf(U.id,$,w).catch(()=>{}),A++}return A}function CY($,w={}){let Y=w.dir??Hw(),A=w.debounceMs??100,U=w.pollMs??Math.max(A*2,250),X=w.verbose;WX.mkdirSync(Y,{recursive:!0});let J=null,W=!1,f=null,B=!1,j=(H)=>{return JSON.stringify(H.map((q)=>({id:q.id,from:q.from,to:q.to,path:q.path,pid:q.pid,pathRewrites:q.pathRewrites,cleanUrls:q.cleanUrls,changeOrigin:q.changeOrigin,static:q.static})).sort((q,M)=>q.id.localeCompare(M.id)))},z=()=>{if(J=null,W)return;s$(Y,X).then((H)=>{return f=j(H),$(H)}).catch((H)=>{E("registry",`watcher onChange failed: ${H}`,X)})},G=()=>{if(W)return;if(J)clearTimeout(J);J=setTimeout(z,A)},T=setInterval(()=>{if(W||B)return;B=!0,s$(Y,X).then((H)=>{if(j(H)!==f)G()}).catch((H)=>{E("registry",`watcher poll failed: ${H}`,X)}).finally(()=>{B=!1})},U),K=WX.watch(Y,{persistent:!0},(H,q)=>{if(q&&/\.tmp\.\d+\.\d+$/.test(q))return;G()});return K.on("error",(H)=>{E("registry",`watcher error: ${H}`,X)}),G(),{close:()=>{if(W=!0,J)clearTimeout(J);clearInterval(T),K.close()}}}var Xq;var hY=j0(()=>{f0();Xq=/^[a-zA-Z0-9._-]+$/});import{spawn as Wq}from"node:child_process";import*as o$ from"node:fs/promises";import{homedir as Bq}from"node:os";import*as VY from"node:path";import*as h0 from"node:process";function e$(){return VY.join(Bq(),".stacks","rpx")}function v2($=e$()){return VY.join($,"daemon.pid")}async function c2($=e$()){try{let w=await o$.readFile(v2($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function jq($=e$()){await o$.unlink(v2($)).catch(()=>{})}function zq(){let $=h0.execPath,w=VY.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&h0.argv[1])return[$,h0.argv[1],"daemon:start"];return[$,"daemon:start"]}async function m2($={}){let w=$.rpxDir??e$(),Y=$.verbose??!1;await $w({rpxDir:w,verbose:Y}).catch((j)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,Y)});let A=await c2(w);if(A!==null&&p0(A))return E("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)E("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await jq(w);await o$.mkdir(w,{recursive:!0});let U=$.spawnCommand??zq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${U.join(" ")}`,Y);let X=Wq(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??h0.cwd(),env:$.spawnEnv?{...h0.env,...$.spawnEnv}:h0.env});X.unref();let J=null;X.once("error",(j)=>{J=j});let W=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(J)throw J;let j=await c2(w);if(j!==null&&p0(j))return E("daemon",`daemon registered with pid=${j}`,Y),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,f))}if(J)throw J;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}var nf=j0(()=>{fw();YX();UX();JX();fX();mf();qY();hY();b1();f0()});import*as qw from"node:fs/promises";import{homedir as Fq}from"node:os";import*as pf from"node:path";function g2(){return pf.join(Fq(),".stacks","rpx")}function tf($=g2()){return pf.join($,Gq)}async function zX($=g2()){try{let w=await qw.readFile(tf($),"utf8"),Y=JSON.parse(w);if(Y.version!==jX||!Array.isArray(Y.resolvers))return null;return{version:jX,resolvers:Y.resolvers.filter((A)=>typeof A==="string"),domains:Array.isArray(Y.domains)?Y.domains.filter((A)=>typeof A==="string"):[],ownerPid:typeof Y.ownerPid==="number"?Y.ownerPid:null,updatedAt:typeof Y.updatedAt==="string"?Y.updatedAt:""}}catch(w){if(w.code==="ENOENT")return null;throw w}}async function l2($,w){await qw.mkdir($,{recursive:!0}),await qw.writeFile(tf($),`${JSON.stringify(w,null,2)}
218
+ `,"utf8")}async function rf($){await qw.rm(tf($),{force:!0})}function n2($){let w=$.trim().toLowerCase().replace(/\.$/,"");if(!w||w.includes("127.0.0.1"))return null;if(w==="localhost"||w.endsWith(".localhost"))return null;if(/^\d{1,3}(\.\d{1,3}){3}$/.test(w))return null;if(!/^[a-z0-9.-]+$/.test(w))return null;return w}function Eq($){let w=n2($);if(!w)return null;let Y=w.split(".");if(Y.length<2)return null;return Y.slice(-2).join(".")}function af($){let w=new Set;for(let Y of $){let A=Eq(Y);if(A)w.add(A)}return Array.from(w).sort()}function sf($){let w=new Set;for(let Y of $){let A=n2(Y);if(A)w.add(A)}return Array.from(w).sort()}var jX=1,Gq="dns-state.json",d2;var p2=j0(()=>{d2=["com","test","dev","app","page","local","localhost","example","invalid"]});var GX={};RW(GX,{tearDownDevelopmentDns:()=>Nw,syncDevelopmentDnsFromRegistry:()=>Dw,stopDnsServer:()=>of,startDnsServer:()=>wF,setupResolver:()=>Cq,setupDevelopmentDns:()=>YW,resolverFilePath:()=>u1,removeResolver:()=>Vq,removeLegacyTldResolvers:()=>wW,reconcileStaleDevelopmentDns:()=>$w,isRpxDevelopmentDnsAnswering:()=>YF,isDnsServerRunning:()=>Nq,contentLooksLikeRpxResolver:()=>AF,RPX_RESOLVER_MARKER:()=>s2,DNS_PORT:()=>QY});import t2 from"node:dgram";import*as r2 from"node:fs/promises";import*as a2 from"node:path";import*as ww from"node:process";function e2($){return{id:$.readUInt16BE(0),flags:$.readUInt16BE(2),qdcount:$.readUInt16BE(4),ancount:$.readUInt16BE(6),nscount:$.readUInt16BE(8),arcount:$.readUInt16BE(10)}}function $F($,w,Y=0){let A=[],U=w,X=0;while(!0){if(U>=$.length||++X>128)break;let J=$[U];if(J===0){U++;break}if((J&192)===192){if(U+1>=$.length||Y>=10)break;let W=$.readUInt16BE(U)&16383,{name:f}=$F($,W,Y+1);if(f)A.push(f);U+=2;break}if(U++,U+J>$.length)break;A.push($.subarray(U,U+J).toString("ascii")),U+=J}return{name:A.join("."),newOffset:U}}function Kq($,w){let{name:Y,newOffset:A}=$F($,w),U=$.readUInt16BE(A),X=$.readUInt16BE(A+2);return{question:{name:Y,type:U,class:X},newOffset:A+4}}function LY($){let w=$.split("."),Y=[];for(let A of w)Y.push(Buffer.from([A.length])),Y.push(Buffer.from(A,"ascii"));return Y.push(Buffer.from([0])),Buffer.concat(Y)}function Tq($,w,Y){let A=[],U=Buffer.alloc(12);U.writeUInt16BE($,0),U.writeUInt16BE(33152,2),U.writeUInt16BE(1,4),U.writeUInt16BE(1,6),U.writeUInt16BE(0,8),U.writeUInt16BE(0,10),A.push(U),A.push(LY(w.name));let X=Buffer.alloc(4);X.writeUInt16BE(w.type,0),X.writeUInt16BE(w.class,2),A.push(X),A.push(LY(w.name));let J=Buffer.alloc(10);if(J.writeUInt16BE(w.type,0),J.writeUInt16BE(1,2),J.writeUInt32BE(300,4),w.type===1){J.writeUInt16BE(4,8),A.push(J);let W=Y.split(".").map((f)=>Number.parseInt(f,10));A.push(Buffer.from(W))}else if(w.type===28)J.writeUInt16BE(16,8),A.push(J),A.push(Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]));else return U.writeUInt16BE(33155,2),U.writeUInt16BE(0,6),Buffer.concat([U,LY(w.name),X]);return Buffer.concat(A)}function Hq($,w){let Y=[],A=Buffer.alloc(12);A.writeUInt16BE($,0),A.writeUInt16BE(33155,2),A.writeUInt16BE(1,4),A.writeUInt16BE(0,6),A.writeUInt16BE(0,8),A.writeUInt16BE(0,10),Y.push(A),Y.push(LY(w.name));let U=Buffer.alloc(4);return U.writeUInt16BE(w.type,0),U.writeUInt16BE(w.class,2),Y.push(U),Buffer.concat(Y)}async function wF($,w){if(ww.platform!=="darwin")return!1;let Y=sf($);if(Y.length===0)return!1;if(t0){for(let A of Y)FX.add(A);return E("dns","DNS server already running — merged domains",w),!0}return FX=new Set(Y),new Promise((A)=>{t0=t2.createSocket("udp4"),t0.on("error",(U)=>{E("dns",`DNS server error: ${U.message}`,w),t0?.close(),t0=null,A(!1)}),t0.on("message",(U,X)=>{try{let J=e2(U),{question:W}=Kq(U,12);E("dns",`Query for ${W.name} type ${W.type} from ${X.address}`,w);let f=W.name.toLowerCase(),B=!1;for(let z of FX)if(f===z||f.endsWith(`.${z}`)){B=!0;break}let j;if(B&&(W.type===1||W.type===28))j=Tq(J.id,W,"127.0.0.1"),E("dns",`Responding with localhost for ${W.name}`,w);else j=Hq(J.id,W),E("dns",`NXDOMAIN for ${W.name}`,w);t0?.send(j,X.port,X.address)}catch(J){E("dns",`Error processing DNS query: ${J}`,w)}}),t0.on("listening",()=>{let U=t0?.address();E("dns",`DNS server listening on ${U?.address}:${U?.port}`,w),A(!0)});try{t0.bind(QY,"127.0.0.1")}catch(U){E("dns",`Failed to bind DNS server: ${U}`,w),A(!1)}})}function of($){if(t0)E("dns","Stopping DNS server",$),t0.close(),t0=null,FX=new Set}function Nq(){return t0!==null}async function YF($,w=500){let Y=$.trim().toLowerCase().replace(/\.$/,"");if(!Y)return!1;return new Promise((A)=>{let U=t2.createSocket("udp4"),X=setTimeout(()=>{U.close(),A(!1)},w);U.on("message",(W)=>{clearTimeout(X),U.close();try{let f=e2(W);A(f.ancount>0)}catch{A(!1)}}),U.on("error",()=>{clearTimeout(X),U.close(),A(!1)});let J=qq(Y,1);U.send(J,QY,"127.0.0.1",(W)=>{if(W)clearTimeout(X),U.close(),A(!1)})})}function qq($,w){let Y=Buffer.alloc(12);Y.writeUInt16BE(1,0),Y.writeUInt16BE(256,2),Y.writeUInt16BE(1,4);let A=Buffer.concat([LY($),Buffer.from([0,w,0,1])]);return Buffer.concat([Y,A])}function Rq(){return`${s2}
217
219
  nameserver 127.0.0.1
218
- port ${CA}
219
- `}function i1($){return uz.join(cz,$)}function nz($){return $.includes("127.0.0.1")&&$.includes(String(CA))}async function $R($){try{return await bz.readFile(i1($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function vf($){if(ww.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:A,isProcessElevated:Y}=await Promise.resolve().then(() => (f0(),h1));if(!Y()&&!A()){G("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),G("dns","DNS cache flushed",$)}catch(X){G("dns",`Could not flush DNS cache: ${X}`,$)}}async function wR($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (f0(),h1)),Y=eN().replace(/\n/g,"\\n"),X=`bash -c 'mkdir -p ${cz} && printf "%b" "${Y}" > ${i1($)}'`;A(X),G("dns",`Created ${i1($)}`,w)}async function AR($,w){let{execSudoSync:A}=await Promise.resolve().then(() => (f0(),h1));A(`rm -f ${i1($)}`),G("dns",`Removed ${i1($)}`,w)}async function YR($,w){return gf({domains:w??[],verbose:$})}async function XR($,w){if(ww.platform!=="darwin")return!0;let{getSudoPassword:A,isProcessElevated:Y}=await Promise.resolve().then(() => (f0(),h1));if(!Y()&&!A())return G("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let X of $)await wR(X,w);return await vf(w),!0}catch(X){return G("dns",`Failed to create resolver file: ${X}`,w),!1}}async function mf($,w){if(ww.platform!=="darwin")return;let{getSudoPassword:A,isProcessElevated:Y}=await Promise.resolve().then(() => (f0(),h1));if(!Y()&&!A())return;try{for(let X of $)await AR(X,w);await vf(w)}catch(X){G("dns",`Failed to remove resolver files: ${X}`,w)}}async function df($){if(ww.platform!=="darwin")return[];let w=[];for(let A of _z){let Y=await $R(A);if(Y&&nz(Y))await mf([A],$),w.push(A)}return w}async function gf($){let w=$.rpxDir??e$(),A=uf($.domains);if(A.length===0)return!1;let Y=bf(A),X=await dz(A,$.verbose);if(!X){let W=A[0];if(W&&await gz(W))X=!0;else G("dns","Dev DNS server not available on 127.0.0.1:15353",$.verbose)}if(!X)return!1;if(!await XR(Y,$.verbose))return!1;let U={version:X8,resolvers:Y,domains:A,ownerPid:$.ownerPid??ww.pid,updatedAt:new Date().toISOString()};return await Dz(w,U),!0}async function kw($,w={}){let A=$.map((f)=>f.to).filter(Boolean),Y=w.rpxDir??e$(),X=bf(A),W=((await J8(Y))?.resolvers??[]).filter((f)=>!X.includes(f));if(W.length>0)await mf(W,w.verbose);if(X.length===0){cf(w.verbose),await Pf(Y);return}await gf({domains:A,rpxDir:Y,verbose:w.verbose,ownerPid:w.ownerPid??ww.pid})}async function Nw($={}){let w=$.rpxDir??e$();cf($.verbose);let Y=(await J8(w))?.resolvers??[];await mf(Y,$.verbose),await df($.verbose),await Pf(w)}async function JR($){await Nw({verbose:$})}async function $w($={}){let w=$.rpxDir??e$(),A=await J8(w),Y=A?.ownerPid!=null&&a0(A.ownerPid);if(A&&!Y){G("dns",`reconcile: owner pid ${A.ownerPid} is gone — tearing down DNS`,$.verbose),await Nw($);return}let X=await df($.verbose);if(X.length>0)G("dns",`reconcile: removed legacy TLD resolvers: ${X.join(", ")}`,$.verbose);await vf($.verbose)}var CA=15353,iz="# managed-by: rpx",cz="/etc/resolver",s0=null,U8;var u1=F0(()=>{Df();xz();MA();f0();U8=new Set});import{dirname as DR,join as ZR}from"path";import*as p0 from"process";import{fileURLToPath as xR}from"url";import{existsSync as _F}from"node:fs";import q8 from"node:fs/promises";import jW from"node:os";import M8 from"node:path";import yw from"node:process";import{EventEmitter as kF}from"node:events";import Yw from"node:process";import zW from"node:process";import h8 from"node:process";import ZA from"node:process";import g1 from"node:process";import GW from"node:tty";import RE,{stdin as wq,stdout as Aq}from"node:process";import TW,{stdin as IE,stdout as yE}from"node:process";import CE from"node:readline";class NW{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=jW.homedir(),w=M8.join($,".config","clapp");this.configPath=M8.join(w,"telemetry.json")}async isEnabled(){if(yw.env.DO_NOT_TRACK==="1"||yw.env.DO_NOT_TRACK==="true")return!1;if(yw.env.NO_TELEMETRY==="1"||yw.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let Y={event:$,...w,timestamp:Date.now(),platform:jW.platform(),nodeVersion:yw.version};if(this.events.push(Y),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:yw.env.DO_NOT_TRACK==="1"||yw.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(_F(this.configPath)){let $=await q8.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=M8.dirname(this.configPath);await q8.mkdir(w,{recursive:!0}),await q8.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var dR=new NW;function DF($,w={}){let A={_:[]},Y=w.alias||{},X=new Set(w.boolean||[]),J={};for(let W of Object.keys(Y))for(let f of Y[W])J[f]=W;for(let W of X)if(Y[W])for(let f of Y[W])X.add(f);function U(W,f){let B=J[W]||W;if(A[B]=f,Y[B])for(let j of Y[B])A[j]=f;if(J[W]&&Y[J[W]])for(let j of Y[J[W]])A[j]=f;A[W]=f}for(let W=0;W<$.length;W++){let f=$[W];if(f==="--"){A._.push(...$.slice(W+1));break}if(f.startsWith("--")){let B=f.indexOf("=");if(B!==-1){let j=f.slice(2,B),z=f.slice(B+1);U(j,z)}else{let j=f.slice(2);if(j.startsWith("no-")){let E=j.slice(3);U(E,!1);continue}let z=J[j]||j;if(X.has(z)||X.has(j))U(j,!0);else{let E=$[W+1];if(E!==void 0&&!E.startsWith("-"))U(j,E),W++;else U(j,!0)}}}else if(f.startsWith("-")&&f.length>1){let B=f.slice(1);for(let j=0;j<B.length;j++){let z=B[j],E=J[z]||z;if(j===B.length-1&&!X.has(E)&&!X.has(z)){let F=$[W+1];if(F!==void 0&&!F.startsWith("-"))U(z,F),W++;else U(z,!0)}else U(z,!0)}}else A._.push(f)}return A}function C8($){return $.replace(/[<[].+/,"").trim()}function ZF($){let w=/<([^>]+)>/g,A=/\[([^\]]+)\]/g,Y=[],X=(W)=>{let f=!1,B=W[1];if(B.startsWith("..."))B=B.slice(3),f=!0;return{required:W[0].startsWith("<"),value:B,variadic:f}},J;while(J=w.exec($))Y.push(X(J));let U;while(U=A.exec($))Y.push(X(U));return Y}function xF($){let w={alias:{},boolean:[]};for(let[A,Y]of $.entries()){if(Y.names.length>1)w.alias[Y.names[0]]=Y.names.slice(1);if(Y.isBoolean)if(Y.negated){if(!$.some((J,U)=>{return U!==A&&J.names.some((W)=>Y.names.includes(W))&&typeof J.required==="boolean"}))w.boolean.push(Y.names[0])}else w.boolean.push(Y.names[0])}return w}function FW($){return $.reduce((w,A)=>w.length>=A.length?w:A,"")}function I8($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function PF($){return $.replace(/([a-z])-([a-z])/g,(w,A,Y)=>{return A+Y.toUpperCase()})}function bF($,w,A){let Y=0,X=w.length,J=$,U;for(;Y<X;++Y)U=J[w[Y]],J=J[w[Y]]=Y===X-1?A:U!=null?U:!!~w[Y+1].indexOf(".")||!(+w[Y+1]>-1)?{}:[]}function uF($,w){for(let A of Object.keys(w)){let Y=w[A];if(Y.shouldTransform){if($[A]=Array.prototype.concat.call([],$[A]),typeof Y.transformFunction==="function")$[A]=$[A].map(Y.transformFunction)}}}function iF($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function RW($){return $.split(".").map((w,A)=>{return A===0?PF(w):w}).join(".")}class DA extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
220
+ port ${QY}
221
+ `}function u1($){return a2.join(o2,$)}function AF($){return $.includes("127.0.0.1")&&$.includes(String(QY))}async function Mq($){try{return await r2.readFile(u1($),"utf8")}catch(w){if(w.code==="ENOENT")return null;throw w}}async function ef($){if(ww.platform!=="darwin")return;let{execSudoSync:w,getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),h1));if(!A()&&!Y()){E("dns","Cannot flush DNS cache without SUDO_PASSWORD",$);return}try{w("dscacheutil -flushcache"),w("killall -HUP mDNSResponder 2>/dev/null || true"),E("dns","DNS cache flushed",$)}catch(U){E("dns",`Could not flush DNS cache: ${U}`,$)}}function UF($){if(!/^[a-z0-9.-]+$/.test($))throw Error(`refusing unsafe resolver basename: ${JSON.stringify($)}`)}async function Iq($,w){UF($);let{execSudoSync:Y}=await Promise.resolve().then(() => (f0(),h1)),A=Rq().replace(/\n/g,"\\n"),U=`bash -c 'mkdir -p ${o2} && printf "%b" "${A}" > ${u1($)}'`;Y(U),E("dns",`Created ${u1($)}`,w)}async function yq($,w){UF($);let{execSudoSync:Y}=await Promise.resolve().then(() => (f0(),h1));Y(`rm -f ${u1($)}`),E("dns",`Removed ${u1($)}`,w)}async function Cq($,w){return YW({domains:w??[],verbose:$})}async function hq($,w){if(ww.platform!=="darwin")return!0;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),h1));if(!A()&&!Y())return E("dns","SUDO_PASSWORD not set, cannot create resolver files",w),!1;try{for(let U of $)await Iq(U,w);return await ef(w),!0}catch(U){return E("dns",`Failed to create resolver file: ${U}`,w),!1}}async function $W($,w){if(ww.platform!=="darwin")return;let{getSudoPassword:Y,isProcessElevated:A}=await Promise.resolve().then(() => (f0(),h1));if(!A()&&!Y())return;try{for(let U of $)await yq(U,w);await ef(w)}catch(U){E("dns",`Failed to remove resolver files: ${U}`,w)}}async function wW($){if(ww.platform!=="darwin")return[];let w=[];for(let Y of d2){let A=await Mq(Y);if(A&&AF(A))await $W([Y],$),w.push(Y)}return w}async function YW($){let w=$.rpxDir??e$(),Y=sf($.domains);if(Y.length===0)return!1;let A=af(Y),U=await wF(Y,$.verbose);if(!U){let W=Y[0];if(W&&await YF(W))U=!0;else E("dns","Dev DNS server not available on 127.0.0.1:15353",$.verbose)}if(!U)return!1;if(!await hq(A,$.verbose))return!1;let J={version:jX,resolvers:A,domains:Y,ownerPid:$.ownerPid??ww.pid,updatedAt:new Date().toISOString()};return await l2(w,J),!0}async function Dw($,w={}){let Y=$.map((f)=>f.to).filter(Boolean),A=w.rpxDir??e$(),U=af(Y),W=((await zX(A))?.resolvers??[]).filter((f)=>!U.includes(f));if(W.length>0)await $W(W,w.verbose);if(U.length===0){of(w.verbose),await rf(A);return}await YW({domains:Y,rpxDir:A,verbose:w.verbose,ownerPid:w.ownerPid??ww.pid})}async function Nw($={}){let w=$.rpxDir??e$();of($.verbose);let A=(await zX(w))?.resolvers??[];await $W(A,$.verbose),await wW($.verbose),await rf(w)}async function Vq($){await Nw({verbose:$})}async function $w($={}){let w=$.rpxDir??e$(),Y=await zX(w),A=Y?.ownerPid!=null&&p0(Y.ownerPid);if(Y&&!A){E("dns",`reconcile: owner pid ${Y.ownerPid} is gone — tearing down DNS`,$.verbose),await Nw($);return}let U=await wW($.verbose);if(U.length>0)E("dns",`reconcile: removed legacy TLD resolvers: ${U.join(", ")}`,$.verbose);await ef($.verbose)}var QY=15353,s2="# managed-by: rpx",o2="/etc/resolver",t0=null,FX;var b1=j0(()=>{nf();p2();hY();f0();FX=new Set});import{dirname as wR,join as YR}from"path";import*as n0 from"process";import{fileURLToPath as AR}from"url";import{existsSync as gF}from"node:fs";import OX from"node:fs/promises";import MW from"node:os";import SX from"node:path";import yw from"node:process";import{EventEmitter as lF}from"node:events";import Aw from"node:process";import IW from"node:process";import ZX from"node:process";import bY from"node:process";import t1 from"node:process";import hW from"node:tty";import k5,{stdin as yR,stdout as CR}from"node:process";import LW,{stdin as x5,stdout as P5}from"node:process";import b5 from"node:readline";class OW{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let $=MW.homedir(),w=SX.join($,".config","clapp");this.configPath=SX.join(w,"telemetry.json")}async isEnabled(){if(yw.env.DO_NOT_TRACK==="1"||yw.env.DO_NOT_TRACK==="true")return!1;if(yw.env.NO_TELEMETRY==="1"||yw.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let $=await this.loadConfig();if($.enabled=!0,!$.userId)$.userId=this.generateUserId();await this.saveConfig($)}async disable(){let $=await this.loadConfig();$.enabled=!1,await this.saveConfig($)}async track($,w){if(!await this.isEnabled())return;let A={event:$,...w,timestamp:Date.now(),platform:MW.platform(),nodeVersion:yw.version};if(this.events.push(A),this.events.length>=10)await this.send()}async trackCommand($,w){await this.track("command",{command:$,duration:w})}async trackError($,w){await this.track("error",{error:$,command:w})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let w=await this.loadConfig();return w.lastSent=Date.now(),await this.saveConfig(w),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let w=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(w),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep($){return new Promise((w)=>setTimeout(w,$))}async status(){let $=await this.loadConfig();return{enabled:$.enabled,doNotTrack:yw.env.DO_NOT_TRACK==="1"||yw.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:$.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(gF(this.configPath)){let $=await OX.readFile(this.configPath,"utf-8");return this.config=JSON.parse($),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig($){this.config=$;try{let w=SX.dirname(this.configPath);await OX.mkdir(w,{recursive:!0}),await OX.writeFile(this.configPath,JSON.stringify($,null,2),"utf-8")}catch{}}generateUserId(){let $=Math.random().toString(36).substring(2,15),w=Date.now().toString(36);return`${$}-${w}`}}var zR=new OW;function nF($,w={}){let Y={_:[]},A=w.alias||{},U=new Set(w.boolean||[]),X={};for(let W of Object.keys(A))for(let f of A[W])X[f]=W;for(let W of U)if(A[W])for(let f of A[W])U.add(f);function J(W,f){let B=X[W]||W;if(Y[B]=f,A[B])for(let j of A[B])Y[j]=f;if(X[W]&&A[X[W]])for(let j of A[X[W]])Y[j]=f;Y[W]=f}for(let W=0;W<$.length;W++){let f=$[W];if(f==="--"){Y._.push(...$.slice(W+1));break}if(f.startsWith("--")){let B=f.indexOf("=");if(B!==-1){let j=f.slice(2,B),z=f.slice(B+1);J(j,z)}else{let j=f.slice(2);if(j.startsWith("no-")){let G=j.slice(3);J(G,!1);continue}let z=X[j]||j;if(U.has(z)||U.has(j))J(j,!0);else{let G=$[W+1];if(G!==void 0&&!G.startsWith("-"))J(j,G),W++;else J(j,!0)}}}else if(f.startsWith("-")&&f.length>1){let B=f.slice(1);for(let j=0;j<B.length;j++){let z=B[j],G=X[z]||z;if(j===B.length-1&&!U.has(G)&&!U.has(z)){let F=$[W+1];if(F!==void 0&&!F.startsWith("-"))J(z,F),W++;else J(z,!0)}else J(z,!0)}}else Y._.push(f)}return Y}function DX($){return $.replace(/[<[].+/,"").trim()}function pF($){let w=/<([^>]+)>/g,Y=/\[([^\]]+)\]/g,A=[],U=(W)=>{let f=!1,B=W[1];if(B.startsWith("..."))B=B.slice(3),f=!0;return{required:W[0].startsWith("<"),value:B,variadic:f}},X;while(X=w.exec($))A.push(U(X));let J;while(J=Y.exec($))A.push(U(J));return A}function tF($){let w={alias:{},boolean:[]};for(let[Y,A]of $.entries()){if(A.names.length>1)w.alias[A.names[0]]=A.names.slice(1);if(A.isBoolean)if(A.negated){if(!$.some((X,J)=>{return J!==Y&&X.names.some((W)=>A.names.includes(W))&&typeof X.required==="boolean"}))w.boolean.push(A.names[0])}else w.boolean.push(A.names[0])}return w}function yW($){return $.reduce((w,Y)=>w.length>=Y.length?w:Y,"")}function _X($,w){return $.length>=w?$:`${$}${" ".repeat(w-$.length)}`}function rF($){return $.replace(/([a-z])-([a-z])/g,(w,Y,A)=>{return Y+A.toUpperCase()})}function aF($,w,Y){let A=0,U=w.length,X=$,J;for(;A<U;++A)J=X[w[A]],X=X[w[A]]=A===U-1?Y:J!=null?J:!!~w[A+1].indexOf(".")||!(+w[A+1]>-1)?{}:[]}function sF($,w){for(let Y of Object.keys(w)){let A=w[Y];if(A.shouldTransform){if($[Y]=Array.prototype.concat.call([],$[Y]),typeof A.transformFunction==="function")$[Y]=$[Y].map(A.transformFunction)}}}function oF($){let w=/([^\\/]+)$/.exec($);return w?w[1]:""}function SW($){return $.split(".").map((w,Y)=>{return Y===0?rF(w):w}).join(".")}class PY extends Error{exitCode=2;isUsageError=!0;constructor($){super($);if(this.name=this.constructor.name,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error($).stack}format($=!1){if($&&this.stack)return`${this.message}
220
222
 
221
223
  Stack trace:
222
- ${this.stack}`;return this.message}}function cF(){let{env:$}=zW,{TERM:w,TERM_PROGRAM:A}=$;if(zW.platform!=="win32")return w!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||A==="Terminus-Sublime"||A==="vscode"||w==="xterm-256color"||w==="alacritty"||w==="rxvt-unicode"||w==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var bA="\x1B",W0=`${bA}[`;var O$={to($,w){if(!w)return`${W0}${$+1}G`;return`${W0}${w+1};${$+1}H`},move($,w){let A="";if($<0)A+=`${W0}${-$}D`;else if($>0)A+=`${W0}${$}C`;if(w<0)A+=`${W0}${-w}A`;else if(w>0)A+=`${W0}${w}B`;return A},up:($=1)=>`${W0}${$}A`,down:($=1)=>`${W0}${$}B`,forward:($=1)=>`${W0}${$}C`,backward:($=1)=>`${W0}${$}D`,nextLine:($=1)=>`${W0}E`.repeat($),prevLine:($=1)=>`${W0}F`.repeat($),left:`${W0}G`,hide:`${W0}?25l`,show:`${W0}?25h`,save:`${bA}7`,restore:`${bA}8`};var y8={screen:`${W0}2J`,up:($=1)=>`${W0}1J`.repeat($),down:($=1)=>`${W0}J`.repeat($),line:`${W0}2K`,lineEnd:`${W0}K`,lineStart:`${W0}1K`,lines($){let w="";for(let A=0;A<$;A++)w+=this.line+(A<$-1?O$.up():"");if($)w+=O$.left;return w}},pR={screen:`${bA}c`};function vF($,w){let A=[];for(let Y=0;Y<=w.length;Y++)A[Y]=[Y];for(let Y=0;Y<=$.length;Y++)A[0][Y]=Y;for(let Y=1;Y<=w.length;Y++)for(let X=1;X<=$.length;X++)if(w.charAt(Y-1)===$.charAt(X-1))A[Y][X]=A[Y-1][X-1];else A[Y][X]=Math.min(A[Y-1][X-1]+1,A[Y][X-1]+1,A[Y-1][X]+1);return A[w.length][$.length]}function qW($,w,A=2,Y=3){return w.map((X)=>({cmd:X,distance:vF($,X)})).filter(({distance:X})=>X<=A).sort((X,J)=>X.distance-J.distance).slice(0,Y).map(({cmd:X})=>X)}class MW{rawName;description;name;names;isBoolean;required;config;negated;constructor($,w,A){if(this.rawName=$,this.description=w,this.config=Object.assign({},A),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=C8($).split(",").map((Y)=>{let X=Y.trim().replace(/^-{1,2}/,"");if(X.startsWith("no-"))this.negated=!0,X=X.replace(/^no-/,"");return RW(X)}).sort((Y,X)=>Y.length>X.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var rR=h8.argv,mF=`${h8.platform}-${h8.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,EW=ZA.argv,dF=`${ZA.platform}-${ZA.arch} node-${ZA.version}`;class V8{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,A,Y){this.rawName=$,this.description=w,this.config=A,this.cli=Y,this.options=[],this.aliasNames=[],this.name=C8($);let X=C8($),J=X.indexOf(":");if(J>0)this.namespace=X.substring(0,J),this.name=X.substring(J+1);if(this.args=ZF($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!A)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,A){let Y=new MW($,w,A);return this.options.push(Y),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof L8}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){return $=$.split(".")[0],!!this.options.find((w)=>{return w.names.includes($)})}outputHelp(){let{name:$,commands:w}=this.cli,{versionNumber:A,options:Y,helpCallback:X}=this.cli.globalCommand,J=[{body:`${$}${A?`/${A}`:""}`}];if(J.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let f=FW(w.map((F)=>F.rawName)),B=new Map,j=[];for(let F of w)if(F.namespace){if(!B.has(F.namespace))B.set(F.namespace,[]);B.get(F.namespace).push(F)}else j.push(F);let z="";if(j.length>0)z+=j.map((F)=>{return` ${I8(F.rawName,f.length)} ${F.description}`}).join(`
223
- `);let E=Array.from(B.keys()).sort();for(let F of E){let T=B.get(F);if(z.length>0)z+=`
224
+ ${this.stack}`;return this.message}}function eF(){let{env:$}=IW,{TERM:w,TERM_PROGRAM:Y}=$;if(IW.platform!=="win32")return w!=="linux";return Boolean($.WT_SESSION)||Boolean($.TERMINUS_SUBLIME)||$.ConEmuTask==="{cmd::Cmder}"||Y==="Terminus-Sublime"||Y==="vscode"||w==="xterm-256color"||w==="alacritty"||w==="rxvt-unicode"||w==="rxvt-unicode-256color"||$.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var cY="\x1B",W0=`${cY}[`;var Q$={to($,w){if(!w)return`${W0}${$+1}G`;return`${W0}${w+1};${$+1}H`},move($,w){let Y="";if($<0)Y+=`${W0}${-$}D`;else if($>0)Y+=`${W0}${$}C`;if(w<0)Y+=`${W0}${-w}A`;else if(w>0)Y+=`${W0}${w}B`;return Y},up:($=1)=>`${W0}${$}A`,down:($=1)=>`${W0}${$}B`,forward:($=1)=>`${W0}${$}C`,backward:($=1)=>`${W0}${$}D`,nextLine:($=1)=>`${W0}E`.repeat($),prevLine:($=1)=>`${W0}F`.repeat($),left:`${W0}G`,hide:`${W0}?25l`,show:`${W0}?25h`,save:`${cY}7`,restore:`${cY}8`};var kX={screen:`${W0}2J`,up:($=1)=>`${W0}1J`.repeat($),down:($=1)=>`${W0}J`.repeat($),line:`${W0}2K`,lineEnd:`${W0}K`,lineStart:`${W0}1K`,lines($){let w="";for(let Y=0;Y<$;Y++)w+=this.line+(Y<$-1?Q$.up():"");if($)w+=Q$.left;return w}},KR={screen:`${cY}c`};function $5($,w){let Y=[];for(let A=0;A<=w.length;A++)Y[A]=[A];for(let A=0;A<=$.length;A++)Y[0][A]=A;for(let A=1;A<=w.length;A++)for(let U=1;U<=$.length;U++)if(w.charAt(A-1)===$.charAt(U-1))Y[A][U]=Y[A-1][U-1];else Y[A][U]=Math.min(Y[A-1][U-1]+1,Y[A][U-1]+1,Y[A-1][U]+1);return Y[w.length][$.length]}function _W($,w,Y=2,A=3){return w.map((U)=>({cmd:U,distance:$5($,U)})).filter(({distance:U})=>U<=Y).sort((U,X)=>U.distance-X.distance).slice(0,A).map(({cmd:U})=>U)}class kW{rawName;description;name;names;isBoolean;required;config;negated;constructor($,w,Y){if(this.rawName=$,this.description=w,this.config=Object.assign({},Y),$=$.replace(/\.\*/g,""),this.negated=!1,this.names=DX($).split(",").map((A)=>{let U=A.trim().replace(/^-{1,2}/,"");if(U.startsWith("no-"))this.negated=!0,U=U.replace(/^no-/,"");return SW(U)}).sort((A,U)=>A.length>U.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if($.includes("<"))this.required=!0;else if($.includes("["))this.required=!1;else this.isBoolean=!0}}var HR=ZX.argv,w5=`${ZX.platform}-${ZX.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,CW=bY.argv,Y5=`${bY.platform}-${bY.arch} node-${bY.version}`;class xX{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor($,w,Y,A){this.rawName=$,this.description=w,this.config=Y,this.cli=A,this.options=[],this.aliasNames=[],this.name=DX($);let U=DX($),X=U.indexOf(":");if(X>0)this.namespace=U.substring(0,X),this.name=U.substring(X+1);if(this.args=pF($),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!Y)this.config={}}usage($){return this.usageText=$,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version($,w="-v, --version"){return this.versionNumber=$,this.option(w,"Display version number"),this}example($){return this.examples.push($),this}option($,w,Y){let A=new kW($,w,Y);return this.options.push(A),this}alias($){return this.aliasNames.push($),this}action($){return this.commandAction=$,this}before($){return this.beforeHooks.push($),this}after($){return this.afterHooks.push($),this}use($){return this.middleware.push($),this}isMatched($){if(this.aliasNames.includes($))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===$;return this.name===$}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof PX}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption($){return $=$.split(".")[0],!!this.options.find((w)=>{return w.names.includes($)})}outputHelp(){let{name:$,commands:w}=this.cli,{versionNumber:Y,options:A,helpCallback:U}=this.cli.globalCommand,X=[{body:`${$}${Y?`/${Y}`:""}`}];if(X.push({title:"Usage",body:` $ ${$} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&w.length>0){let f=yW(w.map((F)=>F.rawName)),B=new Map,j=[];for(let F of w)if(F.namespace){if(!B.has(F.namespace))B.set(F.namespace,[]);B.get(F.namespace).push(F)}else j.push(F);let z="";if(j.length>0)z+=j.map((F)=>{return` ${_X(F.rawName,f.length)} ${F.description}`}).join(`
225
+ `);let G=Array.from(B.keys()).sort();for(let F of G){let T=B.get(F);if(z.length>0)z+=`
224
226
 
225
227
  `;z+=` ${F}:
226
- `,z+=T.map((K)=>{return` ${I8(K.rawName,f.length-2)} ${K.description}`}).join(`
227
- `)}J.push({title:"Commands",body:z}),J.push({title:"For more info, run any command with the `--help` flag",body:w.map((F)=>` $ ${$}${F.displayName===""?"":` ${F.displayName}`} --help`).join(`
228
- `)})}let W=this.isGlobalCommand?Y:[...this.options,...Y||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)W=W.filter((f)=>f.name!=="version");if(W.length>0){let f=FW(W.map((B)=>B.rawName));J.push({title:"Options",body:W.map((B)=>{return` ${I8(B.rawName,f.length)} ${B.description} ${B.config.default===void 0?"":`(default: ${B.config.default})`}`}).join(`
229
- `)})}if(this.examples.length>0)J.push({title:"Examples",body:this.examples.map((f)=>{if(typeof f==="function")return f($);return f}).join(`
230
- `)});if(X)J=X(J)||J;console.log(J.map((f)=>{return f.title?`${f.title}:
228
+ `,z+=T.map((K)=>{return` ${_X(K.rawName,f.length-2)} ${K.description}`}).join(`
229
+ `)}X.push({title:"Commands",body:z}),X.push({title:"For more info, run any command with the `--help` flag",body:w.map((F)=>` $ ${$}${F.displayName===""?"":` ${F.displayName}`} --help`).join(`
230
+ `)})}let W=this.isGlobalCommand?A:[...this.options,...A||[]];if(!this.isGlobalCommand&&!this.isDefaultCommand)W=W.filter((f)=>f.name!=="version");if(W.length>0){let f=yW(W.map((B)=>B.rawName));X.push({title:"Options",body:W.map((B)=>{return` ${_X(B.rawName,f.length)} ${B.description} ${B.config.default===void 0?"":`(default: ${B.config.default})`}`}).join(`
231
+ `)})}if(this.examples.length>0)X.push({title:"Examples",body:this.examples.map((f)=>{if(typeof f==="function")return f($);return f}).join(`
232
+ `)});if(U)X=U(X)||X;console.log(X.map((f)=>{return f.title?`${f.title}:
231
233
  ${f.body}`:f.body}).join(`
232
234
 
233
- `))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?mF:dF}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let A=this.args.filter((X)=>X.required).slice(this.cli.args.length),Y=A.map((X)=>`<${X.value}>`).join(" ");throw new DA(`Missing required argument${A.length>1?"s":""}: ${Y}
235
+ `))}outputVersion(){let{name:$}=this.cli,{versionNumber:w}=this.cli.globalCommand;if(w)console.log(`${$}/${w} ${typeof Bun<"u"?w5:Y5}`)}checkRequiredArgs(){let $=this.args.filter((w)=>w.required).length;if(this.cli.args.length<$){let Y=this.args.filter((U)=>U.required).slice(this.cli.args.length),A=Y.map((U)=>`<${U.value}>`).join(" ");throw new PY(`Missing required argument${Y.length>1?"s":""}: ${A}
234
236
 
235
- Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let A of Object.keys($))if(A!=="--"&&!this.hasOption(A)&&!w.hasOption(A)){let X=[...w.options,...this.options].flatMap((f)=>f.names),J=A.length>1?`--${A}`:`-${A}`,U=qW(A,X),W=`Unknown option \`${J}\``;if(U.length>0)W+=`
237
+ Run \`${this.cli.name} ${this.rawName} --help\` for usage information.`)}}checkUnknownOptions(){let{options:$,globalCommand:w}=this.cli;if(!this.config.allowUnknownOptions){for(let Y of Object.keys($))if(Y!=="--"&&!this.hasOption(Y)&&!w.hasOption(Y)){let U=[...w.options,...this.options].flatMap((f)=>f.names),X=Y.length>1?`--${Y}`:`-${Y}`,J=_W(Y,U),W=`Unknown option \`${X}\``;if(J.length>0)W+=`
236
238
 
237
- Did you mean one of these?`,U.forEach((f)=>{let B=f.length>1?`--${f}`:`-${f}`;W+=`
239
+ Did you mean one of these?`,J.forEach((f)=>{let B=f.length>1?`--${f}`:`-${f}`;W+=`
238
240
  • ${B}`});throw W+=`
239
241
 
240
- Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new DA(W)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,A=[...w.options,...this.options];for(let Y of A){let X=$[Y.name.split(".")[0]];if(Y.required){let J=A.some((U)=>U.negated&&U.names.includes(Y.name));if(X===!0||X===!1&&!J)throw new DA(`Option \`${Y.rawName}\` requires a value.
242
+ Run \`${this.cli.name} ${this.rawName} --help\` to see available options.`,new PY(W)}}}checkOptionValue(){let{options:$,globalCommand:w}=this.cli,Y=[...w.options,...this.options];for(let A of Y){let U=$[A.name.split(".")[0]];if(A.required){let X=Y.some((J)=>J.negated&&J.names.includes(A.name));if(U===!0||U===!1&&!X)throw new PY(`Option \`${A.rawName}\` requires a value.
241
243
 
242
- Example: ${this.cli.name} ${this.rawName} ${Y.rawName} <value>`)}}}}class L8 extends V8{constructor($){super("@@global@@","",{},$)}}var gF=V8,Xw={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 m1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function nF(){return!0}function lF(){let $={};$.supportsColor=nF();function w(Y,X=[]){let J=Y===""?[]:[...X,Y],U=function(f){if(!$.supportsColor)return f;let B="",j="";for(let z of J)if(z in m1&&m1[z]in Xw){let E=m1[z];B+=Xw[E][0],j=Xw[E][1]+j}else if(z in Xw)B+=Xw[z][0],j=Xw[z][1]+j;return B+f+j},W=[...Object.keys(Xw),...Object.keys(m1)];for(let f of W)if(!(f in U))Object.defineProperty(U,f,{get(){return w(f,J)}});return U}let A=[...Object.keys(Xw),...Object.keys(m1)];for(let Y of A)if(!(Y in $))Object.defineProperty($,Y,{get(){return w(Y)}});return $}var d1=lF();class O8 extends kF{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new L8(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(A)=>{if(console.log(`
244
+ Example: ${this.cli.name} ${this.rawName} ${A.rawName} <value>`)}}}}class PX extends xX{constructor($){super("@@global@@","",{},$)}}var A5=xX,Uw={red:["\x1B[31m","\x1B[39m"],green:["\x1B[32m","\x1B[39m"],blue:["\x1B[34m","\x1B[39m"],yellow:["\x1B[33m","\x1B[39m"],cyan:["\x1B[36m","\x1B[39m"],magenta:["\x1B[35m","\x1B[39m"],white:["\x1B[37m","\x1B[39m"],gray:["\x1B[90m","\x1B[39m"],bgRed:["\x1B[41m","\x1B[49m"],bgGreen:["\x1B[42m","\x1B[49m"],bgBlue:["\x1B[44m","\x1B[49m"],bgYellow:["\x1B[43m","\x1B[49m"],bgCyan:["\x1B[46m","\x1B[49m"],bgMagenta:["\x1B[45m","\x1B[49m"],bold:["\x1B[1m","\x1B[22m"],italic:["\x1B[3m","\x1B[23m"],underline:["\x1B[4m","\x1B[24m"],dim:["\x1B[2m","\x1B[22m"],inverse:["\x1B[7m","\x1B[27m"],hidden:["\x1B[8m","\x1B[28m"],strikethrough:["\x1B[9m","\x1B[29m"]};var n1={primary:"blue",secondary:"cyan",success:"green",warning:"yellow",error:"red",info:"magenta",muted:"gray"};function U5(){return!0}function X5(){let $={};$.supportsColor=U5();function w(A,U=[]){let X=A===""?[]:[...U,A],J=function(f){if(!$.supportsColor)return f;let B="",j="";for(let z of X)if(z in n1&&n1[z]in Uw){let G=n1[z];B+=Uw[G][0],j=Uw[G][1]+j}else if(z in Uw)B+=Uw[z][0],j=Uw[z][1]+j;return B+f+j},W=[...Object.keys(Uw),...Object.keys(n1)];for(let f of W)if(!(f in J))Object.defineProperty(J,f,{get(){return w(f,X)}});return J}let Y=[...Object.keys(Uw),...Object.keys(n1)];for(let A of Y)if(!(A in $))Object.defineProperty($,A,{get(){return w(A)}});return $}var p1=X5();class bX extends lF{name;commands;globalCommand;matchedCommand;matchedCommandName;rawArgs;args;options;showHelpOnExit;showVersionOnExit;enableDidYouMean=!0;signalHandlersSet=!1;isVerbose=!1;isQuiet=!1;isDebug=!1;isNoInteraction=!1;environment;isDryRun=!1;isForce=!1;useEmoji=!0;theme;isNoCache=!1;constructor($=""){super();this.name=$,this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.globalCommand=new PX(this),this.globalCommand.usage("<command> [options]")}handleSignals($){if(this.signalHandlersSet)return this;let w=async(Y)=>{if(console.log(`
243
245
 
244
- Received ${A}, cleaning up...`),$)try{await $()}catch(Y){console.error("Error during cleanup:",Y)}Yw.exit(0)};return Yw.on("SIGINT",()=>w("SIGINT")),Yw.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,A){if(!A)A={};let Y=new gF($,w||"",A,this);return Y.globalCommand=this.globalCommand,this.commands.push(Y),Y}option($,w,A){return this.globalCommand.option($,w,A),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,w="-v, --version"){return this.globalCommand.version($,w),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:w},A,Y){if(this.args=$,this.options=w,A)this.matchedCommand=A;if(Y)this.matchedCommandName=Y;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(d1.red(`
246
+ Received ${Y}, cleaning up...`),$)try{await $()}catch(A){console.error("Error during cleanup:",A)}Aw.exit(0)};return Aw.on("SIGINT",()=>w("SIGINT")),Aw.on("SIGTERM",()=>w("SIGTERM")),this.signalHandlersSet=!0,this}didYouMean($=!0){return this.enableDidYouMean=$,this}verbose(){return this.globalCommand.option("-v, --verbose","Enable verbose output"),this}quiet(){return this.globalCommand.option("-q, --quiet","Suppress non-essential output"),this}debug(){return this.globalCommand.option("--debug","Enable debug mode with detailed error information"),this}noInteraction(){return this.globalCommand.option("-n, --no-interaction","Do not ask any interactive questions (for CI/CD)"),this}env(){return this.globalCommand.option("--env <environment>","Target environment (e.g., production, staging, local)"),this}dryRun(){return this.globalCommand.option("--dry-run","Preview actions without executing them"),this}force(){return this.globalCommand.option("-f, --force","Skip confirmation prompts"),this}emoji(){return this.globalCommand.option("--no-emoji","Disable emoji in output"),this}themes(){return this.globalCommand.option("--theme <theme>","Color theme (default, dracula, nord, solarized, monokai)"),this}cache(){return this.globalCommand.option("--no-cache","Disable caching"),this}usage($){return this.globalCommand.usage($),this}command($,w,Y){if(!Y)Y={};let A=new A5($,w||"",Y,this);return A.globalCommand=this.globalCommand,this.commands.push(A),A}option($,w,Y){return this.globalCommand.option($,w,Y),this}help($){return this.globalCommand.option("-h, --help","Display this message"),this.globalCommand.helpCallback=$,this.showHelpOnExit=!0,this}version($,w="-v, --version"){return this.globalCommand.version($,w),this.showVersionOnExit=!0,this}example($){return this.globalCommand.example($),this}outputHelp(){if(this.matchedCommand)this.matchedCommand.outputHelp();else this.globalCommand.outputHelp()}outputVersion(){this.globalCommand.outputVersion()}setParsedInfo({args:$,options:w},Y,A){if(this.args=$,this.options=w,Y)this.matchedCommand=Y;if(A)this.matchedCommandName=A;return this}unsetMatchedCommand(){this.matchedCommand=void 0,this.matchedCommandName=void 0}showCommandNotFound($){if(console.log(p1.red(`
245
247
  ✗ Command "${$}" not found.
246
- `)),this.enableDidYouMean){let w=[];for(let Y of this.commands){if(Y.displayName)w.push(Y.displayName);if(Y.aliasNames)w.push(...Y.aliasNames)}let A=qW($,w);if(A.length>0)console.log(d1.yellow("Did you mean one of these?")),A.forEach((Y)=>console.log(` ${d1.dim("•")} ${this.name} ${Y}`)),console.log("")}console.log(d1.dim("Run"),`${this.name} --help`,d1.dim("to see all available commands")),Yw.exit(1)}async parse($=EW,w={}){let{run:A=!0,exitOnError:Y=!1}=w;if(Y)try{return await this.parse($,{run:A})}catch(f){throw this.handleUsageError(f),f}if(this.rawArgs=$,!this.name)this.name=$[1]?iF($[1]):"cli";let X=!0,J=$.slice(2),U=J[0];if(U&&!U.startsWith("-")){for(let f of this.commands)if(f.isMatched(U)){let B=this.mri(J,f);X=!1;let j={...B,args:B.args.slice(1)};this.setParsedInfo(j,f,U),this.emit(`command:${U}`,f);break}}if(X){for(let f of this.commands)if(f.name===""){X=!1;let B=this.mri(J,f);this.setParsedInfo(B,f),this.emit("command:!",f);break}}if(X){let f=this.mri($.slice(2));this.setParsedInfo(f)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),A=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),A=!1,this.unsetMatchedCommand();let W={args:this.args,options:this.options};if(A)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 A=[...this.globalCommand.options,...w?w.options:[]],Y=xF(A),X=[],J=$.indexOf("--");if(J>-1)X=$.slice(J+1),$=$.slice(0,J);let U=DF($,Y),W={_:U._};for(let E of Object.keys(U))if(E!=="_")W[RW(E)]=U[E];let f=W._,B={"--":X},j=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,z=Object.create(null);for(let E of A){if(!j&&E.config.default!==void 0)for(let F of E.names)B[F]=E.config.default;if(Array.isArray(E.config.type)){if(z[E.name]===void 0)z[E.name]={shouldTransform:!0,transformFunction:E.config.type[0]}}}for(let E of Object.keys(W))if(E!=="_"){let F=E.split(".");bF(B,F,W[E]),uF(B,z)}return{args:f,options:B}}async run($=EW){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let Y=$,X=Y.message??"command-line error",J=this.name?`${this.name}: `:"",U=/--help/.test(X)?"":`
247
- Run \`${this.name??"cli"} --help\` for usage.`;Yw.stderr.write(`${J}${X}${U}
248
- `),Yw.exit(Y.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:A}=this;if(!A||!A.commandAction)return;A.checkUnknownOptions(),A.checkOptionValue(),A.checkRequiredArgs();let Y=[];A.args.forEach((W,f)=>{if(W.variadic)Y.push($.slice(f));else Y.push($[f])}),Y.push(w);let X={command:A,args:Y,options:w};for(let W of A.beforeHooks)await W(X);let J,U=async()=>{let W=A.commandAction.apply(this,Y);if(W instanceof Promise)J=await W;else J=W;return J};if(A.middleware.length>0){let W=0,f=async()=>{if(W<A.middleware.length){let B=A.middleware[W++];await B({...X,next:f})}else await U()};await f()}else await U();for(let W of A.afterHooks)await W(X);return J}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return Yw.removeAllListeners("SIGINT"),Yw.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 IW{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let w=this.cache.get($);if(!w){this.misses++;return}if(Date.now()-w.timestamp>w.ttl){this.cache.delete($),this.misses++;return}return this.hits++,w.value}set($,w,A=5000){if(!this.enabled)return;this.cache.set($,{value:w,timestamp:Date.now(),ttl:A})}has($){if(!this.enabled)return!1;let w=this.cache.get($);if(!w)return!1;if(Date.now()-w.timestamp>w.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[w,A]of this.cache.entries())if($-A.timestamp>A.ttl)this.cache.delete(w)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var sR=new IW;function pF(){if("FORCE_COLOR"in g1.env)return g1.env.FORCE_COLOR!=="0";if("NO_COLOR"in g1.env||g1.env.TERM==="dumb")return!1;if(g1.platform==="win32")return!0;return GW.isatty(1)&&GW.isatty(2)}var yW=pF();function A0($,w){if(!yW)return(A)=>A;return(A)=>$+A+w}var tF=A0("\x1B[0m","\x1B[0m"),rF=A0("\x1B[31m","\x1B[39m"),aF=A0("\x1B[32m","\x1B[39m"),sF=A0("\x1B[33m","\x1B[39m"),oF=A0("\x1B[34m","\x1B[39m"),eF=A0("\x1B[35m","\x1B[39m"),$E=A0("\x1B[36m","\x1B[39m"),wE=A0("\x1B[37m","\x1B[39m"),AE=A0("\x1B[90m","\x1B[39m"),YE=A0("\x1B[1m","\x1B[22m"),XE=A0("\x1B[3m","\x1B[23m"),JE=A0("\x1B[4m","\x1B[24m"),UE=A0("\x1B[2m","\x1B[22m"),fE=A0("\x1B[7m","\x1B[27m"),WE=A0("\x1B[8m","\x1B[28m"),BE=A0("\x1B[9m","\x1B[29m"),jE=A0("\x1B[41m","\x1B[49m"),zE=A0("\x1B[42m","\x1B[49m"),FE=A0("\x1B[43m","\x1B[49m"),EE=A0("\x1B[44m","\x1B[49m"),GE=A0("\x1B[45m","\x1B[49m"),KE=A0("\x1B[46m","\x1B[49m"),TE=A0("\x1B[47m","\x1B[49m"),HE=yW,NE={reset:tF,red:rF,green:aF,yellow:sF,blue:oF,magenta:eF,cyan:$E,white:wE,gray:AE,bold:YE,italic:XE,underline:JE,dim:UE,inverse:fE,hidden:WE,strikethrough:BE,bgRed:jE,bgGreen:zE,bgYellow:FE,bgBlue:EE,bgMagenta:GE,bgCyan:KE,bgWhite:TE,isColorSupported:HE},xA=NE,qE=["up","down","left","right","space","enter","cancel"],PA={actions:new Set(qE),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function CW($,w){if(typeof $==="string")return PA.aliases.get($)===w;for(let A of $){if(A===void 0)continue;if(CW(A,w))return!0}return!1}function ME($,w){if($===w)return[];let A=$.split(`
249
- `),Y=w.split(`
250
- `),X=[];for(let J=0;J<Math.max(A.length,Y.length);J++)if(A[J]!==Y[J])X.push(J);return X}var Yq=RE.platform.startsWith("win"),KW=Symbol("clapp:cancel");function kA($,w){let A=$;if(A.isTTY)A.setRawMode(w)}function hE($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function VE($){return hE($).length}function HW($,w,A){if(!w||w<1)return $;let Y=A?.hard??!1,X=A?.trim??!0,J=$.split(`
251
- `),U=[];for(let W of J){if(VE(W)<=w){U.push(X?W.trimEnd():W);continue}if(Y){let f="",B=0,j=0;while(j<W.length){let z=W.slice(j).match(/^\x1b\[[0-9;]*m/);if(z){f+=z[0],j+=z[0].length;continue}if(B>=w)U.push(X?f.trimEnd():f),f="",B=0;f+=W[j],B++,j++}if(f)U.push(X?f.trimEnd():f)}else U.push(X?W.trimEnd():W)}return U.join(`
252
- `)}class Q8{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:A=IE,output:Y=yE,render:X,signal:J,...U}=$;this.opts=U,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=X.bind(this),this._track=w,this._abortSignal=J,this.input=A,this.output=Y}unsubscribe(){this._subscribers.clear()}setSubscriber($,w){let A=this._subscribers.get($)??[];A.push(w),this._subscribers.set($,A)}on($,w){return this.setSubscriber($,{cb:w}),this}once($,w){return this.setSubscriber($,{cb:w,once:!0}),this}emit($,...w){let A=this._subscribers.get($)??[],Y=[];for(let X of A)if(X.cb(...w),X.once)Y.push(()=>A.splice(A.indexOf(X),1));for(let X of Y)X();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(KW);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=CE.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),kA(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(O$.show),this.output.off("resize",this.render),kA(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(O$.show),this.output.off("resize",this.render),kA(this.input,!1),$(KW)})})}_isActionKey($,w){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,w){if(this.userInput=$??"",this.emit("userInput",this.userInput),w&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,w){if(this._track&&w.name!=="return"){if(w.name&&this._isActionKey($,w))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let A=w.name==="tab"||w.name==="escape"||w.name==="backspace"||w.name==="delete"||w.name==="enter"||w.name==="return"||w.name&&["up","down","left","right"].includes(w.name);if($&&!A&&$.length===1&&$>=" ")this._manualLine+=$;else if(w.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let Y=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(Y)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&PA.aliases.has(w.name))this.emit("cursor",PA.aliases.get(w.name));if(PA.actions.has(w.name))this.emit("cursor",w.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),w),w?.name==="return"){if(this.opts.validate){let A=this.opts.validate(this.value);if(A)this.error=A instanceof Error?A.message:A,this.state="error"}if(this.state!=="error")this.state="submit"}if(CW([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
253
- `),kA(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 $=HW(this._prevFrame,TW.stdout.columns,{hard:!0,trim:!1}).split(`
254
- `).length-1;this.output.write(O$.move(-999,$*-1))}render(){let $=HW(this._render(this)??"",TW.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(O$.hide);else{let w=ME(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let A=w[0];this.output.write(O$.move(0,A)),this.output.write(y8.lines(1));let Y=$.split(`
255
- `);this.output.write(Y[A]),this._prevFrame=$,this.output.write(O$.move(0,Y.length-A-1));return}if(w&&w?.length>1){let A=w[0];this.output.write(O$.move(0,A)),this.output.write(y8.down());let X=$.split(`
256
- `).slice(A);this.output.write(X.join(`
257
- `)),this._prevFrame=$;return}this.output.write(y8.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function LE($,w){if($===void 0)return 0;if(w.length===0)return 0;let Y=w.findIndex((X)=>X.value===$);return Y!==-1?Y:0}function OE($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function QE($,w){if(!w)return;if($)return w;return w[0]}class SE extends Q8{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#A="";#Y;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return xA.inverse(xA.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...A]=this.userInput.slice(this._cursor);return`${$}${xA.inverse(w)}${A.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#Y=$.filter??OE;let A;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)A=$.initialValue;else A=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)A=[this.options[0].value];if(A)for(let Y of A){let X=w.findIndex((J)=>J.value===Y);if(X!==-1)this.toggleSelected(Y),this.#$=X}this.focusedValue=this.options[this.#$]?.value,this.on("key",(Y,X)=>this.#X(Y,X)),this.on("userInput",(Y)=>this.#J(Y))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#X($,w){let A=w.name==="up",Y=w.name==="down",X=w.name==="return";if(A||Y){if(this.#$=Math.max(0,Math.min(this.#$+(A?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(X)this.value=QE(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#J($){if($!==this.#A){this.#A=$;let w=this.options;if($)this.filteredOptions=w.filter((A)=>this.#Y($,A));else this.filteredOptions=[...w];if(this.#$=LE(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class _E extends Q8{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),A=this.value;if(A===void 0)return!1;return w.every((Y)=>A.includes(Y.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),A=this.getGroupItems(w);if(this.isGroupSelected(w))this.value=this.value.filter((Y)=>A.findIndex((X)=>X.value===Y)===-1);else this.value=[...this.value,...A.map((Y)=>Y.value)];this.value=Array.from(new Set(this.value))}else{let w=this.value.includes($.value);this.value=w?this.value.filter((A)=>A!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([A,Y])=>[{value:A,group:!0,label:A},...Y.map((X)=>({...X,group:A}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:A})=>A===$.cursorAt),this.#$?0:1),this.on("cursor",(A)=>{switch(A){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Y=this.options[this.cursor]?.group===!0;if(!this.#$&&Y)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 Y=this.options[this.cursor]?.group===!0;if(!this.#$&&Y)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var kE=cF();var s=($,w)=>kE?$:w,Uq=s("◆","*"),fq=s("■","x"),Wq=s("▲","x"),Bq=s("◇","o"),jq=s("┌","T"),DE=s("│","|"),zq=s("└","—"),Fq=s("●",">"),Eq=s("○"," "),Gq=s("◻","[•]"),Kq=s("◼","[+]"),Tq=s("◻","[ ]"),Hq=s("▪","•"),Nq=s("─","-"),Rq=s("╮","+"),qq=s("├","+"),Mq=s("╯","+"),Iq=s("●","•"),yq=s("◆","*"),Cq=s("▲","!"),hq=s("■","x");var Vq={light:s("─","-"),heavy:s("━","="),block:s("█","#")};function ZE(){return`${xA.gray(DE)} `}var Lq=ZE();HJ();import{homedir as NJ}from"node:os";import{join as RJ,resolve as TI}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",gG={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:RJ(NJ(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:RJ(NJ(),".stacks","ssl","stacks.localhost.crt"),keyPath:RJ(NJ(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var ow=gG;fw();aX();oX();$8();Lf();Qf();KA();MA();u1();f0();import{spawn as rz}from"node:child_process";import*as b0 from"node:fs/promises";import{homedir as az}from"node:os";import*as h$ from"node:path";import*as h from"node:process";var UR=5000;function K$(){return h$.join(az(),".stacks","rpx")}function Mw($=K$()){return h$.join($,"daemon.pid")}async function qw($=K$()){try{let w=await b0.readFile(Mw($),"utf8"),A=Number.parseInt(w.trim(),10);if(!Number.isFinite(A)||A<=0)return null;return A}catch(w){if(w.code==="ENOENT")return null;throw w}}async function W8($=K$()){let w=await qw($);return w!==null&&a0(w)}async function sz($=K$()){await b0.mkdir($,{recursive:!0});let w=Mw($);while(!0){try{let Y=await b0.open(w,"wx");try{await Y.write(`${h.pid}
258
- `)}finally{await Y.close()}return w}catch(Y){if(Y.code!=="EEXIST")throw Y}let A=await qw($);if(A!==null&&a0(A))throw Error(`rpx daemon already running (pid=${A})`);await b0.unlink(w).catch(()=>{})}}async function c1($=K$()){await b0.unlink(Mw($)).catch(()=>{})}function oz($){let w=$.cleanUrls??!1,A=Z1($.path);if($.static)return{static:GA($.static,w),cleanUrls:w,basePath:A};let Y=$.from??"localhost:1";return{sourceHost:new URL(Y.startsWith("http")?Y:`http://${Y}`).host,cleanUrls:w,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites,basePath:A}}function fR($){return $.find((A)=>!/^api\./.test(A)&&!/^docs\./.test(A)&&!/^dashboard\./.test(A))??$[0]??"rpx.localhost"}async function nf($,w){let A=await s$(w,$.verbose),Y=[...new Set(A.map((f)=>f.to).filter(Boolean))],X=fR(Y),J=[...new Set([X,...Y,"rpx.localhost"])],U=Cf(Y,X,$.verbose);if(typeof $.https==="object"&&typeof U.https==="object")U.https={...U.https,...$.https};let W=await a$(U);if(W&&!FX(tX,J))G("daemon",`shared cert missing SANs for registry host(s), regenerating (${J.join(", ")})`,$.verbose),rX(),W=null;if(!W)G("daemon","no usable cert on disk, generating one via tlsx",$.verbose),await S1({...U,forceRegenerate:!0}),W=await a$(U);if(!W)throw Error("failed to bootstrap TLS for rpx daemon");return W}async function WR($,w,A,Y){let X=h.env.SUDO_PASSWORD,J=h.env.HOME??az(),U=[h.execPath,...h.argv.slice(1)],W=[`HOME=${J}`,`PATH=${h.env.PATH??""}`];if(Y)W.push("RPX_VERBOSE=1");let f=X?["-S","-p","","env",...W,...U]:["-n","env",...W,...U];G("daemon",`elevating daemon via sudo for privileged ports ${w}/${A}`,Y);let B=rz("sudo",f,{detached:!0,stdio:["pipe","ignore","ignore"]}),j=null,z=null;if(B.once("error",(T)=>{j=T}),B.once("exit",(T)=>{z=T??0}),X&&B.stdin)B.stdin.write(`${X}
259
- `),B.stdin.end();B.unref();let E=Mw($),F=Date.now()+15000;while(Date.now()<F){if(j)throw j;let T=await qw($);if(T!==null&&a0(T)){if(Y)q.success(`rpx daemon elevated to root (pid=${T}, https on :${w})`);return{httpsPort:w,httpPort:A,pidPath:E,done:Promise.resolve(),stop:async()=>{try{h.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if(z!==null&&z!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${z}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((K)=>setTimeout(K,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}var lz=!1;function lf(){if(lz)return;lz=!0,h.on("uncaughtException",($)=>{q.error(`rpx daemon: uncaught exception (continuing): ${$?.stack??$}`)}),h.on("unhandledRejection",($)=>{q.error(`rpx daemon: unhandled rejection (continuing): ${$}`)})}function ez($,w){let A;try{A=new URL($.url)}catch{return new Response("Bad Request",{status:400})}let Y=($.headers.get("host")??A.hostname).split(":")[0];if(w&&A.pathname.startsWith("/.well-known/acme-challenge/")){let X=w.challengeStore.handlePath(A.pathname);if(X!==void 0)return new Response(X,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(w&&!w.hasCert(Y))w.ensureCert(Y).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${Y}${A.pathname}${A.search}`}})}async function $F($={}){lf();let w=$.verbose??!1,A=$.rpxDir??K$(),Y=$.registryDir??h$.join(A,"registry.d"),X=$.httpsPort??443,J=$.httpPort??80,U=$.hostname??"0.0.0.0",W=$.gcIntervalMs??UR;if(h.env.RPX_DAEMON_WORKER==="1")return zR({rpxDir:h.env.RPX_WORKER_RPXDIR??A,registryDir:h.env.RPX_WORKER_REGISTRYDIR??Y,httpsPort:Number.parseInt(h.env.RPX_WORKER_HTTPSPORT??"",10)||X,hostname:h.env.RPX_WORKER_HOSTNAME??U,verbose:h.env.RPX_WORKER_VERBOSE==="1"||w});let f=X>0&&X<1024||J>0&&J<1024,B=typeof h.getuid==="function"&&h.getuid()===0;if(h.platform!=="win32"&&f&&!B)return WR(A,X,J,w);let j=Math.max(1,$.workers??(Number.parseInt(h.env.RPX_WORKERS??"",10)||1));if(j>1)return FR($,{rpxDir:A,registryDir:Y,httpsPort:X,httpPort:J,hostname:U,verbose:w,gcIntervalMs:W,workers:j});let z=await sz(A),E=new Map,F=(L,w0)=>P1(E,L,w0);function T(L){E=x1(L.map((Aw)=>({host:Aw.to,path:Aw.path,route:oz(Aw)})));let w0=Array.from(E.keys());G("daemon",`routing table now covers ${w0.length} host(s): ${w0.join(", ")||"<empty>"}`,w)}await b1(Y,w).catch((L)=>{G("daemon",`initial gc failed: ${L}`,w)});let K=await s$(Y,w);T(K),await $w({rpxDir:A,verbose:w}).catch((L)=>{G("daemon",`DNS reconcile on start failed: ${L}`,w)}),await kw(K,{rpxDir:A,verbose:w,ownerPid:h.pid}).catch((L)=>{G("daemon",`DNS setup on start failed: ${L}`,w)});let H=[];if($.productionCerts){if(H=await w8($.productionCerts,w),w&&H.length>0)q.info(`SNI: serving ${H.length} real cert(s): ${H.map((L)=>L.serverName).join(", ")}`)}let N=k1(F,w),R=D1(w),M=null;if(H.length===0)M=await nf($,Y);let y=$.onDemandTls,I=y?.enabled?new NA({config:y,certsDir:y.certsDir??$.productionCerts?.certsDir??h$.join(A,"on-demand-certs"),initial:H,verbose:w,onCertAdded:(L)=>{t0(L)}}):null;function C(L){if(L.length>0)return L.map((w0)=>({serverName:w0.serverName,cert:w0.cert,key:w0.key}));return{key:M.key,cert:M.cert,ca:M.ca,requestCert:!1,rejectUnauthorized:!1}}function j0(L){return Bun.serve({port:X,hostname:U,reusePort:Sw(),tls:C(L),fetch(w0,Aw){return N(w0,Aw)},websocket:R,error(w0){return G("daemon",`https server error: ${w0}`,w),new Response(`Server Error: ${w0.message}`,{status:500})}})}let Q=(L)=>[...new Set(L.map((w0)=>w0.to).filter(Boolean))],_=(L)=>{if(!M)return H;return yf([...Q(L),"rpx.localhost"],M)},z0=j0(I?I.sniEntries():H.length>0?H:_(K));async function t0(L){if(Iw)return;G("daemon",`rebuilding :443 with ${L.length} SNI cert(s)`,w),z0.stop(!1);let w0;for(let Aw=0;Aw<20&&!Iw;Aw++)try{z0=j0(L);return}catch(hF){w0=hF,await new Promise((VF)=>setTimeout(VF,25))}q.error(`rpx: failed to rebuild :443 after issuing cert: ${w0?.message}`)}let r0=null;if(J>0)r0=Bun.serve({port:J,hostname:U,fetch(L){return ez(L,I)},error(){return new Response("Bad Request",{status:400})}});if(w)q.success(`rpx daemon listening on https://${U}:${X}${r0?` (http→https on :${J})`:""}`),q.info(`pid file: ${z}`),q.info(`registry: ${Y}`);async function S(L){if(Iw||H.length>0||I||!M)return;try{M=await nf($,Y),await t0(_(L))}catch(w0){G("daemon",`TLS sync on registry change failed: ${w0}`,w)}}let X$=qA((L)=>{T(L),S(L),kw(L,{rpxDir:A,verbose:w,ownerPid:h.pid}).catch((w0)=>{G("daemon",`DNS sync on registry change failed: ${w0}`,w)})},{dir:Y,verbose:w}),_A=setInterval(()=>{b1(Y,w).then((L)=>{if(L>0)G("daemon",`gc reaped ${L} stale entries`,w)}).catch((L)=>{G("daemon",`periodic gc failed: ${L}`,w)})},W);if(typeof _A.unref==="function")_A.unref();let Iw=!1,UW,R8=new Promise((L)=>{UW=L});async function fW(){if(Iw)return R8;if(Iw=!0,clearInterval(_A),X$.close(),z0.stop(!1),r0?.stop(!1),await Nw({rpxDir:A,verbose:w}).catch((L)=>{G("daemon",`DNS teardown failed: ${L}`,w)}),await c1(A),w)q.info("rpx daemon stopped");return UW(),R8}let WW=(L)=>{G("daemon",`received ${L}, shutting down`,w),fW().catch(()=>{})};return h.once("SIGINT",WW),h.once("SIGTERM",WW),{stop:fW,done:R8,httpsPort:typeof z0.port==="number"?z0.port:X,httpPort:r0&&typeof r0.port==="number"?r0.port:J,pidPath:z,ensureCert:(L)=>I?I.ensureCert(L):Promise.resolve(!1)}}function pf($){return h$.join($,"cluster-sni.json")}async function pz($,w,A){let Y=pf($),X=`${Y}.${h.pid}.tmp`;await b0.writeFile(X,JSON.stringify({sni:w,dev:A}),"utf8"),await b0.rename(X,Y)}async function tz($){try{return JSON.parse(await b0.readFile(pf($),"utf8"))}catch{return{sni:[],dev:null}}}function BR($){if($.sni.length>0)return $.sni.map((w)=>({serverName:w.serverName,cert:w.cert,key:w.key}));if($.dev)return{key:$.dev.key,cert:$.dev.cert,ca:$.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function jR(){let $=h.execPath,w=h.env.RPX_WORKER_BIN;if(w)return[$,w,"daemon:start"];let A=h$.basename($).toLowerCase();if((A==="bun"||A==="node"||A.startsWith("bun-"))&&h.argv[1])return[$,h.argv[1],"daemon:start"];return[$,"daemon:start"]}async function zR($){lf();let{rpxDir:w,registryDir:A,httpsPort:Y,hostname:X,verbose:J}=$,U=new Map,W=(I,C)=>P1(U,I,C),f=(I)=>{U=x1(I.map((C)=>({host:C.to,path:C.path,route:oz(C)})))};f(await s$(A,J));let B=k1(W,J),j=D1(J),z=!1,E=(I)=>Bun.serve({port:Y,hostname:X,reusePort:!0,tls:BR(I),fetch(C,j0){return B(C,j0)},websocket:j,error(C){return G("daemon",`worker https error: ${C}`,J),new Response(`Server Error: ${C.message}`,{status:500})}}),F=E(await tz(w));async function T(){if(z)return;let I=await tz(w);F.stop(!1);for(let C=0;C<20&&!z;C++)try{F=E(I);return}catch{await new Promise((j0)=>setTimeout(j0,25))}}let K=qA((I)=>f(I),{dir:A,verbose:J}),H=()=>{T().catch(()=>{})};h.on("SIGHUP",H);let N,R=new Promise((I)=>{N=I});async function M(){if(z)return R;return z=!0,h.off("SIGHUP",H),K.close(),F.stop(!1),N(),R}let y=()=>{M().then(()=>h.exit(0)).catch(()=>h.exit(0))};if(h.once("SIGTERM",y),h.once("SIGINT",y),J)q.success(`rpx worker (pid ${h.pid}) serving :${Y}`);return{stop:M,done:R,httpsPort:typeof F.port==="number"?F.port:Y,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1)}}async function FR($,w){lf();let{rpxDir:A,registryDir:Y,httpsPort:X,httpPort:J,hostname:U,verbose:W,gcIntervalMs:f,workers:B}=w,j=await sz(A),z=[];if($.productionCerts)z=await w8($.productionCerts,W);let E=null;if(z.length===0)E=await nf($,Y);let F=E?{key:E.key,cert:E.cert,ca:Array.isArray(E.ca)?E.ca.join(`
260
- `):E.ca}:null,T=!1,K=[];function H(S){for(let X$ of K)try{X$.kill(S)}catch{}}async function N(S){await pz(A,S,F),H("SIGHUP")}let R=$.onDemandTls,M=R?.enabled?new NA({config:R,certsDir:R.certsDir??$.productionCerts?.certsDir??h$.join(A,"on-demand-certs"),initial:z,verbose:W,onCertAdded:(S)=>{N(S)}}):null;await pz(A,M?M.sniEntries():z,F);let y=await s$(Y,W);await $w({rpxDir:A,verbose:W}).catch((S)=>{G("daemon",`DNS reconcile on start failed: ${S}`,W)}),await kw(y,{rpxDir:A,verbose:W,ownerPid:h.pid}).catch((S)=>{G("daemon",`DNS setup on start failed: ${S}`,W)}),await b1(Y,W).catch(()=>{});let I=qA((S)=>{kw(S,{rpxDir:A,verbose:W,ownerPid:h.pid}).catch((X$)=>{G("daemon",`DNS sync on registry change failed: ${X$}`,W)})},{dir:Y,verbose:W}),C=setInterval(()=>{b1(Y,W).catch(()=>{})},f);C.unref?.();let j0=null;if(J>0)j0=Bun.serve({port:J,hostname:U,fetch(S){return ez(S,M)},error(){return new Response("Bad Request",{status:400})}});function Q(){if(T)return;let S={...h.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:A,RPX_WORKER_REGISTRYDIR:Y,RPX_WORKER_HTTPSPORT:String(X),RPX_WORKER_HOSTNAME:U,RPX_WORKER_VERBOSE:W?"1":"0"},X$=Bun.spawn(jR(),{env:S,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(_A,Iw){if(!T)G("daemon",`worker exited (code ${Iw}); respawning`,W),Q()}});K.push(X$)}for(let S=0;S<B;S++)Q();if(W)q.success(`rpx coordinator listening on https://${U}:${X} via ${B} worker(s)${j0?` (http→https on :${J})`:""}`),q.info(`pid file: ${j}`);let _,z0=new Promise((S)=>{_=S});async function t0(){if(T)return z0;if(T=!0,clearInterval(C),I.close(),j0?.stop(!1),H("SIGTERM"),await Promise.race([Promise.all(K.map((S)=>S.exited)),new Promise((S)=>setTimeout(S,3000))]),H("SIGKILL"),await Nw({rpxDir:A,verbose:W}).catch((S)=>{G("daemon",`DNS teardown failed: ${S}`,W)}),await c1(A),await b0.unlink(pf(A)).catch(()=>{}),W)q.info("rpx coordinator stopped");return _(),z0}let r0=(S)=>{G("daemon",`coordinator received ${S}, shutting down`,W),t0().catch(()=>{})};return h.once("SIGINT",r0),h.once("SIGTERM",r0),{stop:t0,done:z0,httpsPort:X,httpPort:J,pidPath:j,ensureCert:(S)=>M?M.ensureCert(S):Promise.resolve(!1)}}function ER(){let $=h.execPath,w=h$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&h.argv[1])return[$,h.argv[1],"daemon:start"];return[$,"daemon:start"]}async function wF($={}){let w=$.rpxDir??K$(),A=$.verbose??!1;await $w({rpxDir:w,verbose:A}).catch((j)=>{G("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,A)});let Y=await qw(w);if(Y!==null&&a0(Y))return G("daemon",`ensureDaemonRunning: already running pid=${Y}`,A),{pid:Y,spawned:!1};if(Y!==null)G("daemon",`ensureDaemonRunning: clearing stale pid=${Y}`,A),await c1(w);await b0.mkdir(w,{recursive:!0});let X=$.spawnCommand??ER();if(X.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");G("daemon",`spawning daemon: ${X.join(" ")}`,A);let J=rz(X[0],X.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??h.cwd(),env:$.spawnEnv?{...h.env,...$.spawnEnv}:h.env});J.unref();let U=null;J.once("error",(j)=>{U=j});let W=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(U)throw U;let j=await qw(w);if(j!==null&&a0(j))return G("daemon",`daemon registered with pid=${j}`,A),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,f))}if(U)throw U;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function AF($={}){let w=$.rpxDir??K$(),A=$.verbose??!1,Y=$.timeoutMs??5000,X=$.pollIntervalMs??50,J=$.forceAfterTimeout??!0,U=await qw(w);if(U===null||!a0(U)){if(U!==null)await c1(w);return await $w({rpxDir:w,verbose:A}).catch(()=>{}),{stopped:!1,pid:U,forced:!1}}try{h.kill(U,"SIGTERM")}catch(f){if(f.code==="ESRCH")return await c1(w),{stopped:!1,pid:U,forced:!1};throw f}let W=Date.now()+Y;while(Date.now()<W){if(!a0(U))return G("daemon",`daemon pid=${U} stopped cleanly`,A),{stopped:!0,pid:U,forced:!1};await new Promise((f)=>setTimeout(f,X))}if(!J)throw Error(`rpx daemon (pid=${U}) did not exit within ${Y}ms`);G("daemon",`daemon pid=${U} did not exit, escalating to SIGKILL`,A);try{h.kill(U,"SIGKILL")}catch(f){if(f.code!=="ESRCH")throw f}return await c1(w),await Nw({rpxDir:w,verbose:A}).catch((f)=>{G("daemon",`DNS teardown after SIGKILL: ${f}`,A)}),{stopped:!0,pid:U,forced:!0}}async function YF($={}){let w=$.rpxDir??K$();if(await W8(w))return;await $w({rpxDir:w,verbose:$.verbose})}fw();f0();import{spawn as GR}from"node:child_process";import*as Dw from"node:process";class XF{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){G("start",`Process ${$} is already running`,A);return}let[Y,...X]=w.command.split(" "),J=w.cwd||Dw.cwd();G("start",`Starting process ${$}:`,A),G("start",` Command: ${Y} ${X.join(" ")}`,A),G("start",` Working directory: ${J}`,A),G("start",` Environment variables: ${E$(w.env)}`,A);let U=GR(Y,X,{cwd:J,env:{...Dw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((W,f)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)G("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),f(B),Dw.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)G("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),f(Error(`Process ${$} exited with code ${B}`)),Dw.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{G("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{G("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else G("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){G("start",`No process found for ${$}`,w);return}return G("start",`Stopping process ${$}`,w),new Promise((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),G("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){G("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){G("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),Y()}})}async stopAll($){if(this.isShuttingDown){G("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,G("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var B8=new XF;f0();import*as l0 from"node:fs/promises";import{homedir as KR}from"node:os";import*as tf from"node:path";import*as rf from"node:process";var TR=/^[a-zA-Z0-9._-]+$/;function Zw(){return tf.join(KR(),".stacks","rpx","registry.d")}function v1($){return typeof $==="string"&&$.length>0&&$.length<=128&&TR.test($)}function af($,w){if(!v1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return tf.join($,`${w}.json`)}function JF($){if(!$||typeof $!=="object")return!1;let w=$,A=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,Y=typeof w.from==="string"&&w.from.length>0,X=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",J=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&v1(w.id)&&(Y||X)&&typeof w.to==="string"&&w.to.length>0&&J&&A&&typeof w.createdAt==="string"}async function HR($){await l0.mkdir($,{recursive:!0})}async function UF($,w=Zw(),A){if(!JF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await HR(w);let Y=af(w,$.id),X=`${Y}.tmp.${rf.pid}.${Date.now()}`,J=JSON.stringify($,null,2);try{await l0.writeFile(X,J,{encoding:"utf8",mode:420}),await l0.rename(X,Y),G("registry",`wrote entry ${$.id} → ${Y}`,A)}catch(U){throw await l0.unlink(X).catch(()=>{}),U}}async function fF($,w=Zw(),A){let Y=af(w,$);try{await l0.unlink(Y),G("registry",`removed entry ${$}`,A)}catch(X){if(X.code!=="ENOENT")throw X}}async function sf($,w=Zw(),A){let Y=af(w,$);try{let X=await l0.readFile(Y,"utf8"),J=JSON.parse(X);if(!JF(J))return G("registry",`entry ${$} failed validation, removing`,A),await l0.unlink(Y).catch(()=>{}),null;return J}catch(X){if(X.code==="ENOENT")return null;if(X instanceof SyntaxError)return G("registry",`entry ${$} has invalid JSON, removing`,A),await l0.unlink(Y).catch(()=>{}),null;throw X}}async function WF($=Zw(),w){let A;try{A=await l0.readdir($)}catch(X){if(X.code==="ENOENT")return[];throw X}let Y=[];for(let X of A){if(!X.endsWith(".json"))continue;let J=X.slice(0,-5);if(!v1(J))continue;let U=await sf(J,$,w);if(U)Y.push(U)}return Y}fw();import{execSync as LR}from"node:child_process";import*as uw from"node:http";import*as HF from"node:http2";import*as NF from"node:net";import*as Y0 from"node:process";var j8=($,w)=>(A)=>`\x1B[${$}m${A}\x1B[${w}m`,V$={bold:j8(1,22),dim:j8(2,22),green:j8(32,39),cyan:j8(36,39)};OU();Df();fw();MA();f0();import*as BF from"node:fs";import*as jF from"node:path";import*as L$ from"node:process";function NR($,w){let Y=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return Y.length>0?Y:"rpx"}async function of($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,A=$.registryDir,Y=new Set,X=$.proxies.map((E)=>{let F=E.id??NR(E.to,E.path);if(!RA(F))throw Error(`invalid registry id "${F}" derived from to="${E.to}"`);if(Y.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return Y.add(F),{...E,id:F}}),J=new Date().toISOString();for(let E of X)await Lz({id:E.id,from:E.from,to:E.to,path:E.path,pid:$.persistent?void 0:L$.pid,cwd:L$.cwd(),createdAt:J,cleanUrls:E.cleanUrls,changeOrigin:E.changeOrigin,pathRewrites:E.pathRewrites,static:E.static},A,w);let U=await Sz({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let E of X){let F=E.static?`static ${typeof E.static==="string"?E.static:E.static.dir}`:E.from;q.success(`https://${E.to} → ${F}`)}if(q.info(`(via rpx daemon pid=${U.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,f=A??Hw(),B=X.map((E)=>E.id),j=async()=>{if(W)return;W=!0;for(let E of B)await kf(E,A,w).catch((F)=>{G("runner",`removeEntry(${E}) failed: ${F}`,w)})},z=(E)=>{G("runner",`received ${E}, unregistering ${B.length} entries`,w),j().finally(()=>L$.exit(0))};L$.once("SIGINT",z),L$.once("SIGTERM",z),L$.once("exit",()=>{if(W)return;for(let E of B)try{BF.unlinkSync(jF.join(f,`${E}.json`))}catch{}}),await new Promise(()=>{})}f0();import{exec as RR}from"node:child_process";import xw from"node:fs";import FF from"node:os";import $W from"node:path";import*as VA from"node:process";import{promisify as qR}from"node:util";var hA=qR(RR);function zF($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var T$=VA.platform==="win32"?$W.join(VA.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",ef=!1;async function z8($){if(VA.platform==="win32")throw Error("Administrator privileges required on Windows");if(dX()){let{stdout:Y}=await hA($);return Y}let w=Qw(),A=$.replace(/'/g,"'\\''");try{if(w){let{stdout:Y}=await hA(`echo '${w}' | sudo -S sh -c '${A}' 2>/dev/null`);return ef=!0,Y}if(ef)try{let{stdout:Y}=await hA(`sudo -n sh -c '${A}'`);return Y}catch(Y){G("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:Y}=await hA(`sudo -n sh -c '${A}'`);return ef=!0,Y}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(Y){throw Error(`Failed to execute sudo command: ${Y.message}`)}}async function LA($,w){let A=$.filter((X)=>!zF(X)),Y=$.filter((X)=>zF(X));if(Y.length>0)G("hosts",`Skipping /etc/hosts for loopback dev names: ${Y.join(", ")}`,w);if(A.length===0)return;G("hosts",`Adding hosts: ${A.join(", ")}`,w),G("hosts",`Using hosts file at: ${T$}`,w);try{let X;try{X=await xw.promises.readFile(T$,"utf-8")}catch{G("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{X=await z8(`cat "${T$}"`)}catch(f){throw console.log(" Could not read hosts file — skipping hosts setup"),G("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let J=A.filter((f)=>{let B=`127.0.0.1 ${f}`,j=`::1 ${f}`;return!X.includes(B)&&!X.includes(j)});if(J.length===0){G("hosts","All hosts already exist in hosts file",w);return}let U=J.map((f)=>`
248
+ `)),this.enableDidYouMean){let w=[];for(let A of this.commands){if(A.displayName)w.push(A.displayName);if(A.aliasNames)w.push(...A.aliasNames)}let Y=_W($,w);if(Y.length>0)console.log(p1.yellow("Did you mean one of these?")),Y.forEach((A)=>console.log(` ${p1.dim("•")} ${this.name} ${A}`)),console.log("")}console.log(p1.dim("Run"),`${this.name} --help`,p1.dim("to see all available commands")),Aw.exit(1)}async parse($=CW,w={}){let{run:Y=!0,exitOnError:A=!1}=w;if(A)try{return await this.parse($,{run:Y})}catch(f){throw this.handleUsageError(f),f}if(this.rawArgs=$,!this.name)this.name=$[1]?oF($[1]):"cli";let U=!0,X=$.slice(2),J=X[0];if(J&&!J.startsWith("-")){for(let f of this.commands)if(f.isMatched(J)){let B=this.mri(X,f);U=!1;let j={...B,args:B.args.slice(1)};this.setParsedInfo(j,f,J),this.emit(`command:${J}`,f);break}}if(U){for(let f of this.commands)if(f.name===""){U=!1;let B=this.mri(X,f);this.setParsedInfo(B,f),this.emit("command:!",f);break}}if(U){let f=this.mri($.slice(2));this.setParsedInfo(f)}if(this.options.verbose)this.isVerbose=!0;if(this.options.quiet)this.isQuiet=!0;if(this.options.debug)this.isDebug=!0;if(this.options.noInteraction)this.isNoInteraction=!0;if(this.options.env)this.environment=String(this.options.env);if(this.options.dryRun)this.isDryRun=!0;if(this.options.force)this.isForce=!0;if(this.options.noEmoji!==void 0)this.useEmoji=!this.options.noEmoji;if(this.options.theme)this.theme=String(this.options.theme);if(this.options.noCache!==void 0)this.isNoCache=Boolean(this.options.noCache);if(this.options.help&&this.showHelpOnExit)this.outputHelp(),Y=!1,this.unsetMatchedCommand();if(this.options.version&&this.showVersionOnExit&&this.matchedCommandName==null)this.outputVersion(),Y=!1,this.unsetMatchedCommand();let W={args:this.args,options:this.options};if(Y)await this.runMatchedCommand();if(!this.matchedCommand&&this.args[0]){if(this.emit("command:*"),!(this.listenerCount("command:*")>0))this.showCommandNotFound(this.args[0])}return W}mri($,w){let Y=[...this.globalCommand.options,...w?w.options:[]],A=tF(Y),U=[],X=$.indexOf("--");if(X>-1)U=$.slice(X+1),$=$.slice(0,X);let J=nF($,A),W={_:J._};for(let G of Object.keys(J))if(G!=="_")W[SW(G)]=J[G];let f=W._,B={"--":U},j=w&&w.config.ignoreOptionDefaultValue?w.config.ignoreOptionDefaultValue:this.globalCommand.config.ignoreOptionDefaultValue,z=Object.create(null);for(let G of Y){if(!j&&G.config.default!==void 0)for(let F of G.names)B[F]=G.config.default;if(Array.isArray(G.config.type)){if(z[G.name]===void 0)z[G.name]={shouldTransform:!0,transformFunction:G.config.type[0]}}}for(let G of Object.keys(W))if(G!=="_"){let F=G.split(".");aF(B,F,W[G]),sF(B,z)}return{args:f,options:B}}async run($=CW){return this.parse($,{run:!0,exitOnError:!0})}handleUsageError($){if(!(!!$&&typeof $==="object"&&$.name==="ClappError"&&$.isUsageError!==!1))return;let A=$,U=A.message??"command-line error",X=this.name?`${this.name}: `:"",J=/--help/.test(U)?"":`
249
+ Run \`${this.name??"cli"} --help\` for usage.`;Aw.stderr.write(`${X}${U}${J}
250
+ `),Aw.exit(A.exitCode??2)}async runMatchedCommand(){let{args:$,options:w,matchedCommand:Y}=this;if(!Y||!Y.commandAction)return;Y.checkUnknownOptions(),Y.checkOptionValue(),Y.checkRequiredArgs();let A=[];Y.args.forEach((W,f)=>{if(W.variadic)A.push($.slice(f));else A.push($[f])}),A.push(w);let U={command:Y,args:A,options:w};for(let W of Y.beforeHooks)await W(U);let X,J=async()=>{let W=Y.commandAction.apply(this,A);if(W instanceof Promise)X=await W;else X=W;return X};if(Y.middleware.length>0){let W=0,f=async()=>{if(W<Y.middleware.length){let B=Y.middleware[W++];await B({...U,next:f})}else await J()};await f()}else await J();for(let W of Y.afterHooks)await W(U);return X}removeSignalHandlers(){if(!this.signalHandlersSet)return this;return Aw.removeAllListeners("SIGINT"),Aw.removeAllListeners("SIGTERM"),this.signalHandlersSet=!1,this}destroy(){this.removeSignalHandlers(),this.commands=[],this.rawArgs=[],this.args=[],this.options={},this.matchedCommand=void 0,this.matchedCommandName=void 0,this.removeAllListeners()}}class DW{cache;enabled;cleanupInterval=null;hits=0;misses=0;constructor(){this.cache=new Map,this.enabled=!0,this.startCleanupInterval()}startCleanupInterval(){if(this.cleanupInterval)return;this.cleanupInterval=setInterval(()=>{this.cleanup()},30000),this.cleanupInterval.unref()}stopCleanup(){if(this.cleanupInterval)clearInterval(this.cleanupInterval),this.cleanupInterval=null}isEnabled(){return this.enabled}get($){if(!this.enabled){this.misses++;return}let w=this.cache.get($);if(!w){this.misses++;return}if(Date.now()-w.timestamp>w.ttl){this.cache.delete($),this.misses++;return}return this.hits++,w.value}set($,w,Y=5000){if(!this.enabled)return;this.cache.set($,{value:w,timestamp:Date.now(),ttl:Y})}has($){if(!this.enabled)return!1;let w=this.cache.get($);if(!w)return!1;if(Date.now()-w.timestamp>w.ttl)return this.cache.delete($),!1;return!0}delete($){this.cache.delete($)}clear(){this.cache.clear()}disable(){this.enabled=!1,this.clear()}enable(){this.enabled=!0}stats(){return{size:this.cache.size,enabled:this.enabled,hits:this.hits,misses:this.misses}}resetStats(){this.hits=0,this.misses=0}keys(){return Array.from(this.cache.keys())}cleanup(){let $=Date.now();for(let[w,Y]of this.cache.entries())if($-Y.timestamp>Y.ttl)this.cache.delete(w)}destroy(){this.stopCleanup(),this.clear(),this.resetStats()}}var qR=new DW;function J5(){if("FORCE_COLOR"in t1.env)return t1.env.FORCE_COLOR!=="0";if("NO_COLOR"in t1.env||t1.env.TERM==="dumb")return!1;if(t1.platform==="win32")return!0;return hW.isatty(1)&&hW.isatty(2)}var ZW=J5();function Y0($,w){if(!ZW)return(Y)=>Y;return(Y)=>$+Y+w}var f5=Y0("\x1B[0m","\x1B[0m"),W5=Y0("\x1B[31m","\x1B[39m"),B5=Y0("\x1B[32m","\x1B[39m"),j5=Y0("\x1B[33m","\x1B[39m"),z5=Y0("\x1B[34m","\x1B[39m"),F5=Y0("\x1B[35m","\x1B[39m"),G5=Y0("\x1B[36m","\x1B[39m"),E5=Y0("\x1B[37m","\x1B[39m"),K5=Y0("\x1B[90m","\x1B[39m"),T5=Y0("\x1B[1m","\x1B[22m"),H5=Y0("\x1B[3m","\x1B[23m"),N5=Y0("\x1B[4m","\x1B[24m"),q5=Y0("\x1B[2m","\x1B[22m"),R5=Y0("\x1B[7m","\x1B[27m"),M5=Y0("\x1B[8m","\x1B[28m"),I5=Y0("\x1B[9m","\x1B[29m"),y5=Y0("\x1B[41m","\x1B[49m"),C5=Y0("\x1B[42m","\x1B[49m"),h5=Y0("\x1B[43m","\x1B[49m"),V5=Y0("\x1B[44m","\x1B[49m"),L5=Y0("\x1B[45m","\x1B[49m"),Q5=Y0("\x1B[46m","\x1B[49m"),O5=Y0("\x1B[47m","\x1B[49m"),S5=ZW,_5={reset:f5,red:W5,green:B5,yellow:j5,blue:z5,magenta:F5,cyan:G5,white:E5,gray:K5,bold:T5,italic:H5,underline:N5,dim:q5,inverse:R5,hidden:M5,strikethrough:I5,bgRed:y5,bgGreen:C5,bgYellow:h5,bgBlue:V5,bgMagenta:L5,bgCyan:Q5,bgWhite:O5,isColorSupported:S5},uY=_5,D5=["up","down","left","right","space","enter","cancel"],iY={actions:new Set(D5),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"}};function xW($,w){if(typeof $==="string")return iY.aliases.get($)===w;for(let Y of $){if(Y===void 0)continue;if(xW(Y,w))return!0}return!1}function Z5($,w){if($===w)return[];let Y=$.split(`
251
+ `),A=w.split(`
252
+ `),U=[];for(let X=0;X<Math.max(Y.length,A.length);X++)if(Y[X]!==A[X])U.push(X);return U}var hR=k5.platform.startsWith("win"),VW=Symbol("clapp:cancel");function xY($,w){let Y=$;if(Y.isTTY)Y.setRawMode(w)}function u5($){return $.replace(/\x1b\[[0-9;]*m/g,"")}function i5($){return u5($).length}function QW($,w,Y){if(!w||w<1)return $;let A=Y?.hard??!1,U=Y?.trim??!0,X=$.split(`
253
+ `),J=[];for(let W of X){if(i5(W)<=w){J.push(U?W.trimEnd():W);continue}if(A){let f="",B=0,j=0;while(j<W.length){let z=W.slice(j).match(/^\x1b\[[0-9;]*m/);if(z){f+=z[0],j+=z[0].length;continue}if(B>=w)J.push(U?f.trimEnd():f),f="",B=0;f+=W[j],B++,j++}if(f)J.push(U?f.trimEnd():f)}else J.push(U?W.trimEnd():W)}return J.join(`
254
+ `)}class uX{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;_manualLine="";state="initial";error="";value;userInput="";constructor($,w=!0){let{input:Y=x5,output:A=P5,render:U,signal:X,...J}=$;this.opts=J,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=U.bind(this),this._track=w,this._abortSignal=X,this.input=Y,this.output=A}unsubscribe(){this._subscribers.clear()}setSubscriber($,w){let Y=this._subscribers.get($)??[];Y.push(w),this._subscribers.set($,Y)}on($,w){return this.setSubscriber($,{cb:w}),this}once($,w){return this.setSubscriber($,{cb:w,once:!0}),this}emit($,...w){let Y=this._subscribers.get($)??[],A=[];for(let U of Y)if(U.cb(...w),U.once)A.push(()=>Y.splice(Y.indexOf(U),1));for(let U of A)U();return this}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(VW);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}if(this.rl=b5.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0)this._setUserInput(this.opts.initialUserInput,!0);this.input.on("keypress",this.onKeypress),xY(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Q$.show),this.output.off("resize",this.render),xY(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(Q$.show),this.output.off("resize",this.render),xY(this.input,!1),$(VW)})})}_isActionKey($,w){return $==="\t"}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,w){if(this.userInput=$??"",this.emit("userInput",this.userInput),w&&this._track&&this.rl)this.rl.write(this.userInput),this._cursor=this.rl.cursor}onKeypress($,w){if(this._track&&w.name!=="return"){if(w.name&&this._isActionKey($,w))this.rl?.write(null,{ctrl:!0,name:"h"});this._cursor=this.rl?.cursor??0;let Y=w.name==="tab"||w.name==="escape"||w.name==="backspace"||w.name==="delete"||w.name==="enter"||w.name==="return"||w.name&&["up","down","left","right"].includes(w.name);if($&&!Y&&$.length===1&&$>=" ")this._manualLine+=$;else if(w.name==="backspace"&&this._manualLine.length>0)this._manualLine=this._manualLine.slice(0,-1);let A=this._manualLine.length>=(this.rl?.line?.length||0)?this._manualLine:this.rl?.line;this._setUserInput(A)}if(this.state==="error")this.state="active",this.error="";if(w?.name){if(!this._track&&iY.aliases.has(w.name))this.emit("cursor",iY.aliases.get(w.name));if(iY.actions.has(w.name))this.emit("cursor",w.name)}if($&&($.toLowerCase()==="y"||$.toLowerCase()==="n"))this.emit("confirm",$.toLowerCase()==="y");if(this.emit("key",$?.toLowerCase(),w),w?.name==="return"){if(this.opts.validate){let Y=this.opts.validate(this.value);if(Y)this.error=Y instanceof Error?Y.message:Y,this.state="error"}if(this.state!=="error")this.state="submit"}if(xW([$,w?.name,w?.sequence],"cancel"))this.state="cancel";if(this.state==="submit"||this.state==="cancel")this.emit("finalize");if(this.render(),this.state==="submit"||this.state==="cancel")this.close()}close(){if(this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
255
+ `),xY(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.state==="cancel")setTimeout(()=>{this.unsubscribe()},10);else this.unsubscribe()}restoreCursor(){let $=QW(this._prevFrame,LW.stdout.columns,{hard:!0,trim:!1}).split(`
256
+ `).length-1;this.output.write(Q$.move(-999,$*-1))}render(){let $=QW(this._render(this)??"",LW.stdout.columns,{hard:!0,trim:!1});if($===this._prevFrame)return;if(this.state==="initial")this.output.write(Q$.hide);else{let w=Z5(this._prevFrame,$);if(this.restoreCursor(),w&&w?.length===1){let Y=w[0];this.output.write(Q$.move(0,Y)),this.output.write(kX.lines(1));let A=$.split(`
257
+ `);this.output.write(A[Y]),this._prevFrame=$,this.output.write(Q$.move(0,A.length-Y-1));return}if(w&&w?.length>1){let Y=w[0];this.output.write(Q$.move(0,Y)),this.output.write(kX.down());let U=$.split(`
258
+ `).slice(Y);this.output.write(U.join(`
259
+ `)),this._prevFrame=$;return}this.output.write(kX.down())}if(this.output.write($),this.state==="initial")this.state="active";this._prevFrame=$}}function c5($,w){if($===void 0)return 0;if(w.length===0)return 0;let A=w.findIndex((U)=>U.value===$);return A!==-1?A:0}function v5($,w){return(w.label??String(w.value)).toLowerCase().includes($.toLowerCase())}function m5($,w){if(!w)return;if($)return w;return w[0]}class d5 extends uX{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#Y="";#A;#w;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return uY.inverse(uY.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let $=this.userInput.slice(0,this._cursor),[w,...Y]=this.userInput.slice(this._cursor);return`${$}${uY.inverse(w)}${Y.join("")}`}get options(){if(typeof this.#w==="function")return this.#w();return this.#w}constructor($){super($);this.#w=$.options;let w=this.options;this.filteredOptions=[...w],this.multiple=$.multiple===!0,this.#A=$.filter??v5;let Y;if($.initialValue&&Array.isArray($.initialValue))if(this.multiple)Y=$.initialValue;else Y=$.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)Y=[this.options[0].value];if(Y)for(let A of Y){let U=w.findIndex((X)=>X.value===A);if(U!==-1)this.toggleSelected(A),this.#$=U}this.focusedValue=this.options[this.#$]?.value,this.on("key",(A,U)=>this.#U(A,U)),this.on("userInput",(A)=>this.#X(A))}_isActionKey($,w){return $==="\t"||this.multiple&&this.isNavigating&&w.name==="space"&&$!==void 0&&$!==""}#U($,w){let Y=w.name==="up",A=w.name==="down",U=w.name==="return";if(Y||A){if(this.#$=Math.max(0,Math.min(this.#$+(Y?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if(U)this.value=m5(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(w.name==="tab"||this.isNavigating&&w.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected($){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes($))this.selectedValues=this.selectedValues.filter((w)=>w!==$);else this.selectedValues=[...this.selectedValues,$];else this.selectedValues=[$]}#X($){if($!==this.#Y){this.#Y=$;let w=this.options;if($)this.filteredOptions=w.filter((Y)=>this.#A($,Y));else this.filteredOptions=[...w];if(this.#$=c5(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class g5 extends uX{options;cursor=0;#$;getGroupItems($){return this.options.filter((w)=>w.group===$)}isGroupSelected($){let w=this.getGroupItems($),Y=this.value;if(Y===void 0)return!1;return w.every((A)=>Y.includes(A.value))}toggleValue(){let $=this.options[this.cursor];if(this.value===void 0)this.value=[];if($.group===!0){let w=String($.value),Y=this.getGroupItems(w);if(this.isGroupSelected(w))this.value=this.value.filter((A)=>Y.findIndex((U)=>U.value===A)===-1);else this.value=[...this.value,...Y.map((A)=>A.value)];this.value=Array.from(new Set(this.value))}else{let w=this.value.includes($.value);this.value=w?this.value.filter((Y)=>Y!==$.value):[...this.value,$.value]}}constructor($){super($,!1);let{options:w}=$;this.#$=$.selectableGroups!==!1,this.options=Object.entries(w).flatMap(([Y,A])=>[{value:Y,group:!0,label:Y},...A.map((U)=>({...U,group:Y}))]),this.value=[...$.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Y})=>Y===$.cursorAt),this.#$?0:1),this.on("cursor",(Y)=>{switch(Y){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let A=this.options[this.cursor]?.group===!0;if(!this.#$&&A)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let A=this.options[this.cursor]?.group===!0;if(!this.#$&&A)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var l5=eF();var o=($,w)=>l5?$:w,QR=o("◆","*"),OR=o("■","x"),SR=o("▲","x"),_R=o("◇","o"),kR=o("┌","T"),n5=o("│","|"),DR=o("└","—"),ZR=o("●",">"),xR=o("○"," "),PR=o("◻","[•]"),bR=o("◼","[+]"),uR=o("◻","[ ]"),iR=o("▪","•"),cR=o("─","-"),vR=o("╮","+"),mR=o("├","+"),dR=o("╯","+"),gR=o("●","•"),lR=o("◆","*"),nR=o("▲","!"),pR=o("■","x");var tR={light:o("─","-"),heavy:o("━","="),block:o("█","#")};function p5(){return`${uY.gray(n5)} `}var rR=p5();V8();import{homedir as L8}from"node:os";import{join as Q8,resolve as uI}from"node:path";var __dirname="/home/runner/work/rpx/rpx/packages/rpx/src",AE={from:"localhost:5173",to:"stacks.localhost",cleanUrls:!1,https:{basePath:"",caCertPath:Q8(L8(),".stacks","ssl","stacks.localhost.ca.crt"),certPath:Q8(L8(),".stacks","ssl","stacks.localhost.crt"),keyPath:Q8(L8(),".stacks","ssl","stacks.localhost.crt.key")},cleanup:{certs:!1,hosts:!1},vitePluginUsage:!1,verbose:!0,changeOrigin:!1,regenerateUntrustedCerts:!0};var sw=AE;fw();YX();UX();JX();fX();mf();qY();hY();b1();f0();import{spawn as WF}from"node:child_process";import*as P0 from"node:fs/promises";import{homedir as BF}from"node:os";import*as I$ from"node:path";import*as y from"node:process";var Lq=5000;function j$(){return I$.join(BF(),".stacks","rpx")}function Mw($=j$()){return I$.join($,"daemon.pid")}async function Rw($=j$()){try{let w=await P0.readFile(Mw($),"utf8"),Y=Number.parseInt(w.trim(),10);if(!Number.isFinite(Y)||Y<=0)return null;return Y}catch(w){if(w.code==="ENOENT")return null;throw w}}async function EX($=j$()){let w=await Rw($);return w!==null&&p0(w)}async function jF($=j$()){await P0.mkdir($,{recursive:!0});let w=Mw($);while(!0){try{let A=await P0.open(w,"wx");try{await A.write(`${y.pid}
260
+ `)}finally{await A.close()}return w}catch(A){if(A.code!=="EEXIST")throw A}let Y=await Rw($);if(Y!==null&&p0(Y))throw Error(`rpx daemon already running (pid=${Y})`);await P0.unlink(w).catch(()=>{})}}async function i1($=j$()){await P0.unlink(Mw($)).catch(()=>{})}function zF($){let w=$.cleanUrls??!1,Y=k1($.path);if($.static)return{static:NY($.static,w),cleanUrls:w,basePath:Y};let A=$.from??"localhost:1";return{sourceHost:new URL(A.startsWith("http")?A:`http://${A}`).host,cleanUrls:w,changeOrigin:$.changeOrigin??!1,pathRewrites:$.pathRewrites,basePath:Y}}function Qq($){return $.find((Y)=>!/^api\./.test(Y)&&!/^docs\./.test(Y)&&!/^dashboard\./.test(Y))??$[0]??"rpx.localhost"}async function AW($,w){let Y=await s$(w,$.verbose),A=[...new Set(Y.map((f)=>f.to).filter(Boolean))],U=Qq(A),X=[...new Set([U,...A,"rpx.localhost"])],J=Pf(A,U,$.verbose);if(typeof $.https==="object"&&typeof J.https==="object")J.https={...J.https,...$.https};let W=await a$(J);if(W&&!HU($X,X))E("daemon",`shared cert missing SANs for registry host(s), regenerating (${X.join(", ")})`,$.verbose),wX(),W=null;if(!W)E("daemon","no usable cert on disk, generating one via tlsx",$.verbose),await O1({...J,forceRegenerate:!0}),W=await a$(J);if(!W)throw Error("failed to bootstrap TLS for rpx daemon");return W}async function Oq($,w,Y,A){let U=y.env.SUDO_PASSWORD,X=y.env.HOME??BF(),J=[y.execPath,...y.argv.slice(1)],W=[`HOME=${X}`,`PATH=${y.env.PATH??""}`];if(A)W.push("RPX_VERBOSE=1");let f=U?["-S","-p","","env",...W,...J]:["-n","env",...W,...J];E("daemon",`elevating daemon via sudo for privileged ports ${w}/${Y}`,A);let B=WF("sudo",f,{detached:!0,stdio:["pipe","ignore","ignore"]}),j=null,z=null;if(B.once("error",(T)=>{j=T}),B.once("exit",(T)=>{z=T??0}),U&&B.stdin)B.stdin.write(`${U}
261
+ `),B.stdin.end();B.unref();let G=Mw($),F=Date.now()+15000;while(Date.now()<F){if(j)throw j;let T=await Rw($);if(T!==null&&p0(T)){if(A)R.success(`rpx daemon elevated to root (pid=${T}, https on :${w})`);return{httpsPort:w,httpPort:Y,pidPath:G,done:Promise.resolve(),stop:async()=>{try{y.kill(T,"SIGTERM")}catch{}},ensureCert:()=>Promise.resolve(!1)}}if(z!==null&&z!==0)throw Error(`rpx daemon could not elevate to bind :${w} (sudo exited ${z}). Set SUDO_PASSWORD in .env or run \`sudo -v\` first.`);await new Promise((K)=>setTimeout(K,50))}throw Error(`rpx daemon failed to elevate within 15000ms (rpxDir=${$})`)}var XF=!1;function UW(){if(XF)return;XF=!0,y.on("uncaughtException",($)=>{R.error(`rpx daemon: uncaught exception (continuing): ${$?.stack??$}`)}),y.on("unhandledRejection",($)=>{R.error(`rpx daemon: unhandled rejection (continuing): ${$}`)})}function FF($,w){let Y;try{Y=new URL($.url)}catch{return new Response("Bad Request",{status:400})}let A=($.headers.get("host")??Y.hostname).split(":")[0];if(w&&Y.pathname.startsWith("/.well-known/acme-challenge/")){let U=w.challengeStore.handlePath(Y.pathname);if(U!==void 0)return new Response(U,{status:200,headers:{"content-type":"text/plain"}});return new Response("challenge not found",{status:404})}if(w&&!w.hasCert(A))w.ensureCert(A).catch(()=>{});return new Response(null,{status:301,headers:{Location:`https://${A}${Y.pathname}${Y.search}`}})}async function GF($={}){UW();let w=$.verbose??!1,Y=$.rpxDir??j$(),A=$.registryDir??I$.join(Y,"registry.d"),U=$.httpsPort??443,X=$.httpPort??80,J=$.hostname??"0.0.0.0",W=$.gcIntervalMs??Lq;if(y.env.RPX_DAEMON_WORKER==="1")return kq({rpxDir:y.env.RPX_WORKER_RPXDIR??Y,registryDir:y.env.RPX_WORKER_REGISTRYDIR??A,httpsPort:Number.parseInt(y.env.RPX_WORKER_HTTPSPORT??"",10)||U,hostname:y.env.RPX_WORKER_HOSTNAME??J,verbose:y.env.RPX_WORKER_VERBOSE==="1"||w});let f=U>0&&U<1024||X>0&&X<1024,B=typeof y.getuid==="function"&&y.getuid()===0;if(y.platform!=="win32"&&f&&!B)return Oq(Y,U,X,w);let j=Math.max(1,$.workers??(Number.parseInt(y.env.RPX_WORKERS??"",10)||1));if(j>1)return Dq($,{rpxDir:Y,registryDir:A,httpsPort:U,httpPort:X,hostname:J,verbose:w,gcIntervalMs:W,workers:j});let z=await jF(Y),G=new Map,F=(L,t)=>Z1(G,L,t);function T(L){G=D1(L.map((L$)=>({host:L$.to,path:L$.path,route:zF(L$)})));let t=Array.from(G.keys());E("daemon",`routing table now covers ${t.length} host(s): ${t.join(", ")||"<empty>"}`,w)}await P1(A,w).catch((L)=>{E("daemon",`initial gc failed: ${L}`,w)});let K=await s$(A,w);T(K),await $w({rpxDir:Y,verbose:w}).catch((L)=>{E("daemon",`DNS reconcile on start failed: ${L}`,w)}),await Dw(K,{rpxDir:Y,verbose:w,ownerPid:y.pid}).catch((L)=>{E("daemon",`DNS setup on start failed: ${L}`,w)});let H=[];if($.productionCerts){if(H=await x1($.productionCerts,w),w&&H.length>0)R.info(`SNI: serving ${H.length} real cert(s): ${H.map((L)=>L.serverName).join(", ")}`)}let q=S1(F,w),M=_1(w),I=null;if(H.length===0)I=await AW($,A);let h=$.onDemandTls,N=h?.enabled?new IY({config:h,certsDir:h.certsDir??$.productionCerts?.certsDir??I$.join(Y,"on-demand-certs"),initial:H,verbose:w,onCertAdded:(L)=>{v1(L)}}):null;function C(L){if(L.length>0)return L.map((t)=>({serverName:t.serverName,cert:t.cert,key:t.key}));return{key:I.key,cert:I.cert,ca:I.ca,requestCert:!1,rejectUnauthorized:!1}}function O(L){return Bun.serve({port:U,hostname:J,reusePort:C1(),tls:C(L),fetch(t,L$){return q(t,L$)},websocket:M,error(t){return E("daemon",`https server error: ${t}`,w),new Response(`Server Error: ${t.message}`,{status:500})}})}let p=(L)=>[...new Set(L.map((t)=>t.to).filter(Boolean))],x0=(L)=>{if(!I)return H;return xf([...p(L),"rpx.localhost"],I)},h$=O(N?N.sniEntries():H.length>0?H:x0(K)),M$=null,Pw=!1;async function v1(L){if(S)return;if(M$=L,Pw)return;Pw=!0;try{while(!S&&M$){let t=M$;M$=null,E("daemon",`rebuilding :443 with ${t.length} SNI cert(s)`,w),h$.stop(!1);let L$,NW=!1;for(let qW=0;qW<20&&!S;qW++)try{h$=O(t),NW=!0;break}catch(uF){L$=uF,await new Promise((iF)=>setTimeout(iF,25))}if(!NW)R.error(`rpx: failed to rebuild :443 after issuing cert: ${L$?.message}`)}}finally{Pw=!1}}let V$=null;if(X>0)V$=Bun.serve({port:X,hostname:J,fetch(L){return FF(L,N)},error(){return new Response("Bad Request",{status:400})}});if(w)R.success(`rpx daemon listening on https://${J}:${U}${V$?` (http→https on :${X})`:""}`),R.info(`pid file: ${z}`),R.info(`registry: ${A}`);async function m1(L){if(S||H.length>0||N||!I)return;try{I=await AW($,A),await v1(x0(L))}catch(t){E("daemon",`TLS sync on registry change failed: ${t}`,w)}}let ZY=CY((L)=>{T(L),m1(L),Dw(L,{rpxDir:Y,verbose:w,ownerPid:y.pid}).catch((t)=>{E("daemon",`DNS sync on registry change failed: ${t}`,w)})},{dir:A,verbose:w}),bw=setInterval(()=>{P1(A,w).then((L)=>{if(L>0)E("daemon",`gc reaped ${L} stale entries`,w)}).catch((L)=>{E("daemon",`periodic gc failed: ${L}`,w)})},W);if(typeof bw.unref==="function")bw.unref();let S=!1,Yw,d1=new Promise((L)=>{Yw=L});async function g1(){if(S)return d1;if(S=!0,clearInterval(bw),ZY.close(),h$.stop(!1),V$?.stop(!1),await Nw({rpxDir:Y,verbose:w}).catch((L)=>{E("daemon",`DNS teardown failed: ${L}`,w)}),await i1(Y),w)R.info("rpx daemon stopped");return Yw(),d1}let l1=(L)=>{E("daemon",`received ${L}, shutting down`,w),g1().catch(()=>{})};return y.once("SIGINT",l1),y.once("SIGTERM",l1),{stop:g1,done:d1,httpsPort:typeof h$.port==="number"?h$.port:U,httpPort:V$&&typeof V$.port==="number"?V$.port:X,pidPath:z,ensureCert:(L)=>N?N.ensureCert(L):Promise.resolve(!1)}}function XW($){return I$.join($,"cluster-sni.json")}async function JF($,w,Y){let A=XW($),U=`${A}.${y.pid}.tmp`;await P0.writeFile(U,JSON.stringify({sni:w,dev:Y}),"utf8"),await P0.rename(U,A)}async function fF($){try{return JSON.parse(await P0.readFile(XW($),"utf8"))}catch{return{sni:[],dev:null}}}function Sq($){if($.sni.length>0)return $.sni.map((w)=>({serverName:w.serverName,cert:w.cert,key:w.key}));if($.dev)return{key:$.dev.key,cert:$.dev.cert,ca:$.dev.ca,requestCert:!1,rejectUnauthorized:!1};return}function _q(){let $=y.execPath,w=y.env.RPX_WORKER_BIN;if(w)return[$,w,"daemon:start"];let Y=I$.basename($).toLowerCase();if((Y==="bun"||Y==="node"||Y.startsWith("bun-"))&&y.argv[1])return[$,y.argv[1],"daemon:start"];return[$,"daemon:start"]}async function kq($){UW();let{rpxDir:w,registryDir:Y,httpsPort:A,hostname:U,verbose:X}=$,J=new Map,W=(N,C)=>Z1(J,N,C),f=(N)=>{J=D1(N.map((C)=>({host:C.to,path:C.path,route:zF(C)})))};f(await s$(Y,X));let B=S1(W,X),j=_1(X),z=!1,G=(N)=>Bun.serve({port:A,hostname:U,reusePort:!0,tls:Sq(N),fetch(C,O){return B(C,O)},websocket:j,error(C){return E("daemon",`worker https error: ${C}`,X),new Response(`Server Error: ${C.message}`,{status:500})}}),F=G(await fF(w));async function T(){if(z)return;let N=await fF(w),C=null;for(let p=0;p<20&&!z;p++)try{C=G(N);break}catch{await new Promise((x0)=>setTimeout(x0,25))}if(!C){E("daemon","worker reloadTls: could not bind new listener; keeping current",X);return}let O=F;F=C,O.stop(!1)}let K=CY((N)=>f(N),{dir:Y,verbose:X}),H=()=>{T().catch(()=>{})};y.on("SIGHUP",H);let q,M=new Promise((N)=>{q=N});async function I(){if(z)return M;return z=!0,y.off("SIGHUP",H),K.close(),F.stop(!1),q(),M}let h=()=>{I().then(()=>y.exit(0)).catch(()=>y.exit(0))};if(y.once("SIGTERM",h),y.once("SIGINT",h),X)R.success(`rpx worker (pid ${y.pid}) serving :${A}`);return{stop:I,done:M,httpsPort:typeof F.port==="number"?F.port:A,httpPort:0,pidPath:"",ensureCert:()=>Promise.resolve(!1)}}async function Dq($,w){UW();let{rpxDir:Y,registryDir:A,httpsPort:U,httpPort:X,hostname:J,verbose:W,gcIntervalMs:f,workers:B}=w,j=await jF(Y),z=[];if($.productionCerts)z=await x1($.productionCerts,W);let G=null;if(z.length===0)G=await AW($,A);let F=G?{key:G.key,cert:G.cert,ca:Array.isArray(G.ca)?G.ca.join(`
262
+ `):G.ca}:null,T=!1,K=[];function H(S){for(let Yw of K)try{Yw.kill(S)}catch{}}async function q(S){await JF(Y,S,F),H("SIGHUP")}let M=$.onDemandTls,I=M?.enabled?new IY({config:M,certsDir:M.certsDir??$.productionCerts?.certsDir??I$.join(Y,"on-demand-certs"),initial:z,verbose:W,onCertAdded:(S)=>{q(S)}}):null;await JF(Y,I?I.sniEntries():z,F);let h=await s$(A,W);await $w({rpxDir:Y,verbose:W}).catch((S)=>{E("daemon",`DNS reconcile on start failed: ${S}`,W)}),await Dw(h,{rpxDir:Y,verbose:W,ownerPid:y.pid}).catch((S)=>{E("daemon",`DNS setup on start failed: ${S}`,W)}),await P1(A,W).catch(()=>{});let N=CY((S)=>{Dw(S,{rpxDir:Y,verbose:W,ownerPid:y.pid}).catch((Yw)=>{E("daemon",`DNS sync on registry change failed: ${Yw}`,W)})},{dir:A,verbose:W}),C=setInterval(()=>{P1(A,W).catch(()=>{})},f);C.unref?.();let O=null;if(X>0)O=Bun.serve({port:X,hostname:J,fetch(S){return FF(S,I)},error(){return new Response("Bad Request",{status:400})}});let p=10,x0=60000,h$=30000,M$=0,Pw=Date.now();function v1(){if(T)return;let S={...y.env,RPX_DAEMON_WORKER:"1",RPX_WORKERS:"1",RPX_WORKER_RPXDIR:Y,RPX_WORKER_REGISTRYDIR:A,RPX_WORKER_HTTPSPORT:String(U),RPX_WORKER_HOSTNAME:J,RPX_WORKER_VERBOSE:W?"1":"0"},Yw=Bun.spawn(_q(),{env:S,stdout:"inherit",stderr:"inherit",stdin:"ignore",onExit(d1,g1){if(T)return;let l1=K.indexOf(d1);if(l1!==-1)K.splice(l1,1);let L=Date.now();if(L-Pw>x0)Pw=L,M$=0;if(M$++,M$>p){R.error(`rpx: worker keeps exiting (code ${g1}); giving up after ${p} restarts in ${Math.round(x0/1000)}s`);return}let t=Math.min(h$,100*2**Math.min(M$,8));E("daemon",`worker exited (code ${g1}); respawning in ${t}ms (restart ${M$}/${p})`,W),setTimeout(v1,t).unref?.()}});K.push(Yw)}for(let S=0;S<B;S++)v1();if(W)R.success(`rpx coordinator listening on https://${J}:${U} via ${B} worker(s)${O?` (http→https on :${X})`:""}`),R.info(`pid file: ${j}`);let V$,m1=new Promise((S)=>{V$=S});async function ZY(){if(T)return m1;if(T=!0,clearInterval(C),N.close(),O?.stop(!1),H("SIGTERM"),await Promise.race([Promise.all(K.map((S)=>S.exited)),new Promise((S)=>setTimeout(S,3000))]),H("SIGKILL"),await Nw({rpxDir:Y,verbose:W}).catch((S)=>{E("daemon",`DNS teardown failed: ${S}`,W)}),await i1(Y),await P0.unlink(XW(Y)).catch(()=>{}),W)R.info("rpx coordinator stopped");return V$(),m1}let bw=(S)=>{E("daemon",`coordinator received ${S}, shutting down`,W),ZY().catch(()=>{})};return y.once("SIGINT",bw),y.once("SIGTERM",bw),{stop:ZY,done:m1,httpsPort:U,httpPort:X,pidPath:j,ensureCert:(S)=>I?I.ensureCert(S):Promise.resolve(!1)}}function Zq(){let $=y.execPath,w=I$.basename($).toLowerCase();if((w==="bun"||w==="node"||w.startsWith("bun-"))&&y.argv[1])return[$,y.argv[1],"daemon:start"];return[$,"daemon:start"]}async function EF($={}){let w=$.rpxDir??j$(),Y=$.verbose??!1;await $w({rpxDir:w,verbose:Y}).catch((j)=>{E("daemon",`DNS reconcile before ensureDaemonRunning: ${j}`,Y)});let A=await Rw(w);if(A!==null&&p0(A))return E("daemon",`ensureDaemonRunning: already running pid=${A}`,Y),{pid:A,spawned:!1};if(A!==null)E("daemon",`ensureDaemonRunning: clearing stale pid=${A}`,Y),await i1(w);await P0.mkdir(w,{recursive:!0});let U=$.spawnCommand??Zq();if(U.length===0)throw Error("ensureDaemonRunning: spawnCommand is empty");E("daemon",`spawning daemon: ${U.join(" ")}`,Y);let X=WF(U[0],U.slice(1),{detached:!0,stdio:"ignore",cwd:$.spawnCwd??y.cwd(),env:$.spawnEnv?{...y.env,...$.spawnEnv}:y.env});X.unref();let J=null;X.once("error",(j)=>{J=j});let W=$.startupTimeoutMs??5000,f=$.pollIntervalMs??50,B=Date.now()+W;while(Date.now()<B){if(J)throw J;let j=await Rw(w);if(j!==null&&p0(j))return E("daemon",`daemon registered with pid=${j}`,Y),{pid:j,spawned:!0};await new Promise((z)=>setTimeout(z,f))}if(J)throw J;throw Error(`rpx daemon failed to start within ${W}ms (rpxDir=${w})`)}async function KF($={}){let w=$.rpxDir??j$(),Y=$.verbose??!1,A=$.timeoutMs??5000,U=$.pollIntervalMs??50,X=$.forceAfterTimeout??!0,J=await Rw(w);if(J===null||!p0(J)){if(J!==null)await i1(w);return await $w({rpxDir:w,verbose:Y}).catch(()=>{}),{stopped:!1,pid:J,forced:!1}}try{y.kill(J,"SIGTERM")}catch(f){if(f.code==="ESRCH")return await i1(w),{stopped:!1,pid:J,forced:!1};throw f}let W=Date.now()+A;while(Date.now()<W){if(!p0(J))return E("daemon",`daemon pid=${J} stopped cleanly`,Y),{stopped:!0,pid:J,forced:!1};await new Promise((f)=>setTimeout(f,U))}if(!X)throw Error(`rpx daemon (pid=${J}) did not exit within ${A}ms`);E("daemon",`daemon pid=${J} did not exit, escalating to SIGKILL`,Y);try{y.kill(J,"SIGKILL")}catch(f){if(f.code!=="ESRCH")throw f}return await i1(w),await Nw({rpxDir:w,verbose:Y}).catch((f)=>{E("daemon",`DNS teardown after SIGKILL: ${f}`,Y)}),{stopped:!0,pid:J,forced:!0}}async function TF($={}){let w=$.rpxDir??j$();if(await EX(w))return;await $w({rpxDir:w,verbose:$.verbose})}fw();f0();import{spawn as xq}from"node:child_process";import*as KX from"node:process";class HF{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){E("start",`Process ${$} is already running`,Y);return}let[A,...U]=w.command.split(" "),X=w.cwd||KX.cwd();E("start",`Starting process ${$}:`,Y),E("start",` Command: ${A} ${U.join(" ")}`,Y),E("start",` Working directory: ${X}`,Y),E("start",` Environment variables: ${R$(w.env)}`,Y);let J=xq(A,U,{cwd:X,env:{...KX.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:J,env:w.env}),new Promise((W,f)=>{if(J.on("error",(B)=>{if(!this.isShuttingDown)E("start",`Process ${$} failed to start: ${B}`,Y),this.processes.delete($),f(B)}),J.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)E("start",`Process ${$} exited with code ${B}; leaving the proxy running`,Y),this.processes.delete($),f(Error(`Process ${$} exited with code ${B}`))}),Y)J.stdout?.on("data",(B)=>{E("process",`[${$}] ${B.toString().trim()}`,!0)}),J.stderr?.on("data",(B)=>{E("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&J.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else E("start",`Process ${$} started successfully`,Y),W()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){E("start",`No process found for ${$}`,w);return}return E("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),E("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){E("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){E("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){E("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,E("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var TX=new HF;f0();import*as l0 from"node:fs/promises";import{homedir as Pq}from"node:os";import*as JW from"node:path";import*as fW from"node:process";var bq=/^[a-zA-Z0-9._-]+$/;function Zw(){return JW.join(Pq(),".stacks","rpx","registry.d")}function c1($){return typeof $==="string"&&$.length>0&&$.length<=128&&bq.test($)}function WW($,w){if(!c1(w))throw Error(`invalid registry id: ${JSON.stringify(w)}`);return JW.join($,`${w}.json`)}function NF($){if(!$||typeof $!=="object")return!1;let w=$,Y=w.pid===void 0||typeof w.pid==="number"&&Number.isInteger(w.pid)&&w.pid>0,A=typeof w.from==="string"&&w.from.length>0,U=typeof w.static==="string"||!!w.static&&typeof w.static==="object"&&typeof w.static.dir==="string",X=w.path===void 0||typeof w.path==="string";return typeof w.id==="string"&&c1(w.id)&&(A||U)&&typeof w.to==="string"&&w.to.length>0&&X&&Y&&typeof w.createdAt==="string"}async function uq($){await l0.mkdir($,{recursive:!0})}async function qF($,w=Zw(),Y){if(!NF($))throw Error(`invalid registry entry: ${JSON.stringify($)}`);await uq(w);let A=WW(w,$.id),U=`${A}.tmp.${fW.pid}.${Date.now()}`,X=JSON.stringify($,null,2);try{await l0.writeFile(U,X,{encoding:"utf8",mode:420}),await l0.rename(U,A),E("registry",`wrote entry ${$.id} → ${A}`,Y)}catch(J){throw await l0.unlink(U).catch(()=>{}),J}}async function RF($,w=Zw(),Y){let A=WW(w,$);try{await l0.unlink(A),E("registry",`removed entry ${$}`,Y)}catch(U){if(U.code!=="ENOENT")throw U}}async function BW($,w=Zw(),Y){let A=WW(w,$);try{let U=await l0.readFile(A,"utf8"),X=JSON.parse(U);if(!NF(X))return E("registry",`entry ${$} failed validation, removing`,Y),await l0.unlink(A).catch(()=>{}),null;return X}catch(U){if(U.code==="ENOENT")return null;if(U instanceof SyntaxError)return E("registry",`entry ${$} has invalid JSON, removing`,Y),await l0.unlink(A).catch(()=>{}),null;throw U}}async function MF($=Zw(),w){let Y;try{Y=await l0.readdir($)}catch(U){if(U.code==="ENOENT")return[];throw U}let A=[];for(let U of Y){if(!U.endsWith(".json"))continue;let X=U.slice(0,-5);if(!c1(X))continue;let J=await BW(X,$,w);if(J)A.push(J)}return A}fw();import{execSync as tq}from"node:child_process";import*as LX from"node:http";import*as SF from"node:net";import*as A0 from"node:process";var HX=($,w)=>(Y)=>`\x1B[${$}m${Y}\x1B[${w}m`,y$={bold:HX(1,22),dim:HX(2,22),green:HX(32,39),cyan:HX(36,39)};iJ();nf();fw();hY();f0();import*as IF from"node:fs";import*as yF from"node:path";import*as C$ from"node:process";function iq($,w){let A=(w&&w!=="/"?`${$}${w}`:$).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128);return A.length>0?A:"rpx"}async function jW($){if($.proxies.length===0)throw Error("runViaDaemon: no proxies provided");let w=$.verbose??!1,Y=$.registryDir,A=new Set,U=$.proxies.map((G)=>{let F=G.id??iq(G.to,G.path);if(!yY(F))throw Error(`invalid registry id "${F}" derived from to="${G.to}"`);if(A.has(F))throw Error(`duplicate registry id "${F}" — set an explicit \`id\` on one of the proxies`);return A.add(F),{...G,id:F}}),X=new Date().toISOString();for(let G of U)await i2({id:G.id,from:G.from,to:G.to,path:G.path,pid:$.persistent?void 0:C$.pid,cwd:C$.cwd(),createdAt:X,cleanUrls:G.cleanUrls,changeOrigin:G.changeOrigin,pathRewrites:G.pathRewrites,static:G.static},Y,w);let J=await m2({rpxDir:$.rpxDir,verbose:w,spawnCommand:$.spawnCommand,startupTimeoutMs:$.startupTimeoutMs,spawnEnv:$.spawnEnv});for(let G of U){let F=G.static?`static ${typeof G.static==="string"?G.static:G.static.dir}`:G.from;R.success(`https://${G.to} → ${F}`)}if(R.info(`(via rpx daemon pid=${J.pid}; \`rpx daemon:status\` to inspect)`),$.detached)return;let W=!1,f=Y??Hw(),B=U.map((G)=>G.id),j=async()=>{if(W)return;W=!0;for(let G of B)await lf(G,Y,w).catch((F)=>{E("runner",`removeEntry(${G}) failed: ${F}`,w)})},z=(G)=>{E("runner",`received ${G}, unregistering ${B.length} entries`,w),j().finally(()=>C$.exit(0))};C$.once("SIGINT",z),C$.once("SIGTERM",z),C$.once("exit",()=>{if(W)return;for(let G of B)try{IF.unlinkSync(yF.join(f,`${G}.json`))}catch{}}),await new Promise(()=>{})}f0();import{exec as cq}from"node:child_process";import xw from"node:fs";import hF from"node:os";import FW from"node:path";import*as SY from"node:process";import{promisify as vq}from"node:util";var OY=vq(cq);function CF($){let w=$.trim().toLowerCase();return w==="localhost"||w.endsWith(".localhost")||w.endsWith(".localhost.")}var z$=SY.platform==="win32"?FW.join(SY.env.windir||"C:\\Windows","System32","drivers","etc","hosts"):"/etc/hosts",zW=!1;async function NX($){if(SY.platform==="win32")throw Error("Administrator privileges required on Windows");if(rU()){let{stdout:A}=await OY($);return A}let w=Sw(),Y=$.replace(/'/g,"'\\''");try{if(w){let{stdout:A}=await OY(`echo '${w}' | sudo -S sh -c '${Y}' 2>/dev/null`);return zW=!0,A}if(zW)try{let{stdout:A}=await OY(`sudo -n sh -c '${Y}'`);return A}catch(A){E("hosts","Cached sudo privileges expired, requesting again",!0)}try{let{stdout:A}=await OY(`sudo -n sh -c '${Y}'`);return zW=!0,A}catch{throw Error("sudo required but no cached credentials (set SUDO_PASSWORD in .env or run sudo -v)")}}catch(A){throw Error(`Failed to execute sudo command: ${A.message}`)}}async function _Y($,w){let Y=$.filter((U)=>!CF(U)),A=$.filter((U)=>CF(U));if(A.length>0)E("hosts",`Skipping /etc/hosts for loopback dev names: ${A.join(", ")}`,w);if(Y.length===0)return;E("hosts",`Adding hosts: ${Y.join(", ")}`,w),E("hosts",`Using hosts file at: ${z$}`,w);try{let U;try{U=await xw.promises.readFile(z$,"utf-8")}catch{E("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{U=await NX(`cat "${z$}"`)}catch(f){throw console.log(" Could not read hosts file — skipping hosts setup"),E("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let X=Y.filter((f)=>{let B=`127.0.0.1 ${f}`,j=`::1 ${f}`;return!U.includes(B)&&!U.includes(j)});if(X.length===0){E("hosts","All hosts already exist in hosts file",w);return}let J=X.map((f)=>`
261
263
  # Added by rpx
262
264
  127.0.0.1 ${f}
263
265
  ::1 ${f}`).join(`
264
- `),W=$W.join(FF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await xw.promises.writeFile(W,X+U,"utf8"),await z8(`cat "${W}" | tee "${T$}" > /dev/null`),console.log(` Hosts updated: ${J.join(", ")}`)}catch(f){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),J.forEach((B)=>{console.log(` 127.0.0.1 ${B}`),console.log(` ::1 ${B}`)}),console.log(` Or run: sudo nano ${T$}`)}finally{try{await xw.promises.unlink(W)}catch{}}}catch(X){G("hosts",`Failed to manage hosts file: ${X.message}`,w)}}async function EF($,w){G("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let A;try{A=await xw.promises.readFile(T$,"utf-8")}catch{G("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{A=await z8(`cat "${T$}"`)}catch(f){throw G("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let Y=A.split(`
265
- `),X=!1,J=Y.filter((f)=>{if($.some((j)=>f.includes(` ${j}`)&&(f.includes("127.0.0.1")||f.includes("::1"))))return X=!0,!1;if(f.trim()==="# Added by rpx")return X=!0,!1;return!0});if(!X){G("hosts","No matching hosts found to remove",w);return}while(J[J.length-1]?.trim()==="")J.pop();let U=`${J.join(`
266
+ `),W=FW.join(hF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await xw.promises.writeFile(W,U+J,"utf8"),await NX(`cat "${W}" | tee "${z$}" > /dev/null`),console.log(` Hosts updated: ${X.join(", ")}`)}catch(f){console.log(" Could not update hosts file automatically"),console.log(" Add these entries to /etc/hosts:"),X.forEach((B)=>{console.log(` 127.0.0.1 ${B}`),console.log(` ::1 ${B}`)}),console.log(` Or run: sudo nano ${z$}`)}finally{try{await xw.promises.unlink(W)}catch{}}}catch(U){E("hosts",`Failed to manage hosts file: ${U.message}`,w)}}async function VF($,w){E("hosts",`Removing hosts: ${$.join(", ")}`,w);try{let Y;try{Y=await xw.promises.readFile(z$,"utf-8")}catch{E("hosts","Reading hosts file requires elevated permissions, using sudo",w);try{Y=await NX(`cat "${z$}"`)}catch(f){throw E("hosts",`sudo read also failed: ${f}`,w),Error(`Cannot read hosts file: ${f}`)}}let A=Y.split(`
267
+ `),U=!1,X=A.filter((f)=>{if($.some((j)=>f.includes(` ${j}`)&&(f.includes("127.0.0.1")||f.includes("::1"))))return U=!0,!1;if(f.trim()==="# Added by rpx")return U=!0,!1;return!0});if(!U){E("hosts","No matching hosts found to remove",w);return}while(X[X.length-1]?.trim()==="")X.pop();let J=`${X.join(`
266
268
  `)}
267
- `,W=$W.join(FF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await xw.promises.writeFile(W,U,"utf8"),await z8(`cat "${W}" | tee "${T$}" > /dev/null`),G("hosts","Hosts removed successfully",w)}catch(f){G("hosts","Could not clean up hosts file automatically",w)}finally{try{await xw.promises.unlink(W)}catch(f){G("hosts",`Failed to remove temporary file: ${f}`,w)}}}catch(A){G("hosts",`Failed to clean up hosts file: ${A.message}`,w)}}async function OA($,w){G("hosts",`Checking hosts: ${$}`,w);let A;try{A=await xw.promises.readFile(T$,"utf-8")}catch(Y){G("hosts",`Error reading hosts file: ${Y}`,w);try{let X=Qw(),J;if(X)J=`echo '${X}' | sudo -S cat "${T$}" 2>/dev/null`;else J=`sudo -n cat "${T$}" 2>/dev/null || cat "${T$}" 2>/dev/null || echo ""`;let{stdout:U}=await hA(J);A=U}catch(X){return G("hosts",`Cannot read hosts file, assuming entries don't exist: ${X}`,w),$.map(()=>!1)}}return $.map((Y)=>{let X=`127.0.0.1 ${Y}`,J=`::1 ${Y}`;return A.includes(X)||A.includes(J)})}aX();f0();import*as F8 from"node:net";function Pw($,w,A){return G("port",`Checking if port ${$} is in use on ${w}`,A),new Promise((Y)=>{let X=F8.createServer(),J=setTimeout(()=>{G("port",`Checking port ${$} timed out, assuming it's in use`,A),X.close(),Y(!0)},3000);X.once("error",(U)=>{if(clearTimeout(J),U.code==="EADDRINUSE")G("port",`Port ${$} is in use`,A),Y(!0);else G("port",`Error checking port ${$}: ${U.message}`,A),Y(!0)}),X.once("listening",()=>{clearTimeout(J),G("port",`Port ${$} is available`,A),X.close(),Y(!1)});try{X.listen($,w)}catch(U){clearTimeout(J),G("port",`Exception checking port ${$}: ${U}`,A),Y(!0)}})}async function MR($,w,A,Y=50){G("port",`Finding available port starting from ${$} (max attempts: ${Y})`,A);let X=$,J=0;while(J<Y){if(J++,!await Pw(X,w,A))return G("port",`Found available port: ${X} after ${J} attempts`,A),X;G("port",`Port ${X} is in use, trying ${X+1} (attempt ${J}/${Y})`,A),X++}throw Error(`Unable to find available port after ${Y} attempts starting from ${$}`)}function GF($,w,A=5000,Y){return G("port",`Testing connection to ${w}:${$}`,Y),new Promise((X)=>{let J=F8.connect({host:w,port:$,timeout:A});J.once("connect",()=>{G("port",`Successfully connected to ${w}:${$}`,Y),J.end(),X(!0)}),J.once("timeout",()=>{G("port",`Connection to ${w}:${$} timed out`,Y),J.destroy(),X(!1)}),J.once("error",(U)=>{G("port",`Failed to connect to ${w}:${$}: ${U.message}`,Y),J.destroy(),X(!1)})})}class E8{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,A=50){this.hostname=$,this.verbose=w,this.maxRetries=A}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Pw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await GF($,this.hostname,3000,this.verbose))return G("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let A=await MR($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await GF(A,this.hostname,3000,this.verbose))if(A<$+this.maxRetries)return this.findNextAvailablePort(A+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(A),A}releasePort($){G("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var C3=new E8;fw();f0();import{spawn as IR}from"node:child_process";import*as bw from"node:process";class G8{processes=new Map;isShuttingDown=!1;async startProcess($,w,A){if(this.processes.has($)){G("start",`Process ${$} is already running`,A);return}let[Y,...X]=w.command.split(" "),J=w.cwd||bw.cwd();G("start",`Starting process ${$}:`,A),G("start",` Command: ${Y} ${X.join(" ")}`,A),G("start",` Working directory: ${J}`,A),G("start",` Environment variables: ${E$(w.env)}`,A);let U=IR(Y,X,{cwd:J,env:{...bw.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:J,process:U,env:w.env}),new Promise((W,f)=>{if(U.on("error",(B)=>{if(!this.isShuttingDown)G("start",`Process ${$} failed to start: ${B}`,A),this.processes.delete($),f(B),bw.emit("SIGINT")}),U.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)G("start",`Process ${$} exited with code ${B}`,A),this.processes.delete($),f(Error(`Process ${$} exited with code ${B}`)),bw.emit("SIGINT")}),A)U.stdout?.on("data",(B)=>{G("process",`[${$}] ${B.toString().trim()}`,!0)}),U.stderr?.on("data",(B)=>{G("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&U.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else G("start",`Process ${$} started successfully`,A),W()},1000)})}async stopProcess($,w){let A=this.processes.get($);if(!A?.process){G("start",`No process found for ${$}`,w);return}return G("start",`Stopping process ${$}`,w),new Promise((Y)=>{if(!A.process){Y();return}A.process.once("exit",()=>{this.processes.delete($),G("start",`Process ${$} stopped`,w),Y()});try{A.process.kill("SIGTERM"),setTimeout(()=>{if(A.process){G("start",`Force killing process ${$}`,w);try{A.process.kill("SIGKILL")}catch(X){}}},3000)}catch(X){G("start",`Error stopping process ${$}: ${X}`,w),this.processes.delete($),Y()}})}async stopAll($){if(this.isShuttingDown){G("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,G("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((A)=>this.stopProcess(A,$).catch((Y)=>{q.error(`Failed to stop process ${A}:`,Y)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var Q3=new G8;import{timingSafeEqual as yR}from"node:crypto";function CR($,w){if($==null)return!1;let A=Buffer.from($),Y=Buffer.from(w);if(A.length!==Y.length)return!1;return yR(A,Y)}function K8($){return $.toLowerCase().replace(/\.$/,"")}var hR=["/.well-known/acme-challenge/"];function VR($){let w=$.headers.get("host");if(w)return K8(w.split(":")[0]);try{return K8(new URL($.url).hostname)}catch{return""}}function KF($){let w=$.header.toLowerCase(),A=new Set,Y=[];for(let f of $.hosts){let B=K8(f);if(B.startsWith("*."))Y.push(B);else A.add(B)}let X=$.exemptPaths??hR,J=$.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
268
- `,U=(f)=>{let B=K8(f);return A.has(B)||Y.some((j)=>eX(B,j))},W=(f)=>{let B=VR(f);if(!U(B))return;let j="/";try{j=new URL(f.url).pathname}catch{}if(X.some((z)=>j.startsWith(z)))return;if(CR(f.headers.get(w),$.value))return;return new Response(J,{status:403,headers:{"content-type":"text/plain"}})};return W.protects=U,W}oX();$8();KA();f0();var H8=new G8,OR="0.12.0",QR=new E8("0.0.0.0"),QA=new Set,wW=!1,T8=null,AW=null;async function N8($){if(wW)return G("cleanup","Cleanup already in progress, skipping",$?.verbose),AW||Promise.resolve();wW=!0,G("cleanup","Starting cleanup process",$?.verbose),AW=new Promise((w)=>{T8=w});try{await H8.stopAll($?.verbose),q.info("Shutting down proxy servers...");let w=[],A=Array.from(QA).map((Y)=>new Promise((X)=>{Y.close(()=>{G("cleanup","Server closed successfully",$?.verbose),X()})}));if(w.push(...A),$?.hosts&&$.domains?.length){G("cleanup","Cleaning up hosts file entries",$?.verbose),G("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let Y=$.domains.filter((X)=>{if(X==="test.local")return!0;return X!=="localhost"&&!X.startsWith("localhost.")&&X!=="127.0.0.1"});if(G("cleanup",`Filtered domains for cleanup: ${JSON.stringify(Y)}`,$?.verbose),Y.length>0)q.info("Cleaning up hosts file entries..."),w.push(EF(Y,$?.verbose).then(()=>{G("cleanup",`Removed hosts entries for ${Y.join(", ")}`,$?.verbose)}).catch((X)=>{G("cleanup",`Failed to remove hosts entries: ${X}`,$?.verbose),q.warn(`Failed to clean up hosts file entries for ${Y.join(", ")}:`,X)}))}if($?.certs&&$.domains?.length){G("cleanup","Cleaning up SSL certificates",$?.verbose),q.info("Cleaning up SSL certificates...");let Y=$.domains.map(async(X)=>{try{await zz(X,$?.verbose),G("cleanup",`Removed certificates for ${X}`,$?.verbose)}catch(J){G("cleanup",`Failed to remove certificates for ${X}: ${J}`,$?.verbose),q.warn(`Failed to clean up certificates for ${X}:`,J)}});w.push(...Y)}await Promise.allSettled(w),G("cleanup","All cleanup tasks completed successfully",$?.verbose),q.success("All cleanup tasks completed successfully")}catch(w){G("cleanup",`Error during cleanup: ${w}`,$?.verbose),q.error("Error during cleanup:",w)}finally{if(T8)T8();T8=null,wW=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(Y0.env.NODE_ENV!=="test"&&Y0.env.BUN_ENV!=="test"&&!w)Y0.exit(0)}return AW}var YW=!1;function XW($){if(YW){G("signal",`Received second ${$} signal, forcing exit`,!0),Y0.exit(1);return}YW=!0,G("signal",`Received ${$} signal, initiating cleanup`,!0),N8().catch((w)=>{G("signal",`Cleanup failed after ${$}: ${w}`,!0),Y0.exit(1)}).finally(()=>{YW=!1})}Y0.once("SIGINT",()=>XW("SIGINT"));Y0.once("SIGTERM",()=>XW("SIGTERM"));Y0.on("uncaughtException",($)=>{G("process",`Uncaught exception: ${$}`,!0),q.error("Uncaught exception:",$),XW("uncaughtException")});async function SA($,w,A,Y=5){G("connection",`Testing connection to ${$}:${w} (retries left: ${Y})`,A);let X=15000,J=Date.now();if(Y0.env.RPX_BYPASS_CONNECTION_TEST==="true"){G("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,A);return}let U=()=>new Promise((W,f)=>{let B=NF.connect({host:$,port:w,timeout:3000});B.once("connect",()=>{G("connection",`Successfully connected to ${$}:${w}`,A),B.end(),W()}),B.once("timeout",()=>{G("connection",`Connection to ${$}:${w} timed out`,A),B.destroy(),f(Error("Connection timed out"))}),B.once("error",(j)=>{G("connection",`Failed to connect to ${$}:${w}: ${j}`,A),B.destroy(),f(j)})});try{await U()}catch(W){let f=W;if(Date.now()-J>X){G("connection",`Connection test timed out after ${X}ms, but continuing anyway`,A),q.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(f.code==="ECONNREFUSED"&&Y>0)return G("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${Y} retries left)`,A),await new Promise((j)=>setTimeout(j,2000)),SA($,w,A,Y-1);if(Y>0)try{G("connection",`Trying HTTP request to ${$}:${w}`,A),await new Promise((j,z)=>{let E=uw.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(F)=>{G("connection",`Received HTTP response with status: ${F.statusCode}`,A),j()});E.on("error",(F)=>z(F)),E.on("timeout",()=>{E.destroy(),z(Error("HTTP request timed out"))}),E.end()}),G("connection",`HTTP request to ${$}:${w} succeeded`,A);return}catch(j){return G("connection",`HTTP request to ${$}:${w} failed: ${j}`,A),G("connection",`Retrying socket connection in 2 seconds... (${Y} retries left)`,A),await new Promise((z)=>setTimeout(z,2000)),SA($,w,A,Y-1)}let B=`Failed to connect to ${$}:${w} after ${5-Y} attempts: ${f.message}`;G("connection",`${B}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,A),q.warn(B),q.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function RF($){G("server",`Starting server with options: ${E$($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),A=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),Y=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),X=[A.hostname];if(JW($)&&!A.hostname.includes("localhost")&&!A.hostname.includes("127.0.0.1")){G("hosts",`Checking if hosts file entry exists for: ${A.hostname}`,$?.verbose);try{if(!(await OA(X,$.verbose))[0]){q.info(`Adding ${A.hostname} to hosts file...`),q.info("This may require sudo/administrator privileges");try{await LA(X,$.verbose)}catch(W){if(q.error("Failed to add hosts entry:",W.message),q.warn("You can manually add this entry to your hosts file:"),q.warn(`127.0.0.1 ${A.hostname}`),q.warn(`::1 ${A.hostname}`),Y0.platform==="win32")q.warn("On Windows:"),q.warn("1. Run notepad as administrator"),q.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else q.warn("On Unix systems:"),q.warn("sudo nano /etc/hosts")}}else G("hosts",`Host entry already exists for ${A.hostname}`,$.verbose)}catch(U){q.error("Failed to check hosts file:",U.message)}}try{await SA(w.hostname,Y,$.verbose)}catch(U){G("server",`Connection test failed: ${U}`,$.verbose),q.error(U.message),q.warn("Continuing with proxy setup despite connection test failure..."),q.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let J=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=FA({...$,to:A.hostname});if(J=await a$({...$,to:A.hostname,https:$.https}),!J){if(G("ssl",`Generating new certificates for ${A.hostname}`,$.verbose),await S1({...$,from:w.toString(),to:A.hostname,https:$.https}),J=await a$({...$,to:A.hostname,https:$.https}),!J)throw Error(`Failed to load SSL configuration after generating certificates for ${A.hostname}`)}}catch(U){throw G("server",`SSL setup failed: ${U}`,$.verbose),U}G("server",`Setting up reverse proxy with SSL config for ${A.hostname}`,$.verbose),await _R({...$,from:$.from||"localhost:5173",to:A.hostname,fromPort:Y,sourceUrl:{hostname:w.hostname,host:w.host},ssl:J})}async function SR($,w,A,Y,X,J,U,W,f,B,j){G("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${B}`,f);function z(K){let H={};for(let[N,R]of Object.entries(K))if(!N.startsWith(":"))H[N]=R;return H}let E=(K,H)=>{G("request",`Incoming request: ${K.method} ${K.url}`,f);let N=K.url||"/",R=K.method||"GET";if(K instanceof HF.Http2ServerRequest){let C=K.headers;R=C[":method"]||R,N=C[":path"]||N}if(B){if(!N.match(/\.[a-z0-9]+$/i))if(N.endsWith("/"))N=`${N}index.html`;else N=`${N}.html`}let M=z(K.headers);if(j)M.host=`${J.hostname}:${A}`,G("request",`Changed origin: setting host header to ${M.host}`,f);let y={hostname:J.hostname,port:A,path:N,method:R,headers:M};G("request",`Proxy request options: ${E$(y)}`,f);let I=uw.request(y,(C)=>{if(G("response",`Proxy response received with status ${C.statusCode}`,f),B&&C.statusCode===404){let Q=[];if(N.endsWith(".html"))Q.push(N.slice(0,-5));else if(!N.match(/\.[a-z0-9]+$/i))Q.push(`${N}.html`);if(!N.endsWith("/"))Q.push(`${N}/index.html`);if(Q.length>0){G("cleanUrls",`Trying alternative paths: ${Q.join(", ")}`,f);let _=(z0)=>{if(z0.length===0){H.writeHead(C.statusCode||404,C.headers),C.pipe(H);return}let t0=z0[0],r0={...y,path:t0},S=uw.request(r0,(X$)=>{if(X$.statusCode===200)G("cleanUrls",`Found matching path: ${t0}`,f),H.writeHead(X$.statusCode,X$.headers),X$.pipe(H);else _(z0.slice(1))});S.on("error",()=>_(z0.slice(1))),S.end()};_(Q);return}}let j0={...C.headers,"Strict-Transport-Security":"max-age=31536000; includeSubDomains; preload","X-Content-Type-Options":"nosniff"};H.writeHead(C.statusCode||500,j0),C.pipe(H)});I.on("error",(C)=>{G("request",`Proxy request failed: ${C}`,f),q.error("Proxy request failed:",C),H.writeHead(502),H.end(`Proxy Error: ${C.message}`)}),K.pipe(I)};if(G("server",`Creating server with SSL config: ${!!U}`,f),U)return new Promise((K,H)=>{try{let N=Bun.serve({port:Y,hostname:X,reusePort:Sw(),tls:{key:U.key,cert:U.cert,ca:U.ca,requestCert:!1,rejectUnauthorized:!1},async fetch(R){let M=new URL(R.url);if(G("request",`Bun.serve received: ${R.method} ${M.pathname}`,f),B&&M.pathname.endsWith(".html")){let C=M.pathname.replace(/\.html$/,"");return new Response(null,{status:301,headers:{Location:C}})}let y=`http://${J.host}`,I=`${y}${M.pathname}${M.search}`;try{let C=new Headers(R.headers);if(C.set("host",J.host),j)C.set("origin",y);return C.set("x-forwarded-for","127.0.0.1"),C.set("x-forwarded-proto","https"),C.set("x-forwarded-host",w),await fetch(I,{method:R.method,headers:C,body:R.body,redirect:"manual"})}catch(C){return G("request",`Proxy error: ${C}`,f),new Response(`Proxy Error: ${C}`,{status:502})}},error(R){return G("server",`Bun.serve error: ${R}`,f),new Response(`Server Error: ${R.message}`,{status:500})}});QA.add(N),TF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!0,cleanUrls:B,verbose:f}),K()}catch(N){H(N)}});let F=uw.createServer(E);function T(K){return QA.add(K),new Promise((H,N)=>{K.listen(Y,X,()=>{G("server",`Server listening on port ${Y}`,f),TF({from:$,to:w,vitePluginUsage:W,listenPort:Y,ssl:!!U,cleanUrls:B,verbose:f}),H()}),K.on("error",(R)=>{G("server",`Server error: ${R}`,f),N(R)})})}return T(F)}async function _R($){G("setup",`Setting up reverse proxy: ${E$($)}`,$.verbose);let{from:w,to:A,fromPort:Y,sourceUrl:X,ssl:J,verbose:U,cleanup:W,vitePluginUsage:f,changeOrigin:B,cleanUrls:j}=$,z=80,E=443,F="0.0.0.0",T=$.portManager||QR,K=JW($);try{if(K&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1")){if(!(await OA([A],U))[0]){q.warn(`The hostname ${A} isn't in your hosts file. Adding it now...`);try{await LA([A],U),q.success(`Added ${A} to your hosts file.`)}catch(y){q.error(`Failed to add ${A} to your hosts file: ${y}`),q.info(`You may need to manually add '127.0.0.1 ${A}' to your /etc/hosts file.`)}}}else if(K&&Y0.platform!=="darwin"&&A&&A.includes("localhost")&&!A.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await OA([A],U))[0]){G("hosts",`${A} not found in hosts file, adding...`,U);try{await LA([A],U)}catch(y){G("hosts",`Failed to add ${A} to hosts file: ${y}`,U)}}}if(J&&!T.usedPorts.has(z)){if(!await Pw(z,F,U))G("setup","Starting HTTP redirect server",U),qF(U),T.usedPorts.add(z);else if(G("setup","Port 80 is in use, skipping HTTP redirect",U),U)q.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let H=J?E:z,N=await Pw(H,F,U),R;if(N){if(G("setup",`Port ${H} is already in use`,U),U)q.warn(`Port ${H} is already in use. This may be another instance of rpx or another service.`);if(H===443){if(R=await T.getNextAvailablePort(3443,!0),G("setup",`Using port ${R} instead of ${H}`,U),U)q.info(`Using port ${R} instead. Access your site at https://${A}:${R}`)}else if(R=await T.getNextAvailablePort(H+1000,!0),G("setup",`Using port ${R} instead of ${H}`,U),U)q.info(`Using port ${R} instead. Access your site at http://${A}:${R}`)}else R=H,T.usedPorts.add(R),G("setup",`Using standard ${H===443?"HTTPS":"HTTP"} port ${H} for ${A}`,U);await SR(w,A,Y,R,F,X,J,f,U,j,B)}catch(H){G("setup",`Setup failed: ${H}`,U),q.error(`Failed to setup reverse proxy: ${H.message}`),N8({domains:[A],hosts:typeof W==="boolean"?W:W?.hosts,certs:typeof W==="boolean"?W:W?.certs,verbose:U,vitePluginUsage:f})}}function qF($){G("redirect","Starting HTTP redirect server",$);let w=uw.createServer((A,Y)=>{let X=A.headers.host||"";G("redirect",`Redirecting request from ${X}${A.url} to HTTPS`,$),Y.writeHead(301,{Location:`https://${X}${A.url}`}),Y.end()}).listen(80);QA.add(w),G("redirect","HTTP redirect server started",$)}function MF($){let w={...LU,...$};if(G("proxy",`Starting proxy with options: ${E$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){q.error("viaDaemon mode requires both `from` and `to`");return}of({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((f)=>{q.error(`Failed to register with rpx daemon: ${f.message}`),Y0.exit(1)});return}let A=w.to||"",Y=A.split(".").pop()?.toLowerCase()||"",X=Y0.platform==="darwin"&&A&&!A.includes("localhost")&&!A.includes("127.0.0.1"),J=["dev","app","page","new","day","foo"],U=["test","localhost","local","example","invalid"];if(X&&J.includes(Y)&&w?.verbose)q.warn(`The .${Y} TLD may not work reliably for local development`),q.info(` Google owns .${Y} with HSTS preloading, which can bypass local DNS`),q.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(X)Promise.resolve().then(() => (u1(),f8)).then(({setupDevelopmentDns:f})=>{f({domains:[A],verbose:w.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if(w.verbose)if(U.includes(Y))q.success(`DNS server started for .${Y} domains`);else q.success(`DNS server started for .${Y} domains (hosts file entry also added)`)});else G("dns",`Could not start DNS server - ${A} may not resolve in browser`,w.verbose)})}).catch((f)=>{G("dns",`Failed to start DNS server: ${f}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:FA(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};G("proxy",`Server options: ${E$(W)}`,w.verbose),RF(W).catch((f)=>{G("proxy",`Failed to start proxy: ${f}`,w.verbose),q.error(`Failed to start proxy: ${f.message}`),N8({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function kR($){return $?.verbose||!1}function JW($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function IF($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let A=kR(w),Y=JW(w);if(G("config",`Starting with config: ${E$(w,2)}`,A),G("config",`Is multi-proxy? ${"proxies"in w}`,A),G("config",`Hosts management enabled? ${Y}`,A),w.viaDaemon){let K="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((H)=>({id:H.id,from:H.from,to:H.to,path:H.path,cleanUrls:H.cleanUrls??w.cleanUrls,changeOrigin:H.changeOrigin??w.changeOrigin,pathRewrites:H.pathRewrites})):[{id:w.id,from:w.from,to:w.to??"rpx.localhost",path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await of({proxies:K,verbose:A});return}if("proxies"in w&&Array.isArray(w.proxies)){G("servers",`Found ${w.proxies.length} proxies in config`,A);for(let T of w.proxies)if(T.start){let K=`${T.from}-${T.to}`;try{G("watch",`Starting command for ${K} with command: ${T.start.command}`,A),q.info(`Starting command for ${K}...`),await H8.startProcess(K,T.start,A);let H=new URL(T.from?.startsWith("http")?T.from:`http://${T.from}`),N=H.hostname||"localhost",R=Number(H.port)||80;try{await SA(N,R,A),G("watch",`Dev server is ready at ${N}:${R}`,A)}catch(M){G("watch",`Connection check failed, but continuing with proxy setup: ${M}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(H){throw G("watch",`Failed to start command for ${K}: ${H}`,A),Error(`Failed to start command for ${K}: ${H}`)}}else G("watch",`No start command for proxy ${T.from} -> ${T.to}`,A)}else if("start"in w&&w.start){G("watch","Found start command in single proxy config",A);let T=`${w.from}-${w.to}`;try{if(w.start)G("watch",`Starting command: ${w.start.command}`,A),await H8.startProcess(T,w.start,A);let K=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),H=K.hostname||"localhost",N=Number(K.port)||80;try{await SA(H,N,A),G("watch",`Dev server is ready at ${H}:${N}`,A)}catch(R){G("watch",`Connection check failed, but continuing with proxy setup: ${R}`,A),q.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(K){throw G("watch",`Failed to run start command: ${K}`,A),Error(`Failed to run start command: ${K}`)}}else G("watch","No start command found in config",A);let X="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(Y0.platform!=="win32"&&(w.https||Y)){if(!Qw())try{G("sudo","Pre-acquiring sudo credentials for privileged operations",A),LR("sudo -v",{stdio:"inherit"})}catch{G("sudo","Could not pre-acquire sudo credentials",A)}}if(w.https){let T=await a$(w);if(!T){if(G("ssl",`No valid or trusted certificates found for ${X}, generating new ones`,w.verbose),await S1(w),T=await a$(w),!T)throw Error(`Failed to load SSL certificates after generation for ${X}`)}else G("ssl",`Using existing and trusted certificates for ${X}`,w.verbose);w._cachedSSLConfig=T}let J="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((T)=>({...T,https:w.https,cleanup:w.cleanup,cleanUrls:T.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:T.changeOrigin??w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:A,_cachedSSLConfig:w._cachedSSLConfig}],U=J.map((T)=>T.to||"rpx.localhost"),W=w._cachedSSLConfig,f=U.filter((T)=>T&&!T.includes("localhost")&&!T.includes("127.0.0.1")),B=["dev","app","page","new","day","foo"],j=["test","localhost","local","example","invalid"],z=[...new Set(f.map((T)=>T.split(".").pop()?.toLowerCase()))],E=z.filter((T)=>!!T&&B.includes(T));if(E.length>0&&A)q.warn(`The following TLDs may not work reliably for local development: ${E.map((T)=>`.${T}`).join(", ")}`),q.info(" These TLDs have HSTS preloading which can bypass local DNS"),q.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(Y&&Y0.platform==="darwin"&&f.length>0){let{setupDevelopmentDns:T}=await Promise.resolve().then(() => (u1(),f8));if(await T({domains:f,verbose:A})){if(A)if(z.every((N)=>!!N&&j.includes(N)))q.success(`DNS server started for ${z.map((N)=>`.${N}`).join(", ")} domains`);else q.success(`DNS server started for ${z.map((N)=>`.${N}`).join(", ")} domains (hosts file entries also added)`)}else G("dns","Could not start DNS server - custom domains may not resolve",A)}let F=async()=>{G("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:T}=await Promise.resolve().then(() => (u1(),f8));await T({verbose:w.verbose})}catch(T){G("cleanup",`Error stopping DNS server: ${T}`,w.verbose)}try{await H8.stopAll(w.verbose)}catch(T){G("cleanup",`Error stopping processes: ${T}`,w.verbose)}await N8({domains:U,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};if(Y0.on("SIGINT",F),Y0.on("SIGTERM",F),Y0.on("uncaughtException",(T)=>{G("process",`Uncaught exception: ${T}`,!0),console.error("Uncaught exception:",T),F()}),W&&J.length>1){G("proxies",`Creating shared HTTPS server for ${J.length} domains`,A);let T=[],K=new Set;for(let Q of J){let _=Q.to||"rpx.localhost",z0=Q.cleanUrls||!1,t0=Q.path,r0=Z1(t0);if(Q.static)T.push({host:_,path:t0,route:{static:GA(Q.static,z0),cleanUrls:z0,basePath:r0}}),G("proxies",`Route: ${_}${t0??""} → static ${typeof Q.static==="string"?Q.static:Q.static.dir}`,A);else{let S=new URL(Q.from?.startsWith("http")?Q.from:`http://${Q.from}`);T.push({host:_,path:t0,route:{sourceHost:S.host,cleanUrls:z0,changeOrigin:Q.changeOrigin||!1,pathRewrites:Q.pathRewrites,basePath:r0}}),G("proxies",`Route: ${_}${t0??""} → ${S.host}`,A)}if(K.has(_))continue;if(K.add(_),Y&&!TA(_)&&!_.includes("localhost")&&!_.includes("127.0.0.1"))try{if(!(await OA([_],A))[0])await LA([_],A)}catch{G("hosts",`Could not add hosts entry for ${_}`,A)}}if(!await Pw(80,"0.0.0.0",A))qF(A);let N=443;if(await Pw(N,"0.0.0.0",A)){if(G("proxies",`Port ${N} is already in use, cannot start shared proxy`,A),A)q.warn(`Port ${N} is in use. Shared HTTPS proxy cannot start.`);return}let M=x1(T),y=k1((Q,_)=>P1(M,Q,_),A),I=w.originGuard?KF(w.originGuard):null,C=I?(Q,_)=>I(Q)??y(Q,_):y,j0=D1(A);try{let Q=Bun.serve({port:N,hostname:"0.0.0.0",reusePort:Sw(),tls:{key:W.key,cert:W.cert,ca:W.ca,requestCert:!1,rejectUnauthorized:!1},fetch(_,z0){return C(_,z0)},websocket:j0,error(_){return G("server",`Shared proxy server error: ${_}`,A),new Response(`Server Error: ${_.message}`,{status:500})}});QA.add(Q),G("proxies",`Shared HTTPS proxy listening on port ${N} for ${M.size} domains`,A)}catch(Q){G("proxies",`Failed to start shared proxy: ${Q}`,A),console.error("Failed to start shared HTTPS proxy:",Q),F()}}else for(let T of J)try{let K=T.to||"rpx.localhost";G("proxy",`Starting proxy for ${K} with SSL config: ${!!W}`,T.verbose),await RF({from:T.from||"localhost:5173",to:K,cleanUrls:T.cleanUrls||!1,https:T.https||!1,cleanup:T.cleanup||!1,vitePluginUsage:T.vitePluginUsage||!1,verbose:T.verbose||!1,_cachedSSLConfig:W,changeOrigin:T.changeOrigin||!1})}catch(K){G("proxies",`Failed to start proxy for ${T.to}: ${K}`,T.verbose),console.error(`Failed to start proxy for ${T.to}:`,K),F()}}function TF($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${V$.green(V$.bold("rpx"))} ${V$.green(`v${OR}`)}`),console.log(` ${V$.green("➜")} ${V$.dim($?.from??"")} ${V$.dim("➜")} ${V$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${V$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${V$.green("➜")} Clean URLs enabled`)}Ff();var $L=new Ow("rpx",{showTags:!1});function yF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}p0.chdir(ZR(DR(xR(import.meta.url)),".."));var o0=new O8("rpx"),CF="0.12.0";o0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").action(async($)=>{if(!$?.from||!$.to)return IF(ow);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let A={command:$.startCommand};if($.startCwd)A.cwd=$.startCwd;if($.startEnv)try{A.env=JSON.parse($.startEnv)}catch(Y){console.error("Failed to parse start-env JSON:",Y),p0.exit(1)}w.start=A}return MF(w)});o0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let A=yF(ow)?ow.proxies.find((Y)=>Y.to===$||`${Y.from}-${Y.to}`===$):ow.to===$?ow:null;if(!A?.start)console.error(`No watch configuration found for proxy: ${$}`),p0.exit(1);try{await B8.startProcess($,A.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(Y){console.error(`Failed to start dev server for ${$}:`,Y),p0.exit(1)}});o0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await B8.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(A){console.error(`Failed to stop dev server for ${$}:`,A),p0.exit(1)}});o0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await B8.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),p0.exit(1)}});o0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--verbose","Enable verbose logging").action(async($)=>{try{await(await $F({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,verbose:$.verbose??!0})).done,p0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),p0.exit(1)}});o0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,A=await AF({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!A.stopped&&A.pid===null){console.log("rpx daemon is not running");return}if(!A.stopped){console.log(`rpx daemon pid=${A.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${A.pid} stopped${A.forced?" (SIGKILL)":""}`)});o0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??K$(),A=await qw(w),Y=await W8(w),X=$.registryDir,J=await WF(X).catch(()=>[]);if($.json){console.log(JSON.stringify({running:Y,pid:A,pidFile:Mw(w),rpxDir:w,registryDir:X??Zw(),entries:J},null,2));return}if(!Y){if(console.log("rpx daemon: not running"),A!==null)console.log(`(stale pid file at ${Mw(w)} \u2192 pid ${A})`)}else console.log(`rpx daemon: running (pid=${A})`),console.log(`pid file: ${Mw(w)}`);if(console.log(`registry: ${X??Zw()}`),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})`)}});o0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),p0.exit(1);if(!v1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),p0.exit(1);try{await UF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),p0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await wF({rpxDir:$.rpxDir,verbose:$.verbose}),A=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${A} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),p0.exit(1)}});o0.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(!v1($))console.error(`invalid id: ${JSON.stringify($)}`),p0.exit(1);let A=await sf($,w.registryDir,w.verbose);if(!A){console.log(`no registry entry for id=${$}`);return}await fF($,w.registryDir,w.verbose),console.log(`unregistered ${A.to} (id=${$})`)});o0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??K$();if(await W8(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await YF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});o0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(CF)});o0.version(CF);o0.help();o0.run();
269
+ `,W=FW.join(hF.tmpdir(),`rpx-hosts-${Date.now()}.tmp`);try{await xw.promises.writeFile(W,J,"utf8"),await NX(`cat "${W}" | tee "${z$}" > /dev/null`),E("hosts","Hosts removed successfully",w)}catch(f){E("hosts","Could not clean up hosts file automatically",w)}finally{try{await xw.promises.unlink(W)}catch(f){E("hosts",`Failed to remove temporary file: ${f}`,w)}}}catch(Y){E("hosts",`Failed to clean up hosts file: ${Y.message}`,w)}}async function kY($,w){E("hosts",`Checking hosts: ${$}`,w);let Y;try{Y=await xw.promises.readFile(z$,"utf-8")}catch(A){E("hosts",`Error reading hosts file: ${A}`,w);try{let U=Sw(),X;if(U)X=`echo '${U}' | sudo -S cat "${z$}" 2>/dev/null`;else X=`sudo -n cat "${z$}" 2>/dev/null || cat "${z$}" 2>/dev/null || echo ""`;let{stdout:J}=await OY(X);Y=J}catch(U){return E("hosts",`Cannot read hosts file, assuming entries don't exist: ${U}`,w),$.map(()=>!1)}}return $.map((A)=>{let U=`127.0.0.1 ${A}`,X=`::1 ${A}`;return Y.includes(U)||Y.includes(X)})}YX();f0();import*as qX from"node:net";function Iw($,w,Y){return E("port",`Checking if port ${$} is in use on ${w}`,Y),new Promise((A)=>{let U=qX.createServer(),X=setTimeout(()=>{E("port",`Checking port ${$} timed out, assuming it's in use`,Y),U.close(),A(!0)},3000);U.once("error",(J)=>{if(clearTimeout(X),J.code==="EADDRINUSE")E("port",`Port ${$} is in use`,Y),A(!0);else E("port",`Error checking port ${$}: ${J.message}`,Y),A(!0)}),U.once("listening",()=>{clearTimeout(X),E("port",`Port ${$} is available`,Y),U.close(),A(!1)});try{U.listen($,w)}catch(J){clearTimeout(X),E("port",`Exception checking port ${$}: ${J}`,Y),A(!0)}})}async function mq($,w,Y,A=50){E("port",`Finding available port starting from ${$} (max attempts: ${A})`,Y);let U=$,X=0;while(X<A){if(X++,!await Iw(U,w,Y))return E("port",`Found available port: ${U} after ${X} attempts`,Y),U;E("port",`Port ${U} is in use, trying ${U+1} (attempt ${X}/${A})`,Y),U++}throw Error(`Unable to find available port after ${A} attempts starting from ${$}`)}function LF($,w,Y=5000,A){return E("port",`Testing connection to ${w}:${$}`,A),new Promise((U)=>{let X=qX.connect({host:w,port:$,timeout:Y});X.once("connect",()=>{E("port",`Successfully connected to ${w}:${$}`,A),X.end(),U(!0)}),X.once("timeout",()=>{E("port",`Connection to ${w}:${$} timed out`,A),X.destroy(),U(!1)}),X.once("error",(J)=>{E("port",`Failed to connect to ${w}:${$}: ${J.message}`,A),X.destroy(),U(!1)})})}class RX{usedPorts=new Set;hostname;verbose;maxRetries;constructor($="0.0.0.0",w,Y=50){this.hostname=$,this.verbose=w,this.maxRetries=Y}async getNextAvailablePort($,w=!1){if(this.usedPorts.has($))return this.findNextAvailablePort($+1,w);if(await Iw($,this.hostname,this.verbose))return this.findNextAvailablePort($+1,w);if(w){if(!await LF($,this.hostname,3000,this.verbose))return E("port",`Port ${$} is available but not connectable, trying next port`,this.verbose),this.findNextAvailablePort($+1,w)}return this.usedPorts.add($),$}async findNextAvailablePort($,w=!1){let Y=await mq($,this.hostname,this.verbose,this.maxRetries);if(w){if(!await LF(Y,this.hostname,3000,this.verbose))if(Y<$+this.maxRetries)return this.findNextAvailablePort(Y+1,w);else throw Error(`Unable to find a connectable port after ${this.maxRetries} attempts`)}return this.usedPorts.add(Y),Y}releasePort($){E("port",`Releasing port ${$}`,this.verbose),this.usedPorts.delete($)}}var l3=new RX;fw();f0();import{spawn as dq}from"node:child_process";import*as MX from"node:process";class IX{processes=new Map;isShuttingDown=!1;async startProcess($,w,Y){if(this.processes.has($)){E("start",`Process ${$} is already running`,Y);return}let[A,...U]=w.command.split(" "),X=w.cwd||MX.cwd();E("start",`Starting process ${$}:`,Y),E("start",` Command: ${A} ${U.join(" ")}`,Y),E("start",` Working directory: ${X}`,Y),E("start",` Environment variables: ${R$(w.env)}`,Y);let J=dq(A,U,{cwd:X,env:{...MX.env,...w.env},shell:!0,stdio:"inherit"});return this.processes.set($,{command:w.command,cwd:X,process:J,env:w.env}),new Promise((W,f)=>{if(J.on("error",(B)=>{if(!this.isShuttingDown)E("start",`Process ${$} failed to start: ${B}`,Y),this.processes.delete($),f(B)}),J.on("exit",(B)=>{if(!this.isShuttingDown&&B!==null&&B!==0)E("start",`Process ${$} exited with code ${B}; leaving the proxy running`,Y),this.processes.delete($),f(Error(`Process ${$} exited with code ${B}`))}),Y)J.stdout?.on("data",(B)=>{E("process",`[${$}] ${B.toString().trim()}`,!0)}),J.stderr?.on("data",(B)=>{E("process",`[${$}] ERR: ${B.toString().trim()}`,!0)});setTimeout(()=>{if(!this.isShuttingDown&&J.killed)this.processes.delete($),f(Error(`Process ${$} was killed during startup`));else E("start",`Process ${$} started successfully`,Y),W()},1000)})}async stopProcess($,w){let Y=this.processes.get($);if(!Y?.process){E("start",`No process found for ${$}`,w);return}return E("start",`Stopping process ${$}`,w),new Promise((A)=>{if(!Y.process){A();return}Y.process.once("exit",()=>{this.processes.delete($),E("start",`Process ${$} stopped`,w),A()});try{Y.process.kill("SIGTERM"),setTimeout(()=>{if(Y.process){E("start",`Force killing process ${$}`,w);try{Y.process.kill("SIGKILL")}catch(U){}}},3000)}catch(U){E("start",`Error stopping process ${$}: ${U}`,w),this.processes.delete($),A()}})}async stopAll($){if(this.isShuttingDown){E("start","Already shutting down, skipping duplicate stopAll call",$);return}this.isShuttingDown=!0,E("start","Stopping all processes",$);let w=Array.from(this.processes.keys()).map((Y)=>this.stopProcess(Y,$).catch((A)=>{R.error(`Failed to stop process ${Y}:`,A)}));await Promise.allSettled(w),this.processes.clear(),this.isShuttingDown=!1}isRunning($){let w=this.processes.get($);return!!w?.process&&!w.process.killed}}var a3=new IX;import{timingSafeEqual as gq}from"node:crypto";function lq($,w){if($==null)return!1;let Y=Buffer.from($),A=Buffer.from(w);if(Y.length!==A.length)return!1;return gq(Y,A)}function yX($){return $.toLowerCase().replace(/\.$/,"")}var nq=["/.well-known/acme-challenge/"];function pq($){let w=$.headers.get("host");if(w)return yX(w.split(":")[0]);try{return yX(new URL($.url).hostname)}catch{return""}}function QF($){let w=$.header.toLowerCase(),Y=new Set,A=[];for(let f of $.hosts){let B=yX(f);if(B.startsWith("*."))A.push(B);else Y.add(B)}let U=$.exemptPaths??nq,X=$.forbiddenMessage??`Forbidden: direct origin access is not allowed; requests must arrive via the CDN.
270
+ `,J=(f)=>{let B=yX(f);return Y.has(B)||A.some((j)=>XX(B,j))},W=(f)=>{let B=pq(f);if(!J(B))return;let j="/";try{j=new URL(f.url).pathname}catch{}if(U.some((z)=>j.startsWith(z)))return;if(lq(f.headers.get(w),$.value))return;return new Response(X,{status:403,headers:{"content-type":"text/plain"}})};return W.protects=J,W}UX();JX();fX();qY();f0();var hX=new IX,rq="0.12.0",aq=new RX("0.0.0.0"),VX=new Set,GW=!1,CX=null,EW=null;async function QX($){if(GW)return E("cleanup","Cleanup already in progress, skipping",$?.verbose),EW||Promise.resolve();GW=!0,E("cleanup","Starting cleanup process",$?.verbose),EW=new Promise((w)=>{CX=w});try{await hX.stopAll($?.verbose),R.info("Shutting down proxy servers...");let w=[],Y=Array.from(VX).map((A)=>new Promise((U)=>{let X=A;try{if(typeof X.stop==="function")X.stop(!0),E("cleanup","Bun server stopped",$?.verbose),U();else if(typeof X.close==="function")X.close(()=>{E("cleanup","Server closed successfully",$?.verbose),U()});else U()}catch(J){E("cleanup",`Error stopping server: ${J}`,$?.verbose),U()}}));if(w.push(...Y),VX.clear(),$?.hosts&&$.domains?.length){E("cleanup","Cleaning up hosts file entries",$?.verbose),E("cleanup",`Original domains for cleanup: ${JSON.stringify($.domains)}`,$?.verbose);let A=$.domains.filter((U)=>{if(U==="test.local")return!0;return U!=="localhost"&&!U.startsWith("localhost.")&&U!=="127.0.0.1"});if(E("cleanup",`Filtered domains for cleanup: ${JSON.stringify(A)}`,$?.verbose),A.length>0)R.info("Cleaning up hosts file entries..."),w.push(VF(A,$?.verbose).then(()=>{E("cleanup",`Removed hosts entries for ${A.join(", ")}`,$?.verbose)}).catch((U)=>{E("cleanup",`Failed to remove hosts entries: ${U}`,$?.verbose),R.warn(`Failed to clean up hosts file entries for ${A.join(", ")}:`,U)}))}if($?.certs&&$.domains?.length){E("cleanup","Cleaning up SSL certificates",$?.verbose),R.info("Cleaning up SSL certificates...");let A=$.domains.map(async(U)=>{try{await M2(U,$?.verbose),E("cleanup",`Removed certificates for ${U}`,$?.verbose)}catch(X){E("cleanup",`Failed to remove certificates for ${U}: ${X}`,$?.verbose),R.warn(`Failed to clean up certificates for ${U}:`,X)}});w.push(...A)}await Promise.allSettled(w),E("cleanup","All cleanup tasks completed successfully",$?.verbose),R.success("All cleanup tasks completed successfully")}catch(w){E("cleanup",`Error during cleanup: ${w}`,$?.verbose),R.error("Error during cleanup:",w)}finally{if(CX)CX();CX=null,GW=!1;let w=$&&"vitePluginUsage"in $&&$.vitePluginUsage===!0;if(A0.env.NODE_ENV!=="test"&&A0.env.BUN_ENV!=="test"&&!w)A0.exit(0)}return EW}var KW=!1;function _F($){if(KW){E("signal",`Received second ${$} signal, forcing exit`,!0),A0.exit(1);return}KW=!0,E("signal",`Received ${$} signal, initiating cleanup`,!0),QX().catch((w)=>{E("signal",`Cleanup failed after ${$}: ${w}`,!0),A0.exit(1)}).finally(()=>{KW=!1})}A0.once("SIGINT",()=>_F("SIGINT"));A0.once("SIGTERM",()=>_F("SIGTERM"));A0.on("uncaughtException",($)=>{R.error("Uncaught exception (continuing):",$)});A0.on("unhandledRejection",($)=>{R.error("Unhandled rejection (continuing):",$)});async function DY($,w,Y,A=5){E("connection",`Testing connection to ${$}:${w} (retries left: ${A})`,Y);let U=15000,X=Date.now();if(A0.env.RPX_BYPASS_CONNECTION_TEST==="true"){E("connection",`Bypassing connection test for ${$}:${w} due to RPX_BYPASS_CONNECTION_TEST flag`,Y);return}let J=()=>new Promise((W,f)=>{let B=SF.connect({host:$,port:w,timeout:3000});B.once("connect",()=>{E("connection",`Successfully connected to ${$}:${w}`,Y),B.end(),W()}),B.once("timeout",()=>{E("connection",`Connection to ${$}:${w} timed out`,Y),B.destroy(),f(Error("Connection timed out"))}),B.once("error",(j)=>{E("connection",`Failed to connect to ${$}:${w}: ${j}`,Y),B.destroy(),f(j)})});try{await J()}catch(W){let f=W;if(Date.now()-X>U){E("connection",`Connection test timed out after ${U}ms, but continuing anyway`,Y),R.warn(`Connection test to ${$}:${w} timed out, but RPX will try to proceed anyway.`);return}if(f.code==="ECONNREFUSED"&&A>0)return E("connection",`Connection refused, server might be starting up. Retrying in 2 seconds... (${A} retries left)`,Y),await new Promise((j)=>setTimeout(j,2000)),DY($,w,Y,A-1);if(A>0)try{E("connection",`Trying HTTP request to ${$}:${w}`,Y),await new Promise((j,z)=>{let G=LX.request({hostname:$,port:w,path:"/",method:"HEAD",timeout:5000},(F)=>{E("connection",`Received HTTP response with status: ${F.statusCode}`,Y),j()});G.on("error",(F)=>z(F)),G.on("timeout",()=>{G.destroy(),z(Error("HTTP request timed out"))}),G.end()}),E("connection",`HTTP request to ${$}:${w} succeeded`,Y);return}catch(j){return E("connection",`HTTP request to ${$}:${w} failed: ${j}`,Y),E("connection",`Retrying socket connection in 2 seconds... (${A} retries left)`,Y),await new Promise((z)=>setTimeout(z,2000)),DY($,w,Y,A-1)}let B=`Failed to connect to ${$}:${w} after ${5-A} attempts: ${f.message}`;E("connection",`${B}. To bypass this check set RPX_BYPASS_CONNECTION_TEST=true`,Y),R.warn(B),R.warn("RPX will try to continue anyway. If you're sure this is correct, you can set RPX_BYPASS_CONNECTION_TEST=true to skip this check.")}}async function kF($){E("server",`Starting server with options: ${R$($)}`,$.verbose);let w=new URL(($.from?.startsWith("http")?$.from:`http://${$.from}`)||"localhost:5173"),Y=new URL(($.to?.startsWith("http")?$.to:`http://${$.to}`)||"rpx.localhost"),A=Number.parseInt(w.port)||(w.protocol.includes("https:")?443:80),U=[Y.hostname];if(HW($)&&!Y.hostname.includes("localhost")&&!Y.hostname.includes("127.0.0.1")){E("hosts",`Checking if hosts file entry exists for: ${Y.hostname}`,$?.verbose);try{if(!(await kY(U,$.verbose))[0]){R.info(`Adding ${Y.hostname} to hosts file...`),R.info("This may require sudo/administrator privileges");try{await _Y(U,$.verbose)}catch(W){if(R.error("Failed to add hosts entry:",W.message),R.warn("You can manually add this entry to your hosts file:"),R.warn(`127.0.0.1 ${Y.hostname}`),R.warn(`::1 ${Y.hostname}`),A0.platform==="win32")R.warn("On Windows:"),R.warn("1. Run notepad as administrator"),R.warn("2. Open C:\\Windows\\System32\\drivers\\etc\\hosts");else R.warn("On Unix systems:"),R.warn("sudo nano /etc/hosts")}}else E("hosts",`Host entry already exists for ${Y.hostname}`,$.verbose)}catch(J){R.error("Failed to check hosts file:",J.message)}}try{await DY(w.hostname,A,$.verbose)}catch(J){E("server",`Connection test failed: ${J}`,$.verbose),R.error(J.message),R.warn("Continuing with proxy setup despite connection test failure..."),R.info("If you need to bypass connection testing, set environment variable RPX_BYPASS_CONNECTION_TEST=true")}let X=$._cachedSSLConfig||null;if($.https)try{if($.https===!0)$.https=TY({...$,to:Y.hostname});if(X=await a$({...$,to:Y.hostname,https:$.https}),!X){if(E("ssl",`Generating new certificates for ${Y.hostname}`,$.verbose),await O1({...$,from:w.toString(),to:Y.hostname,https:$.https}),X=await a$({...$,to:Y.hostname,https:$.https}),!X)throw Error(`Failed to load SSL configuration after generating certificates for ${Y.hostname}`)}}catch(J){throw E("server",`SSL setup failed: ${J}`,$.verbose),J}E("server",`Setting up reverse proxy with SSL config for ${Y.hostname}`,$.verbose),await oq({...$,from:$.from||"localhost:5173",to:Y.hostname,fromPort:A,sourceUrl:{hostname:w.hostname,host:w.host},ssl:X})}async function sq($,w,Y,A,U,X,J,W,f){E("proxy",`Creating proxy server ${$} -> ${w} with cleanUrls: ${W}`,J);let B=[{host:w,route:{sourceHost:A.host,cleanUrls:W||!1,changeOrigin:f||!1,basePath:"/"}}];if(!TW({routeEntries:B,listenPort:Y,sslConfig:U,originGuard:null,verbose:J??!1}))throw Error(`Failed to start proxy server for ${w} on port ${Y}`);$R({from:$,to:w,vitePluginUsage:X,listenPort:Y,ssl:!!U,cleanUrls:W,verbose:J})}async function oq($){E("setup",`Setting up reverse proxy: ${R$($)}`,$.verbose);let{from:w,to:Y,sourceUrl:A,ssl:U,verbose:X,cleanup:J,vitePluginUsage:W,changeOrigin:f,cleanUrls:B}=$,j=80,z=443,G="0.0.0.0",F=$.portManager||aq,T=HW($);try{if(T&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1")){if(!(await kY([Y],X))[0]){R.warn(`The hostname ${Y} isn't in your hosts file. Adding it now...`);try{await _Y([Y],X),R.success(`Added ${Y} to your hosts file.`)}catch(I){R.error(`Failed to add ${Y} to your hosts file: ${I}`),R.info(`You may need to manually add '127.0.0.1 ${Y}' to your /etc/hosts file.`)}}}else if(T&&A0.platform!=="darwin"&&Y&&Y.includes("localhost")&&!Y.match(/^(localhost|127\.0\.0\.1)$/)){if(!(await kY([Y],X))[0]){E("hosts",`${Y} not found in hosts file, adding...`,X);try{await _Y([Y],X)}catch(I){E("hosts",`Failed to add ${Y} to hosts file: ${I}`,X)}}}if(U&&!F.usedPorts.has(j)){if(!await Iw(j,G,X))E("setup","Starting HTTP redirect server",X),DF(X),F.usedPorts.add(j);else if(E("setup","Port 80 is in use, skipping HTTP redirect",X),X)R.warn("Port 80 is in use, HTTP to HTTPS redirect will not be available")}let K=U?z:j,H=await Iw(K,G,X),q;if(H){if(E("setup",`Port ${K} is already in use`,X),X)R.warn(`Port ${K} is already in use. This may be another instance of rpx or another service.`);if(K===443){if(q=await F.getNextAvailablePort(3443,!0),E("setup",`Using port ${q} instead of ${K}`,X),X)R.info(`Using port ${q} instead. Access your site at https://${Y}:${q}`)}else if(q=await F.getNextAvailablePort(K+1000,!0),E("setup",`Using port ${q} instead of ${K}`,X),X)R.info(`Using port ${q} instead. Access your site at http://${Y}:${q}`)}else q=K,F.usedPorts.add(q),E("setup",`Using standard ${K===443?"HTTPS":"HTTP"} port ${K} for ${Y}`,X);await sq(w,Y,q,A,U,W,X,B,f)}catch(K){E("setup",`Setup failed: ${K}`,X),R.error(`Failed to setup reverse proxy: ${K.message}`),QX({domains:[Y],hosts:typeof J==="boolean"?J:J?.hosts,certs:typeof J==="boolean"?J:J?.certs,verbose:X,vitePluginUsage:W})}}function DF($,w=80,Y=443){E("redirect",`Starting HTTP redirect server on port ${w}`,$);let A=LX.createServer((U,X)=>{let J=U.headers.host||"",W=J.includes(":")?J.slice(0,J.indexOf(":")):J,f=Y===443?W:`${W}:${Y}`;E("redirect",`Redirecting request from ${J}${U.url} to https://${f}`,$),X.writeHead(301,{Location:`https://${f}${U.url}`}),X.end()}).listen(w);VX.add(A),E("redirect","HTTP redirect server started",$)}function ZF($){let w={...uJ,...$};if(E("proxy",`Starting proxy with options: ${R$(w)}`,w?.verbose),w.viaDaemon){if(!w.from||!w.to){R.error("viaDaemon mode requires both `from` and `to`");return}jW({proxies:[{id:w.id,from:w.from,to:w.to,path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}],verbose:w.verbose}).catch((f)=>{R.error(`Failed to register with rpx daemon: ${f.message}`),A0.exit(1)});return}let Y=w.to||"",A=Y.split(".").pop()?.toLowerCase()||"",U=A0.platform==="darwin"&&Y&&!Y.includes("localhost")&&!Y.includes("127.0.0.1"),X=["dev","app","page","new","day","foo"],J=["test","localhost","local","example","invalid"];if(U&&X.includes(A)&&w?.verbose)R.warn(`The .${A} TLD may not work reliably for local development`),R.info(` Google owns .${A} with HSTS preloading, which can bypass local DNS`),R.info(" Consider using a reserved TLD: .test, .localhost, or .local");if(U)Promise.resolve().then(() => (b1(),GX)).then(({setupDevelopmentDns:f})=>{f({domains:[Y],verbose:w.verbose}).then((B)=>{if(B)Promise.resolve().then(()=>{if(w.verbose)if(J.includes(A))R.success(`DNS server started for .${A} domains`);else R.success(`DNS server started for .${A} domains (hosts file entry also added)`)});else E("dns",`Could not start DNS server - ${Y} may not resolve in browser`,w.verbose)})}).catch((f)=>{E("dns",`Failed to start DNS server: ${f}`,w.verbose)});let W={from:w.from,to:w.to,cleanUrls:w.cleanUrls,https:TY(w),cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,changeOrigin:w.changeOrigin,verbose:w.verbose,regenerateUntrustedCerts:w.regenerateUntrustedCerts};E("proxy",`Server options: ${R$(W)}`,w.verbose),kF(W).catch((f)=>{E("proxy",`Failed to start proxy: ${f}`,w.verbose),R.error(`Failed to start proxy: ${f.message}`),QX({domains:[w.to],hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose})})}function eq($){return $?.verbose||!1}function HW($){if($?.hostsManagement===!1)return!1;let w=$?.cleanup;if(w===!1)return!1;if(w&&typeof w==="object"&&w.hosts===!1)return!1;return!0}async function xF($){let w={from:"localhost:5173",to:"rpx.localhost",https:!1,cleanup:{hosts:!0,certs:!1},vitePluginUsage:!1,verbose:!1,cleanUrls:!1,changeOrigin:!1,regenerateUntrustedCerts:!0};if($)w={...w,...$};let Y=eq(w),A=HW(w);if(E("config",`Starting with config: ${R$(w,2)}`,Y),E("config",`Is multi-proxy? ${"proxies"in w}`,Y),E("config",`Hosts management enabled? ${A}`,Y),w.viaDaemon){let C="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((O)=>({id:O.id,from:O.from,to:O.to,path:O.path,cleanUrls:O.cleanUrls??w.cleanUrls,changeOrigin:O.changeOrigin??w.changeOrigin,pathRewrites:O.pathRewrites})):[{id:w.id,from:w.from,to:w.to??"rpx.localhost",path:w.path,cleanUrls:w.cleanUrls,changeOrigin:w.changeOrigin,pathRewrites:w.pathRewrites}];await jW({proxies:C,verbose:Y});return}if("proxies"in w&&Array.isArray(w.proxies)){E("servers",`Found ${w.proxies.length} proxies in config`,Y);for(let N of w.proxies)if(N.start){let C=`${N.from}-${N.to}`;try{E("watch",`Starting command for ${C} with command: ${N.start.command}`,Y),R.info(`Starting command for ${C}...`),await hX.startProcess(C,N.start,Y);let O=new URL(N.from?.startsWith("http")?N.from:`http://${N.from}`),p=O.hostname||"localhost",x0=Number(O.port)||80;try{await DY(p,x0,Y),E("watch",`Dev server is ready at ${p}:${x0}`,Y)}catch(h$){E("watch",`Connection check failed, but continuing with proxy setup: ${h$}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(O){throw E("watch",`Failed to start command for ${C}: ${O}`,Y),Error(`Failed to start command for ${C}: ${O}`)}}else E("watch",`No start command for proxy ${N.from} -> ${N.to}`,Y)}else if("start"in w&&w.start){E("watch","Found start command in single proxy config",Y);let N=`${w.from}-${w.to}`;try{if(w.start)E("watch",`Starting command: ${w.start.command}`,Y),await hX.startProcess(N,w.start,Y);let C=new URL(w.from?.startsWith("http")?w.from:`http://${w.from}`),O=C.hostname||"localhost",p=Number(C.port)||80;try{await DY(O,p,Y),E("watch",`Dev server is ready at ${O}:${p}`,Y)}catch(x0){E("watch",`Connection check failed, but continuing with proxy setup: ${x0}`,Y),R.warn("Dev server connection check failed. RPX will try to proceed anyway...")}}catch(C){throw E("watch",`Failed to run start command: ${C}`,Y),Error(`Failed to run start command: ${C}`)}}else E("watch","No start command found in config",Y);let U="proxies"in w&&Array.isArray(w.proxies)?w.proxies[0]?.to:("to"in w)?w.to:"rpx.localhost";if(A0.platform!=="win32"&&(w.https||A)){if(!Sw())try{E("sudo","Pre-acquiring sudo credentials for privileged operations",Y),tq("sudo -v",{stdio:"inherit"})}catch{E("sudo","Could not pre-acquire sudo credentials",Y)}}let X=[];if(w.productionCerts){if(X=await x1(w.productionCerts,Y),X.length>0)E("ssl",`Using ${X.length} production SNI cert(s): ${X.map((N)=>N.serverName).join(", ")}`,Y)}if(w.https){let N=X.length>0?null:await a$(w);if(!N&&X.length===0){if(E("ssl",`No valid or trusted certificates found for ${U}, generating new ones`,w.verbose),await O1(w),N=await a$(w),!N)throw Error(`Failed to load SSL certificates after generation for ${U}`)}else E("ssl",`Using existing and trusted certificates for ${U}`,w.verbose);w._cachedSSLConfig=N}let J="proxies"in w&&Array.isArray(w.proxies)?w.proxies.map((N)=>({...N,https:w.https,cleanup:w.cleanup,cleanUrls:N.cleanUrls??("cleanUrls"in w?w.cleanUrls:!1),vitePluginUsage:w.vitePluginUsage,changeOrigin:N.changeOrigin??w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig})):[{from:"from"in w?w.from:"localhost:5173",to:"to"in w?w.to:"rpx.localhost",cleanUrls:"cleanUrls"in w?w.cleanUrls:!1,https:w.https,cleanup:w.cleanup,vitePluginUsage:w.vitePluginUsage,start:"start"in w?w.start:void 0,changeOrigin:w.changeOrigin,verbose:Y,_cachedSSLConfig:w._cachedSSLConfig}],W=J.map((N)=>N.to||"rpx.localhost"),f=X.length>0?X:w._cachedSSLConfig??null,B=W.filter((N)=>N&&!N.includes("localhost")&&!N.includes("127.0.0.1")),j=["dev","app","page","new","day","foo"],z=["test","localhost","local","example","invalid"],G=[...new Set(B.map((N)=>N.split(".").pop()?.toLowerCase()))],F=G.filter((N)=>!!N&&j.includes(N));if(F.length>0&&Y)R.warn(`The following TLDs may not work reliably for local development: ${F.map((N)=>`.${N}`).join(", ")}`),R.info(" These TLDs have HSTS preloading which can bypass local DNS"),R.info(" Consider using reserved TLDs: .test, .localhost, or .local");if(A&&A0.platform==="darwin"&&B.length>0){let{setupDevelopmentDns:N}=await Promise.resolve().then(() => (b1(),GX));if(await N({domains:B,verbose:Y})){if(Y)if(G.every((p)=>!!p&&z.includes(p)))R.success(`DNS server started for ${G.map((p)=>`.${p}`).join(", ")} domains`);else R.success(`DNS server started for ${G.map((p)=>`.${p}`).join(", ")} domains (hosts file entries also added)`)}else E("dns","Could not start DNS server - custom domains may not resolve",Y)}let T=async()=>{E("cleanup","Starting cleanup handler",w.verbose);try{let{tearDownDevelopmentDns:N}=await Promise.resolve().then(() => (b1(),GX));await N({verbose:w.verbose})}catch(N){E("cleanup",`Error stopping DNS server: ${N}`,w.verbose)}try{await hX.stopAll(w.verbose)}catch(N){E("cleanup",`Error stopping processes: ${N}`,w.verbose)}await QX({domains:W,hosts:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.hosts,certs:typeof w.cleanup==="boolean"?w.cleanup:w.cleanup?.certs,verbose:w.verbose||!1})};A0.on("SIGINT",T),A0.on("SIGTERM",T);let K=w.singlePortMode===!0,H=w.httpsPort??443,q=w.httpPort??80,M=w.originGuard?QF(w.originGuard):null,I=!!f&&(J.length>1||K),h=!f&&K&&J.length>0;if(I&&f){E("proxies",`Creating shared HTTPS server for ${J.length} domains on port ${H}`,Y);let N=await OF(J,A,Y);if(!await Iw(q,"0.0.0.0",Y))DF(Y,q,H);if(await Iw(H,"0.0.0.0",Y)){if(E("proxies",`Port ${H} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${H} is in use. Shared HTTPS proxy cannot start.`);return}if(!TW({routeEntries:N,listenPort:H,sslConfig:f,originGuard:M,verbose:Y})){R.error(`Shared HTTPS proxy failed to bind :${H}; not exiting`);return}}else if(h){E("proxies",`Creating shared HTTP server for ${J.length} domains on port ${q}`,Y);let N=await OF(J,A,Y);if(await Iw(q,"0.0.0.0",Y)){if(E("proxies",`Port ${q} is already in use, cannot start shared proxy`,Y),Y)R.warn(`Port ${q} is in use. Shared HTTP proxy cannot start.`);return}if(!TW({routeEntries:N,listenPort:q,sslConfig:null,originGuard:M,verbose:Y})){R.error(`Shared HTTP proxy failed to bind :${q}; not exiting`);return}}else for(let N of J)try{let C=N.to||"rpx.localhost";E("proxy",`Starting proxy for ${C} with SSL config: ${!!f}`,N.verbose),await kF({from:N.from||"localhost:5173",to:C,cleanUrls:N.cleanUrls||!1,https:N.https||!1,cleanup:N.cleanup||!1,vitePluginUsage:N.vitePluginUsage||!1,verbose:N.verbose||!1,_cachedSSLConfig:w._cachedSSLConfig,changeOrigin:N.changeOrigin||!1})}catch(C){E("proxies",`Failed to start proxy for ${N.to}: ${C}`,N.verbose),R.error(`Failed to start proxy for ${N.to}:`,C)}}async function OF($,w,Y){let A=[],U=new Set;for(let X of $){let J=X.to||"rpx.localhost",W=X.cleanUrls||!1,f=X.path,B=k1(f);if(X.static)A.push({host:J,path:f,route:{static:NY(X.static,W),cleanUrls:W,basePath:B}}),E("proxies",`Route: ${J}${f??""} → static ${typeof X.static==="string"?X.static:X.static.dir}`,Y);else{let j=new URL(X.from?.startsWith("http")?X.from:`http://${X.from}`);A.push({host:J,path:f,route:{sourceHost:j.host,cleanUrls:W,changeOrigin:X.changeOrigin||!1,pathRewrites:X.pathRewrites,basePath:B}}),E("proxies",`Route: ${J}${f??""} → ${j.host}`,Y)}if(U.has(J))continue;if(U.add(J),w&&!RY(J)&&!J.includes("localhost")&&!J.includes("127.0.0.1"))try{if(!(await kY([J],Y))[0])await _Y([J],Y)}catch{E("hosts",`Could not add hosts entry for ${J}`,Y)}}return A}function TW($){let{routeEntries:w,listenPort:Y,sslConfig:A,originGuard:U,verbose:X}=$,J=D1(w),W=S1((j,z)=>Z1(J,j,z),X),f=U?(j,z)=>U(j)??W(j,z):W,B=_1(X);try{let j=Bun.serve({port:Y,hostname:"0.0.0.0",reusePort:C1(),...A?{tls:Array.isArray(A)?A.map((z)=>({serverName:z.serverName,key:z.key,cert:z.cert})):{key:A.key,cert:A.cert,ca:A.ca,requestCert:!1,rejectUnauthorized:!1}}:{},fetch(z,G){return f(z,G)},websocket:B,error(z){return E("server",`Shared proxy server error: ${z}`,X),new Response(`Server Error: ${z.message}`,{status:500})}});return VX.add(j),E("proxies",`Shared ${A?"HTTPS":"HTTP"} proxy listening on port ${Y} for ${J.size} domains`,X),j}catch(j){return E("proxies",`Failed to start shared proxy: ${j}`,X),console.error("Failed to start shared proxy:",j),null}}function $R($){if($?.vitePluginUsage||!$?.verbose)return;if(console.log(""),console.log(` ${y$.green(y$.bold("rpx"))} ${y$.green(`v${rq}`)}`),console.log(` ${y$.green("➜")} ${y$.dim($?.from??"")} ${y$.dim("➜")} ${y$.cyan($?.ssl?`https://${$?.to}`:`http://${$?.to}`)}`),$?.listenPort!==($?.ssl?443:80))console.log(` ${y$.green("➜")} Listening on port ${$?.listenPort}`);if($?.cleanUrls)console.log(` ${y$.green("➜")} Clean URLs enabled`)}yf();var IL=new Ow("rpx",{showTags:!1});function PF($){return!!($&&("proxies"in $)&&Array.isArray($.proxies))}n0.chdir(YR(wR(AR(import.meta.url)),".."));var r0=new bX("rpx"),bF="0.12.0";r0.command("start","Start the Reverse Proxy Server").option("--from <from>","The URL to proxy from").option("--to <to>","The URL to proxy to").option("--key-path <path>","Absolute path to the SSL key").option("--cert-path <path>","Absolute path to the SSL certificate").option("--ca-cert-path <path>","Absolute path to the SSL CA certificate").option("--hosts-cleanup","Cleanup /etc/hosts on exit").option("--certs-cleanup","Cleanup SSL certificates on exit").option("--start-command <command>","Command to start the dev server").option("--start-cwd <path>","Current working directory for the dev server").option("--start-env <env>","Environment variables for the dev server").option("--change-origin","Change the origin of the host header to the target URL").option("--single-port-mode","Route all proxies through one shared listener (by Host header) instead of a port per proxy").option("--http-port <port>","Port for the shared HTTP listener / redirect (default: 80)").option("--https-port <port>","Port for the shared HTTPS listener (default: 443)").option("--via-daemon","Route through the shared rpx daemon instead of binding :443 directly").option("--id <id>","Stable id used when registering with the daemon (auto-derived from --to)").option("--verbose","Enable verbose logging").example("rpx start --from localhost:5173 --to my-project.localhost").example("rpx start --from localhost:3000 --to my-project.localhost/api").example("rpx start --from localhost:3000 --to localhost:3001").example("rpx start --from localhost:5173 --to my-project.test --key-path /absolute/path/to/key --cert-path /absolute/path/to/cert").example("rpx start --from localhost:5173 --to my-project.localhost --change-origin").example("rpx start --single-port-mode --https-port 8443").action(async($)=>{if(!$?.from||!$.to)return xF(sw);let w={from:$.from,to:$.to,https:{keyPath:$.keyPath,certPath:$.certPath,caCertPath:$.caCertPath},cleanup:{certs:$.certsCleanup||!1,hosts:$.hostsCleanup||!1},verbose:$.verbose||!1,changeOrigin:$.changeOrigin||!1,singlePortMode:$.singlePortMode||!1,httpPort:$.httpPort!==void 0?Number($.httpPort):void 0,httpsPort:$.httpsPort!==void 0?Number($.httpsPort):void 0,viaDaemon:$.viaDaemon||!1,id:$.id};if($.startCommand){let Y={command:$.startCommand};if($.startCwd)Y.cwd=$.startCwd;if($.startEnv)try{Y.env=JSON.parse($.startEnv)}catch(A){console.error("Failed to parse start-env JSON:",A),n0.exit(1)}w.start=Y}return ZF(w)});r0.command("watch:start <proxy>","Start the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{let Y=PF(sw)?sw.proxies.find((A)=>A.to===$||`${A.from}-${A.to}`===$):sw.to===$?sw:null;if(!Y?.start)console.error(`No watch configuration found for proxy: ${$}`),n0.exit(1);try{await TX.startProcess($,Y.start,w.verbose),console.log(`Started dev server for ${$}`)}catch(A){console.error(`Failed to start dev server for ${$}:`,A),n0.exit(1)}});r0.command("watch:stop <proxy>","Stop the dev server for a specific proxy").option("--verbose","Enable verbose logging").action(async($,w)=>{try{await TX.stopProcess($,w.verbose),console.log(`Stopped dev server for ${$}`)}catch(Y){console.error(`Failed to stop dev server for ${$}:`,Y),n0.exit(1)}});r0.command("watch:stopall","Stop all running dev servers").option("--verbose","Enable verbose logging").action(async($)=>{try{await TX.stopAll($.verbose),console.log("Stopped all dev servers")}catch(w){console.error("Failed to stop all dev servers:",w),n0.exit(1)}});r0.command("daemon:start","Start the rpx daemon in the foreground (binds :443 + :80)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--https-port <port>","HTTPS port (default 443)",{default:443}).option("--http-port <port>","HTTP redirect port; 0 to disable (default 80)",{default:80}).option("--hostname <host>","Bind address (default 0.0.0.0)",{default:"0.0.0.0"}).option("--certs-dir <path>","Directory of real PEM certs for per-domain SNI (<domain>.crt/.key, _wildcard.<apex>.crt/.key)").option("--workers <n>","Run as a multi-core cluster of N worker processes (default 1; also RPX_WORKERS)").option("--verbose","Enable verbose logging").action(async($)=>{try{await(await GF({rpxDir:$.rpxDir,registryDir:$.registryDir,httpsPort:typeof $.httpsPort==="string"?Number.parseInt($.httpsPort,10):$.httpsPort,httpPort:typeof $.httpPort==="string"?Number.parseInt($.httpPort,10):$.httpPort,hostname:$.hostname,productionCerts:$.certsDir?{certsDir:$.certsDir}:void 0,workers:$.workers===void 0?void 0:typeof $.workers==="string"?Number.parseInt($.workers,10):$.workers,verbose:$.verbose??!0})).done,n0.exit(0)}catch(w){console.error(`Failed to start rpx daemon: ${w.message}`),n0.exit(1)}});r0.command("daemon:stop","Stop the running rpx daemon (SIGTERM, escalates to SIGKILL)").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--timeout <ms>","Max ms to wait for graceful shutdown",{default:5000}).option("--no-force","Do not escalate to SIGKILL after timeout").option("--verbose","Enable verbose logging").action(async($)=>{let w=typeof $.timeout==="string"?Number.parseInt($.timeout,10):$.timeout,Y=await KF({rpxDir:$.rpxDir,timeoutMs:w,forceAfterTimeout:$.force!==!1,verbose:$.verbose});if(!Y.stopped&&Y.pid===null){console.log("rpx daemon is not running");return}if(!Y.stopped){console.log(`rpx daemon pid=${Y.pid} was already gone (cleaned stale lock)`);return}console.log(`rpx daemon pid=${Y.pid} stopped${Y.forced?" (SIGKILL)":""}`)});r0.command("daemon:status","Print daemon state and currently registered hosts").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--json","Emit machine-readable JSON instead of a human summary").action(async($)=>{let w=$.rpxDir??j$(),Y=await Rw(w),A=await EX(w),U=$.registryDir,X=await MF(U).catch(()=>[]);if($.json){console.log(JSON.stringify({running:A,pid:Y,pidFile:Mw(w),rpxDir:w,registryDir:U??Zw(),entries:X},null,2));return}if(!A){if(console.log("rpx daemon: not running"),Y!==null)console.log(`(stale pid file at ${Mw(w)} \u2192 pid ${Y})`)}else console.log(`rpx daemon: running (pid=${Y})`),console.log(`pid file: ${Mw(w)}`);if(console.log(`registry: ${U??Zw()}`),X.length===0){console.log("no registered hosts");return}console.log(`registered hosts (${X.length}):`);for(let J of X){let W=J.pid!==void 0?`, pid=${J.pid}`:"";console.log(` https://${J.to} \u2192 ${J.from} (id=${J.id}${W})`)}});r0.command("register","Register an upstream app with the rpx daemon").option("--id <id>","Unique id for this entry (a-z, 0-9, dot, dash, underscore)").option("--from <host:port>","Upstream host:port (e.g. localhost:5173)").option("--to <host>","Public hostname (e.g. pet-store.localhost)").option("--cwd <path>","Working directory of the upstream (informational)").option("--clean-urls","Strip .html and 301 to the clean URL").option("--change-origin","Rewrite Origin to the upstream").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--registry-dir <path>","Override the registry dir (default <rpx-dir>/registry.d)").option("--skip-spawn","Do not lazy-spawn the daemon if it is not already running").option("--verbose","Enable verbose logging").example("rpx register --id pet-store --from localhost:5173 --to pet-store.localhost").action(async($)=>{if(!$.id||!$.from||!$.to)console.error("rpx register requires --id, --from, and --to"),n0.exit(1);if(!c1($.id))console.error(`invalid id: ${JSON.stringify($.id)} (must match /^[a-zA-Z0-9._-]+$/, \u2264128 chars)`),n0.exit(1);try{await qF({id:$.id,from:$.from,to:$.to,cwd:$.cwd,createdAt:new Date().toISOString(),cleanUrls:$.cleanUrls,changeOrigin:$.changeOrigin},$.registryDir,$.verbose)}catch(w){console.error(`failed to write registry entry: ${w.message}`),n0.exit(1)}if($.skipSpawn){console.log(`registered ${$.to} \u2192 ${$.from} (daemon spawn skipped)`);return}try{let w=await EF({rpxDir:$.rpxDir,verbose:$.verbose}),Y=w.spawned?"spawned":"attached to";console.log(`registered https://${$.to} \u2192 ${$.from} (${Y} daemon pid=${w.pid})`)}catch(w){console.error(`registered entry but daemon spawn failed: ${w.message}`),console.error("the entry remains in the registry; start the daemon manually with `rpx daemon:start`"),n0.exit(1)}});r0.command("unregister <id>","Remove a previously registered app from the rpx daemon").option("--registry-dir <path>","Override the registry dir (default ~/.stacks/rpx/registry.d)").option("--verbose","Enable verbose logging").action(async($,w)=>{if(!c1($))console.error(`invalid id: ${JSON.stringify($)}`),n0.exit(1);let Y=await BW($,w.registryDir,w.verbose);if(!Y){console.log(`no registry entry for id=${$}`);return}await RF($,w.registryDir,w.verbose),console.log(`unregistered ${Y.to} (id=${$})`)});r0.command("dns:reconcile","Remove stale macOS DNS overrides left by crashed dev sessions").option("--rpx-dir <path>","Override the rpx state dir (default ~/.stacks/rpx)").option("--verbose","Enable verbose logging").action(async($)=>{let w=$.rpxDir??j$();if(await EX(w)){console.log("rpx daemon is running \u2014 DNS overrides are managed by the daemon");return}await TF({rpxDir:w,verbose:$.verbose}),console.log("DNS reconcile complete")});r0.command("version","Show the version of the Reverse Proxy CLI").action(()=>{console.log(bF)});r0.version(bF);r0.help();r0.run();